TextPage.vue 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292
  1. <template>
  2. <div ref="main" class="main">
  3. <div class="layout back" @wheel.prevent.stop="onMouseWheel">
  4. <div v-html="background"></div>
  5. <!-- img -->
  6. </div>
  7. <div ref="scrollBox1" class="layout over-hidden" @wheel.prevent.stop="onMouseWheel">
  8. <div ref="scrollingPage1" class="layout over-hidden" @transitionend="onPage1TransitionEnd" @animationend="onPage1AnimationEnd">
  9. <div v-html="page1"></div>
  10. </div>
  11. </div>
  12. <div ref="scrollBox2" class="layout over-hidden" @wheel.prevent.stop="onMouseWheel">
  13. <div ref="scrollingPage2" class="layout over-hidden" @transitionend="onPage2TransitionEnd" @animationend="onPage2AnimationEnd">
  14. <div v-html="page2"></div>
  15. </div>
  16. </div>
  17. <div v-show="showStatusBar" ref="statusBar" class="layout">
  18. <div v-html="statusBar"></div>
  19. </div>
  20. <div v-show="clickControl" ref="layoutEvents" class="layout events" @mousedown.prevent.stop="onMouseDown" @mouseup.prevent.stop="onMouseUp"
  21. @wheel.prevent.stop="onMouseWheel"
  22. @touchstart.stop="onTouchStart" @touchend.stop="onTouchEnd" @touchmove.stop="onTouchMove" @touchcancel.prevent.stop="onTouchCancel"
  23. oncontextmenu="return false;">
  24. <div v-show="showStatusBar" v-html="statusBarClickable" @mousedown.prevent.stop @touchstart.stop
  25. @click.prevent.stop="onStatusBarClick"></div>
  26. </div>
  27. <div v-show="!clickControl && showStatusBar" class="layout" v-html="statusBarClickable" @mousedown.prevent.stop @touchstart.stop
  28. @click.prevent.stop="onStatusBarClick"></div>
  29. <!-- невидимым делать нельзя, вовремя не подгружаютя шрифты -->
  30. <canvas ref="offscreenCanvas" class="layout" style="visibility: hidden"></canvas>
  31. <div ref="measureWidth" style="position: absolute; visibility: hidden"></div>
  32. </div>
  33. </template>
  34. <script>
  35. //-----------------------------------------------------------------------------
  36. import Vue from 'vue';
  37. import Component from 'vue-class-component';
  38. import {loadCSS} from 'fg-loadcss';
  39. import _ from 'lodash';
  40. import {sleep} from '../../../share/utils';
  41. import bookManager from '../share/bookManager';
  42. import DrawHelper from './DrawHelper';
  43. import rstore from '../../../store/modules/reader';
  44. import {clickMap} from '../share/clickMap';
  45. const minLayoutWidth = 100;
  46. export default @Component({
  47. watch: {
  48. bookPos: function() {
  49. this.$emit('book-pos-changed', {bookPos: this.bookPos, bookPosSeen: this.bookPosSeen});
  50. this.draw();
  51. },
  52. bookPosSeen: function() {
  53. this.$emit('book-pos-changed', {bookPos: this.bookPos, bookPosSeen: this.bookPosSeen});
  54. },
  55. settings: function() {
  56. this.debouncedLoadSettings();
  57. },
  58. toggleLayout: function() {
  59. this.updateLayout();
  60. },
  61. inAnimation: function() {
  62. this.updateLayout();
  63. },
  64. },
  65. })
  66. class TextPage extends Vue {
  67. toggleLayout = false;
  68. showStatusBar = false;
  69. clickControl = true;
  70. background = null;
  71. page1 = null;
  72. page2 = null;
  73. statusBar = null;
  74. statusBarClickable = null;
  75. lastBook = null;
  76. bookPos = 0;
  77. bookPosSeen = null;
  78. fontStyle = null;
  79. fontSize = null;
  80. fontName = null;
  81. fontWeight = null;
  82. inAnimation = false;
  83. meta = null;
  84. created() {
  85. this.drawHelper = new DrawHelper();
  86. this.commit = this.$store.commit;
  87. this.dispatch = this.$store.dispatch;
  88. this.config = this.$store.state.config;
  89. this.reader = this.$store.state.reader;
  90. this.debouncedStartClickRepeat = _.debounce((x, y) => {
  91. this.startClickRepeat(x, y);
  92. }, 800);
  93. this.debouncedPrepareNextPage = _.debounce(() => {
  94. this.prepareNextPage();
  95. }, 100);
  96. this.debouncedDrawStatusBar = _.throttle(() => {
  97. this.drawStatusBar();
  98. }, 60);
  99. this.debouncedLoadSettings = _.debounce(() => {
  100. this.loadSettings();
  101. }, 50);
  102. this.debouncedUpdatePage = _.debounce(async(lines) => {
  103. if (!this.pageChangeAnimation)
  104. this.toggleLayout = !this.toggleLayout;
  105. else {
  106. this.page2 = this.page1;
  107. this.toggleLayout = true;
  108. }
  109. if (this.toggleLayout)
  110. this.page1 = this.drawHelper.drawPage(lines);
  111. else
  112. this.page2 = this.drawHelper.drawPage(lines);
  113. await this.doPageAnimation();
  114. }, 10);
  115. this.$root.$on('resize', () => {this.$nextTick(this.onResize)});
  116. }
  117. mounted() {
  118. this.context = this.$refs.offscreenCanvas.getContext('2d');
  119. }
  120. hex2rgba(hex, alpha = 1) {
  121. const [r, g, b] = hex.match(/\w\w/g).map(x => parseInt(x, 16));
  122. return `rgba(${r},${g},${b},${alpha})`;
  123. }
  124. calcDrawProps() {
  125. const wideLetter = 'Щ';
  126. //preloaded fonts
  127. this.fontList = [`12px ${this.fontName}`];
  128. //widths
  129. this.realWidth = this.$refs.main.clientWidth;
  130. this.realHeight = this.$refs.main.clientHeight;
  131. this.$refs.layoutEvents.style.width = this.realWidth + 'px';
  132. this.$refs.layoutEvents.style.height = this.realHeight + 'px';
  133. this.w = this.realWidth - 2*this.indentLR;
  134. this.scrollHeight = this.realHeight - (this.showStatusBar ? this.statusBarHeight : 0);
  135. this.h = this.scrollHeight - 2*this.indentTB;
  136. this.lineHeight = this.fontSize + this.lineInterval;
  137. this.pageLineCount = 1 + Math.floor((this.h - this.lineHeight + this.lineInterval/2)/this.lineHeight);
  138. this.$refs.scrollingPage1.style.width = this.w + 'px';
  139. this.$refs.scrollingPage2.style.width = this.w + 'px';
  140. //stuff
  141. this.currentAnimation = '';
  142. this.pageChangeDirectionDown = true;
  143. this.fontShift = this.fontVertShift/100;
  144. this.textShift = this.textVertShift/100 + this.fontShift;
  145. //statusBar
  146. this.$refs.statusBar.style.left = '0px';
  147. this.$refs.statusBar.style.top = (this.statusBarTop ? 1 : this.realHeight - this.statusBarHeight) + 'px';
  148. this.statusBarColor = this.hex2rgba(this.textColor || '#000000', this.statusBarColorAlpha);
  149. //drawHelper
  150. this.drawHelper.realWidth = this.realWidth;
  151. this.drawHelper.realHeight = this.realHeight;
  152. this.drawHelper.lastBook = this.lastBook;
  153. this.drawHelper.book = this.book;
  154. this.drawHelper.parsed = this.parsed;
  155. this.drawHelper.pageLineCount = this.pageLineCount;
  156. this.drawHelper.backgroundColor = this.backgroundColor;
  157. this.drawHelper.statusBarColor = this.statusBarColor;
  158. this.drawHelper.fontStyle = this.fontStyle;
  159. this.drawHelper.fontWeight = this.fontWeight;
  160. this.drawHelper.fontSize = this.fontSize;
  161. this.drawHelper.fontName = this.fontName;
  162. this.drawHelper.fontShift = this.fontShift;
  163. this.drawHelper.textColor = this.textColor;
  164. this.drawHelper.textShift = this.textShift;
  165. this.drawHelper.p = this.p;
  166. this.drawHelper.w = this.w;
  167. this.drawHelper.h = this.h;
  168. this.drawHelper.indentLR = this.indentLR;
  169. this.drawHelper.textAlignJustify = this.textAlignJustify;
  170. this.drawHelper.lineHeight = this.lineHeight;
  171. this.drawHelper.context = this.context;
  172. //альтернатива context.measureText
  173. if (!this.context.measureText(wideLetter).width) {
  174. const ctx = this.$refs.measureWidth;
  175. this.drawHelper.measureText = function(text, style) {
  176. ctx.innerText = text;
  177. ctx.style.font = this.fontByStyle(style);
  178. return ctx.clientWidth;
  179. };
  180. this.drawHelper.measureTextFont = function(text, font) {
  181. ctx.innerText = text;
  182. ctx.style.font = font;
  183. return ctx.clientWidth;
  184. }
  185. }
  186. //statusBar
  187. this.statusBarClickable = this.drawHelper.statusBarClickable(this.statusBarTop, this.statusBarHeight);
  188. //parsed
  189. if (this.parsed) {
  190. this.parsed.p = this.p;
  191. this.parsed.w = this.w;// px, ширина текста
  192. this.parsed.font = this.font;
  193. this.parsed.fontSize = this.fontSize;
  194. this.parsed.wordWrap = this.wordWrap;
  195. this.parsed.cutEmptyParagraphs = this.cutEmptyParagraphs;
  196. this.parsed.addEmptyParagraphs = this.addEmptyParagraphs;
  197. let t = wideLetter;
  198. if (!this.drawHelper.measureText(t, {}))
  199. throw new Error('Ошибка measureText');
  200. while (this.drawHelper.measureText(t, {}) < this.w) t += wideLetter;
  201. this.parsed.maxWordLength = t.length - 1;
  202. this.parsed.measureText = this.drawHelper.measureText.bind(this.drawHelper);
  203. this.parsed.lineHeight = this.lineHeight;
  204. this.parsed.showImages = this.showImages;
  205. this.parsed.showInlineImagesInCenter = this.showInlineImagesInCenter;
  206. this.parsed.imageHeightLines = this.imageHeightLines;
  207. this.parsed.imageFitWidth = this.imageFitWidth;
  208. this.parsed.compactTextPerc = this.compactTextPerc;
  209. }
  210. //scrolling page
  211. const pageSpace = this.scrollHeight - this.pageLineCount*this.lineHeight;
  212. let top = pageSpace/2;
  213. if (this.showStatusBar)
  214. top += this.statusBarHeight*(this.statusBarTop ? 1 : 0);
  215. let page1 = this.$refs.scrollBox1.style;
  216. let page2 = this.$refs.scrollBox2.style;
  217. page1.perspective = page2.perspective = '3072px';
  218. page1.width = page2.width = this.w + this.indentLR + 'px';
  219. page1.height = page2.height = this.scrollHeight - (pageSpace > 0 ? pageSpace : 0) + 'px';
  220. page1.top = page2.top = top + 'px';
  221. page1.left = page2.left = this.indentLR + 'px';
  222. page1 = this.$refs.scrollingPage1.style;
  223. page2 = this.$refs.scrollingPage2.style;
  224. page1.width = page2.width = this.w + this.indentLR + 'px';
  225. page1.height = page2.height = this.scrollHeight + this.lineHeight + 'px';
  226. }
  227. async checkLoadedFonts() {
  228. let loaded = await Promise.all(this.fontList.map(font => document.fonts.check(font)));
  229. if (loaded.some(r => !r)) {
  230. loaded = await Promise.all(this.fontList.map(font => document.fonts.load(font)));
  231. if (loaded.some(r => !r.length))
  232. throw new Error('some font not loaded');
  233. }
  234. }
  235. async loadFonts() {
  236. this.fontsLoading = true;
  237. let inst = null;
  238. (async() => {
  239. await sleep(500);
  240. if (this.fontsLoading)
  241. inst = this.$notify({
  242. title: '',
  243. dangerouslyUseHTMLString: true,
  244. message: 'Загрузка шрифта &nbsp;<i class="el-icon-loading"></i>',
  245. duration: 0
  246. });
  247. })();
  248. if (!this.fontsLoaded)
  249. this.fontsLoaded = {};
  250. //загрузка дин.шрифта
  251. const loaded = this.fontsLoaded[this.fontCssUrl];
  252. if (this.fontCssUrl && !loaded) {
  253. loadCSS(this.fontCssUrl);
  254. this.fontsLoaded[this.fontCssUrl] = 1;
  255. }
  256. const waitingTime = 10*1000;
  257. const delay = 100;
  258. let i = 0;
  259. //ждем шрифты
  260. while (i < waitingTime/delay) {
  261. i++;
  262. try {
  263. await this.checkLoadedFonts();
  264. i = waitingTime;
  265. } catch (e) {
  266. await sleep(delay);
  267. }
  268. }
  269. if (i !== waitingTime) {
  270. this.$notify.error({
  271. title: 'Ошибка загрузки',
  272. message: 'Некоторые шрифты не удалось загрузить'
  273. });
  274. }
  275. this.fontsLoading = false;
  276. if (inst)
  277. inst.close();
  278. }
  279. getSettings() {
  280. const settings = this.settings;
  281. for (let prop in rstore.settingDefaults) {
  282. this[prop] = settings[prop];
  283. }
  284. const wf = this.webFontName;
  285. const i = _.findIndex(rstore.webFonts, ['name', wf]);
  286. if (wf && i >= 0) {
  287. this.fontName = wf;
  288. this.fontCssUrl = rstore.webFonts[i].css;
  289. this.fontVertShift = settings.fontShifts[wf] || 0;
  290. }
  291. }
  292. async calcPropsAndLoadFonts(omitLoadFonts) {
  293. this.calcDrawProps();
  294. this.setBackground();
  295. if (!omitLoadFonts)
  296. await this.loadFonts();
  297. this.draw();
  298. // ширина шрифта некоторое время выдается неверно, поэтому
  299. if (!omitLoadFonts) {
  300. const parsed = this.parsed;
  301. await sleep(100);
  302. if (this.parsed === parsed) {
  303. parsed.force = true;
  304. this.draw();
  305. parsed.force = false;
  306. }
  307. }
  308. }
  309. loadSettings() {
  310. (async() => {
  311. let fontName = this.fontName;
  312. this.getSettings();
  313. await this.calcPropsAndLoadFonts(fontName == this.fontName);
  314. })();
  315. }
  316. showBook() {
  317. this.$refs.main.focus();
  318. this.toggleLayout = false;
  319. this.updateLayout();
  320. this.book = null;
  321. this.meta = null;
  322. this.fb2 = null;
  323. this.parsed = null;
  324. this.linesUp = null;
  325. this.linesDown = null;
  326. this.statusBarMessage = '';
  327. this.getSettings();
  328. this.calcDrawProps();
  329. this.draw();// пока не загрузили, очистим канвас
  330. if (this.lastBook) {
  331. (async() => {
  332. try {
  333. //подождем ленивый парсинг
  334. this.stopLazyParse = true;
  335. while (this.doingLazyParse) await sleep(10);
  336. const isParsed = await bookManager.hasBookParsed(this.lastBook);
  337. if (!isParsed) {
  338. return;
  339. }
  340. this.book = await bookManager.getBook(this.lastBook);
  341. this.meta = bookManager.metaOnly(this.book);
  342. this.fb2 = this.meta.fb2;
  343. let authorNames = [];
  344. if (this.fb2.author) {
  345. authorNames = this.fb2.author.map(a => _.compact([
  346. a.lastName,
  347. a.firstName,
  348. a.middleName
  349. ]).join(' '));
  350. }
  351. this.title = _.compact([
  352. authorNames.join(', '),
  353. this.fb2.bookTitle
  354. ]).join(' - ');
  355. this.$root.$emit('set-app-title', this.title);
  356. this.parsed = this.book.parsed;
  357. this.page1 = null;
  358. this.page2 = null;
  359. this.statusBar = null;
  360. await this.stopTextScrolling();
  361. await this.calcPropsAndLoadFonts();
  362. this.refreshTime();
  363. if (this.lazyParseEnabled)
  364. this.lazyParsePara();
  365. } catch (e) {
  366. this.$alert(e.message, 'Ошибка', {type: 'error'});
  367. }
  368. })();
  369. }
  370. }
  371. updateLayout() {
  372. if (this.inAnimation) {
  373. this.$refs.scrollBox1.style.visibility = 'visible';
  374. this.$refs.scrollBox2.style.visibility = 'visible';
  375. } else if (this.toggleLayout) {
  376. this.$refs.scrollBox1.style.visibility = 'visible';
  377. this.$refs.scrollBox2.style.visibility = 'hidden';
  378. } else {
  379. this.$refs.scrollBox1.style.visibility = 'hidden';
  380. this.$refs.scrollBox2.style.visibility = 'visible';
  381. }
  382. }
  383. setBackground() {
  384. this.background = `<div class="layout ${this.wallpaper}" style="width: ${this.realWidth}px; height: ${this.realHeight}px;` +
  385. ` background-color: ${this.backgroundColor}"></div>`;
  386. }
  387. async onResize() {
  388. /*this.page1 = null;
  389. this.page2 = null;
  390. this.statusBar = null;*/
  391. try {
  392. this.calcDrawProps();
  393. this.setBackground();
  394. this.draw();
  395. } catch (e) {
  396. //
  397. }
  398. }
  399. get settings() {
  400. return this.$store.state.reader.settings;
  401. }
  402. get font() {
  403. return `${this.fontStyle} ${this.fontWeight} ${this.fontSize}px ${this.fontName}`;
  404. }
  405. onPage1TransitionEnd() {
  406. if (this.resolveTransition1Finish)
  407. this.resolveTransition1Finish();
  408. }
  409. onPage2TransitionEnd() {
  410. if (this.resolveTransition2Finish)
  411. this.resolveTransition2Finish();
  412. }
  413. startSearch(needle) {
  414. this.drawHelper.needle = needle;
  415. this.drawHelper.searching = true;
  416. this.draw();
  417. }
  418. stopSearch() {
  419. this.drawHelper.searching = false;
  420. this.draw();
  421. }
  422. generateWaitingFunc(waitingHandlerName, stopPropertyName) {
  423. const func = (timeout) => {
  424. return new Promise((resolve, reject) => { (async() => {
  425. this[waitingHandlerName] = resolve;
  426. let wait = (timeout + 201)/100;
  427. while (wait > 0 && !this[stopPropertyName]) {
  428. wait--;
  429. await sleep(100);
  430. }
  431. resolve();
  432. })().catch(reject); });
  433. };
  434. return func;
  435. }
  436. async startTextScrolling() {
  437. if (this.doingScrolling || !this.book || !this.parsed.textLength || !this.linesDown || this.pageLineCount < 1 ||
  438. this.linesDown.length <= this.pageLineCount) {
  439. this.$emit('stop-scrolling');
  440. return;
  441. }
  442. //ждем анимацию
  443. while (this.inAnimation) await sleep(10);
  444. this.stopScrolling = false;
  445. this.doingScrolling = true;
  446. const transitionFinish = this.generateWaitingFunc('resolveTransition1Finish', 'stopScrolling');
  447. if (!this.toggleLayout)
  448. this.page1 = this.page2;
  449. this.toggleLayout = true;
  450. await this.$nextTick();
  451. await sleep(50);
  452. this.cachedPos = -1;
  453. this.draw();
  454. const page = this.$refs.scrollingPage1;
  455. let i = 0;
  456. while (!this.stopScrolling) {
  457. page.style.transition = `${this.scrollingDelay}ms ${this.scrollingType}`;
  458. page.style.transform = `translateY(-${this.lineHeight}px)`;
  459. if (i > 0) {
  460. this.doDown();
  461. if (this.linesDown.length <= this.pageLineCount + 1) {
  462. this.stopScrolling = true;
  463. }
  464. }
  465. await transitionFinish(this.scrollingDelay);
  466. page.style.transition = '';
  467. page.style.transform = 'none';
  468. page.offsetHeight;
  469. i++;
  470. }
  471. this.resolveTransition1Finish = null;
  472. this.doingScrolling = false;
  473. this.$emit('stop-scrolling');
  474. this.draw();
  475. }
  476. async stopTextScrolling() {
  477. this.stopScrolling = true;
  478. const page = this.$refs.scrollingPage1;
  479. page.style.transition = '';
  480. page.style.transform = 'none';
  481. page.offsetHeight;
  482. while (this.doingScrolling) await sleep(10);
  483. }
  484. draw() {
  485. //scrolling
  486. if (this.doingScrolling) {
  487. this.currentAnimation = '';
  488. if (this.cachedPos == this.bookPos) {
  489. this.linesDown = this.linesCached.linesDown;
  490. this.linesUp = this.linesCached.linesUp;
  491. this.page1 = this.pageCached;
  492. } else {
  493. const lines = this.getLines(this.bookPos);
  494. this.linesDown = lines.linesDown;
  495. this.linesUp = lines.linesUp;
  496. this.page1 = this.drawHelper.drawPage(lines.linesDown, true);
  497. }
  498. //caching next
  499. if (this.cachedPageTimer)
  500. clearTimeout(this.cachedPageTimer);
  501. this.cachedPageTimer = setTimeout(() => {
  502. if (this.linesDown && this.linesDown.length > this.pageLineCount && this.pageLineCount > 0) {
  503. this.cachedPos = this.linesDown[1].begin;
  504. this.linesCached = this.getLines(this.cachedPos);
  505. this.pageCached = this.drawHelper.drawPage(this.linesCached.linesDown, true);
  506. }
  507. this.cachedPageTimer = null;
  508. }, 20);
  509. this.debouncedDrawStatusBar();
  510. return;
  511. }
  512. //check
  513. if (this.w < minLayoutWidth) {
  514. this.page1 = null;
  515. this.page2 = null;
  516. this.statusBar = null;
  517. return;
  518. }
  519. if (this.book && this.bookPos > 0 && this.bookPos >= this.parsed.textLength) {
  520. this.doEnd(true);
  521. return;
  522. }
  523. //fast draw prepared
  524. if (!this.pageChangeAnimation && this.pageChangeDirectionDown && this.pagePrepared && this.bookPos == this.bookPosPrepared) {
  525. this.toggleLayout = !this.toggleLayout;
  526. this.linesDown = this.linesDownNext;
  527. this.linesUp = this.linesUpNext;
  528. } else {//normal debounced draw
  529. const lines = this.getLines(this.bookPos);
  530. this.linesDown = lines.linesDown;
  531. this.linesUp = lines.linesUp;
  532. this.debouncedUpdatePage(lines.linesDown);
  533. }
  534. this.pagePrepared = false;
  535. if (!this.pageChangeAnimation)
  536. this.debouncedPrepareNextPage();
  537. this.debouncedDrawStatusBar();
  538. if (this.book && this.linesDown && this.linesDown.length < this.pageLineCount) {
  539. this.doEnd(true);
  540. return;
  541. }
  542. }
  543. onPage1AnimationEnd() {
  544. if (this.resolveAnimation1Finish)
  545. this.resolveAnimation1Finish();
  546. }
  547. onPage2AnimationEnd() {
  548. if (this.resolveAnimation2Finish)
  549. this.resolveAnimation2Finish();
  550. }
  551. async doPageAnimation() {
  552. if (this.currentAnimation && !this.inAnimation) {
  553. this.inAnimation = true;
  554. const animation1Finish = this.generateWaitingFunc('resolveAnimation1Finish', 'stopAnimation');
  555. const animation2Finish = this.generateWaitingFunc('resolveAnimation2Finish', 'stopAnimation');
  556. const transition1Finish = this.generateWaitingFunc('resolveTransition1Finish', 'stopAnimation');
  557. const transition2Finish = this.generateWaitingFunc('resolveTransition2Finish', 'stopAnimation');
  558. const duration = Math.round(3000*(1 - this.pageChangeAnimationSpeed/100));
  559. let page1 = this.$refs.scrollingPage1;
  560. let page2 = this.$refs.scrollingPage2;
  561. switch (this.currentAnimation) {
  562. case 'thaw':
  563. await this.drawHelper.doPageAnimationThaw(page1, page2,
  564. duration, this.pageChangeDirectionDown, animation1Finish);
  565. break;
  566. case 'blink':
  567. await this.drawHelper.doPageAnimationBlink(page1, page2,
  568. duration, this.pageChangeDirectionDown, animation1Finish, animation2Finish);
  569. break;
  570. case 'rightShift':
  571. await this.drawHelper.doPageAnimationRightShift(page1, page2,
  572. duration, this.pageChangeDirectionDown, transition1Finish);
  573. break;
  574. case 'downShift':
  575. page1.style.height = this.scrollHeight + 'px';
  576. page2.style.height = this.scrollHeight + 'px';
  577. await this.drawHelper.doPageAnimationDownShift(page1, page2,
  578. duration, this.pageChangeDirectionDown, transition1Finish);
  579. page1.style.height = this.scrollHeight + this.lineHeight + 'px';
  580. page2.style.height = this.scrollHeight + this.lineHeight + 'px';
  581. break;
  582. case 'rotate':
  583. await this.drawHelper.doPageAnimationRotate(page1, page2,
  584. duration, this.pageChangeDirectionDown, transition1Finish, transition2Finish);
  585. break;
  586. case 'flip':
  587. await this.drawHelper.doPageAnimationFlip(page1, page2,
  588. duration, this.pageChangeDirectionDown, transition1Finish, transition2Finish, this.backgroundColor);
  589. break;
  590. }
  591. this.resolveAnimation1Finish = null;
  592. this.resolveAnimation2Finish = null;
  593. this.resolveTransition1Finish = null;
  594. this.resolveTransition2Finish = null;
  595. page1.style.animation = '';
  596. page2.style.animation = '';
  597. page1.style.transition = '';
  598. page1.style.transform = 'none';
  599. page1.offsetHeight;
  600. page2.style.transition = '';
  601. page2.style.transform = 'none';
  602. page2.offsetHeight;
  603. this.currentAnimation = '';
  604. this.pageChangeDirectionDown = false;//true только если PgDown
  605. this.inAnimation = false;
  606. this.stopAnimation = false;
  607. }
  608. }
  609. getLines(bookPos) {
  610. if (!this.parsed || this.pageLineCount < 1)
  611. return {};
  612. return {
  613. linesDown: this.parsed.getLines(bookPos, 2*this.pageLineCount),
  614. linesUp: this.parsed.getLines(bookPos, -2*this.pageLineCount)
  615. };
  616. }
  617. drawStatusBar(message) {
  618. if (this.w < minLayoutWidth) {
  619. this.statusBar = null;
  620. return;
  621. }
  622. if (this.showStatusBar && this.linesDown && this.pageLineCount > 0) {
  623. const lines = this.linesDown;
  624. let i = this.pageLineCount;
  625. if (this.keepLastToFirst)
  626. i--;
  627. i = (i > lines.length - 1 ? lines.length - 1 : i);
  628. if (i >= 0) {
  629. if (!message)
  630. message = this.statusBarMessage;
  631. if (!message)
  632. message = this.title;
  633. this.statusBar = this.drawHelper.drawStatusBar(this.statusBarTop, this.statusBarHeight,
  634. lines[i].end, this.parsed.textLength, message);
  635. this.bookPosSeen = lines[i].end;
  636. }
  637. } else {
  638. this.statusBar = '';
  639. }
  640. }
  641. blinkCachedLoadMessage(state) {
  642. if (state === 'finish') {
  643. this.statusBarMessage = '';
  644. } else if (state) {
  645. this.statusBarMessage = 'Книга загружена из кэша';
  646. } else {
  647. this.statusBarMessage = ' ';
  648. }
  649. this.drawStatusBar();
  650. }
  651. async lazyParsePara() {
  652. if (!this.parsed || this.doingLazyParse)
  653. return;
  654. this.doingLazyParse = true;
  655. let j = 0;
  656. let k = 0;
  657. let prevPerc = 0;
  658. this.stopLazyParse = false;
  659. for (let i = 0; i < this.parsed.para.length; i++) {
  660. j++;
  661. if (j > 1) {
  662. await sleep(1);
  663. j = 0;
  664. }
  665. if (this.stopLazyParse)
  666. break;
  667. this.parsed.parsePara(i);
  668. k++;
  669. if (k > 100) {
  670. let perc = Math.round(i/this.parsed.para.length*100);
  671. if (perc != prevPerc)
  672. this.drawStatusBar(`Обработка текста ${perc}%`);
  673. prevPerc = perc;
  674. k = 0;
  675. }
  676. }
  677. this.drawStatusBar();
  678. this.doingLazyParse = false;
  679. }
  680. async refreshTime() {
  681. if (!this.timeRefreshing) {
  682. this.timeRefreshing = true;
  683. await sleep(60*1000);
  684. if (this.book && this.parsed.textLength) {
  685. this.debouncedDrawStatusBar();
  686. }
  687. this.timeRefreshing = false;
  688. this.refreshTime();
  689. }
  690. }
  691. prepareNextPage() {
  692. // подготовка следующей страницы заранее
  693. if (!this.book || !this.parsed.textLength || !this.linesDown || this.pageLineCount < 1)
  694. return;
  695. let i = this.pageLineCount;
  696. if (this.keepLastToFirst)
  697. i--;
  698. if (i >= 0 && this.linesDown.length > i) {
  699. this.bookPosPrepared = this.linesDown[i].begin;
  700. const lines = this.getLines(this.bookPosPrepared);
  701. this.linesDownNext = lines.linesDown;
  702. this.linesUpNext = lines.linesUp;
  703. if (this.toggleLayout)
  704. this.page2 = this.drawHelper.drawPage(lines.linesDown);//наоборот
  705. else
  706. this.page1 = this.drawHelper.drawPage(lines.linesDown);
  707. this.pagePrepared = true;
  708. }
  709. }
  710. doDown() {
  711. if (this.linesDown && this.linesDown.length > this.pageLineCount && this.pageLineCount > 0) {
  712. this.bookPos = this.linesDown[1].begin;
  713. }
  714. }
  715. doUp() {
  716. if (this.linesUp && this.linesUp.length > 1 && this.pageLineCount > 0) {
  717. this.bookPos = this.linesUp[1].begin;
  718. }
  719. }
  720. doPageDown() {
  721. if (this.linesDown && this.pageLineCount > 0) {
  722. let i = this.pageLineCount;
  723. if (this.keepLastToFirst)
  724. i--;
  725. if (i >= 0 && this.linesDown.length >= 2*i) {
  726. this.currentAnimation = this.pageChangeAnimation;
  727. this.pageChangeDirectionDown = true;
  728. this.bookPos = this.linesDown[i].begin;
  729. } else
  730. this.doEnd();
  731. }
  732. }
  733. doPageUp() {
  734. if (this.linesUp && this.pageLineCount > 0) {
  735. let i = this.pageLineCount;
  736. if (this.keepLastToFirst)
  737. i--;
  738. i = (i > this.linesUp.length - 1 ? this.linesUp.length - 1 : i);
  739. if (i >= 0 && this.linesUp.length > i) {
  740. this.currentAnimation = this.pageChangeAnimation;
  741. this.pageChangeDirectionDown = false;
  742. this.bookPos = this.linesUp[i].begin;
  743. }
  744. }
  745. }
  746. doHome() {
  747. this.currentAnimation = this.pageChangeAnimation;
  748. this.pageChangeDirectionDown = false;
  749. this.bookPos = 0;
  750. }
  751. doEnd(noAni) {
  752. if (this.parsed.para.length && this.pageLineCount > 0) {
  753. let i = this.parsed.para.length - 1;
  754. let lastPos = this.parsed.para[i].offset + this.parsed.para[i].length - 1;
  755. const lines = this.parsed.getLines(lastPos, -this.pageLineCount);
  756. if (lines) {
  757. i = this.pageLineCount - 1;
  758. i = (i > lines.length - 1 ? lines.length - 1 : i);
  759. if (!noAni)
  760. this.currentAnimation = this.pageChangeAnimation;
  761. this.pageChangeDirectionDown = true;
  762. this.bookPos = lines[i].begin;
  763. }
  764. }
  765. }
  766. doToolBarToggle() {
  767. this.$emit('tool-bar-toggle');
  768. }
  769. doScrollingToggle() {
  770. this.$emit('scrolling-toggle');
  771. }
  772. doFullScreenToggle() {
  773. this.$emit('full-screen-toogle');
  774. }
  775. async doFontSizeInc() {
  776. if (!this.settingsChanging) {
  777. this.settingsChanging = true;
  778. const newSize = (this.settings.fontSize + 1 < 100 ? this.settings.fontSize + 1 : 100);
  779. const newSettings = Object.assign({}, this.settings, {fontSize: newSize});
  780. this.commit('reader/setSettings', newSettings);
  781. await sleep(50);
  782. this.settingsChanging = false;
  783. }
  784. }
  785. async doFontSizeDec() {
  786. if (!this.settingsChanging) {
  787. this.settingsChanging = true;
  788. const newSize = (this.settings.fontSize - 1 > 5 ? this.settings.fontSize - 1 : 5);
  789. const newSettings = Object.assign({}, this.settings, {fontSize: newSize});
  790. this.commit('reader/setSettings', newSettings);
  791. await sleep(50);
  792. this.settingsChanging = false;
  793. }
  794. }
  795. async doScrollingSpeedUp() {
  796. if (!this.settingsChanging) {
  797. this.settingsChanging = true;
  798. const newDelay = (this.settings.scrollingDelay - 50 > 1 ? this.settings.scrollingDelay - 50 : 1);
  799. const newSettings = Object.assign({}, this.settings, {scrollingDelay: newDelay});
  800. this.commit('reader/setSettings', newSettings);
  801. await sleep(50);
  802. this.settingsChanging = false;
  803. }
  804. }
  805. async doScrollingSpeedDown() {
  806. if (!this.settingsChanging) {
  807. this.settingsChanging = true;
  808. const newDelay = (this.settings.scrollingDelay + 50 < 10000 ? this.settings.scrollingDelay + 50 : 10000);
  809. const newSettings = Object.assign({}, this.settings, {scrollingDelay: newDelay});
  810. this.commit('reader/setSettings', newSettings);
  811. await sleep(50);
  812. this.settingsChanging = false;
  813. }
  814. }
  815. keyHook(event) {
  816. let result = false;
  817. if (event.type == 'keydown' && !event.ctrlKey && !event.altKey) {
  818. result = true;
  819. switch (event.code) {
  820. case 'ArrowDown':
  821. if (event.shiftKey)
  822. this.doScrollingSpeedUp();
  823. else
  824. this.doDown();
  825. break;
  826. case 'ArrowUp':
  827. if (event.shiftKey)
  828. this.doScrollingSpeedDown();
  829. else
  830. this.doUp();
  831. break;
  832. case 'PageDown':
  833. case 'ArrowRight':
  834. this.doPageDown();
  835. break;
  836. case 'Space':
  837. if (event.shiftKey)
  838. this.doPageUp();
  839. else
  840. this.doPageDown();
  841. break;
  842. case 'PageUp':
  843. case 'ArrowLeft':
  844. case 'Backspace':
  845. this.doPageUp();
  846. break;
  847. case 'Home':
  848. this.doHome();
  849. break;
  850. case 'End':
  851. this.doEnd();
  852. break;
  853. case 'KeyA':
  854. if (event.shiftKey)
  855. this.doFontSizeDec();
  856. else
  857. this.doFontSizeInc();
  858. break;
  859. case 'Enter':
  860. case 'Backquote'://`
  861. case 'KeyF':
  862. this.doFullScreenToggle();
  863. break;
  864. case 'Tab':
  865. case 'KeyQ':
  866. this.doToolBarToggle();
  867. event.preventDefault();
  868. event.stopPropagation();
  869. break;
  870. default:
  871. result = false;
  872. break;
  873. }
  874. }
  875. return result;
  876. }
  877. async startClickRepeat(pointX, pointY) {
  878. this.repX = pointX;
  879. this.repY = pointY;
  880. if (!this.repInit && this.repDoing) {
  881. this.repInit = true;
  882. let delay = 400;
  883. while (this.repDoing) {
  884. this.handleClick(pointX, pointY);
  885. await sleep(delay);
  886. if (delay > 15)
  887. delay *= 0.8;
  888. }
  889. this.repInit = false;
  890. }
  891. }
  892. endClickRepeat() {
  893. this.repDoing = false;
  894. }
  895. onTouchStart(event) {
  896. if (!this.$isMobileDevice)
  897. return;
  898. this.endClickRepeat();
  899. if (event.touches.length == 1) {
  900. const touch = event.touches[0];
  901. const rect = event.target.getBoundingClientRect();
  902. const x = touch.pageX - rect.left;
  903. const y = touch.pageY - rect.top;
  904. const hc = this.handleClick(x, y, new Set(['Menu']));
  905. if (hc) {
  906. if (hc != 'Menu') {
  907. this.repDoing = true;
  908. this.debouncedStartClickRepeat(x, y);
  909. } else {
  910. this.startTouch = {x, y};
  911. }
  912. }
  913. }
  914. }
  915. onTouchMove(event) {
  916. if (this.startTouch) {
  917. event.preventDefault();
  918. }
  919. }
  920. onTouchEnd(event) {
  921. if (!this.$isMobileDevice)
  922. return;
  923. this.endClickRepeat();
  924. if (event.changedTouches.length == 1) {
  925. const touch = event.changedTouches[0];
  926. const rect = event.target.getBoundingClientRect();
  927. const x = touch.pageX - rect.left;
  928. const y = touch.pageY - rect.top;
  929. if (this.startTouch) {
  930. const dy = this.startTouch.y - y;
  931. const dx = this.startTouch.x - x;
  932. const moveDelta = 30;
  933. const touchDelta = 15;
  934. if (dy > 0 && Math.abs(dy) >= moveDelta && Math.abs(dy) > Math.abs(dx)) {
  935. //движение вверх
  936. this.doFullScreenToggle();
  937. } else if (dy < 0 && Math.abs(dy) >= moveDelta && Math.abs(dy) > Math.abs(dx)) {
  938. //движение вниз
  939. this.doScrollingToggle();
  940. } else if (dx > 0 && Math.abs(dx) >= moveDelta && Math.abs(dy) < Math.abs(dx)) {
  941. //движение влево
  942. this.doScrollingSpeedDown();
  943. } else if (dx < 0 && Math.abs(dx) >= moveDelta && Math.abs(dy) < Math.abs(dx)) {
  944. //движение вправо
  945. this.doScrollingSpeedUp();
  946. } else if (Math.abs(dy) < touchDelta && Math.abs(dx) < touchDelta) {
  947. this.doToolBarToggle();
  948. }
  949. this.startTouch = null;
  950. }
  951. }
  952. }
  953. onTouchCancel() {
  954. if (!this.$isMobileDevice)
  955. return;
  956. this.endClickRepeat();
  957. }
  958. onMouseDown(event) {
  959. if (this.$isMobileDevice)
  960. return;
  961. this.endClickRepeat();
  962. if (event.button == 0) {
  963. const hc = this.handleClick(event.offsetX, event.offsetY);
  964. if (hc && hc != 'Menu') {
  965. this.repDoing = true;
  966. this.debouncedStartClickRepeat(event.offsetX, event.offsetY);
  967. }
  968. } else if (event.button == 1) {
  969. this.doScrollingToggle();
  970. } else if (event.button == 2) {
  971. this.doToolBarToggle();
  972. }
  973. }
  974. onMouseUp() {
  975. if (this.$isMobileDevice)
  976. return;
  977. this.endClickRepeat();
  978. }
  979. onMouseWheel(event) {
  980. if (this.$isMobileDevice)
  981. return;
  982. if (event.deltaY > 0) {
  983. this.doDown();
  984. } else if (event.deltaY < 0) {
  985. this.doUp();
  986. }
  987. }
  988. onStatusBarClick() {
  989. const url = this.meta.url;
  990. if (url && url.indexOf('file://') != 0) {
  991. window.open(url, '_blank');
  992. } else {
  993. this.$alert('Оригинал недоступен, т.к. файл книги был загружен с локального диска', '', {type: 'warning'});
  994. }
  995. }
  996. getClickAction(pointX, pointY) {
  997. const w = pointX/this.realWidth*100;
  998. const h = pointY/this.realHeight*100;
  999. let action = '';
  1000. loops: {
  1001. for (const x in clickMap) {
  1002. for (const y in clickMap[x]) {
  1003. if (w < x && h < y) {
  1004. action = clickMap[x][y];
  1005. break loops;
  1006. }
  1007. }
  1008. }
  1009. }
  1010. return action;
  1011. }
  1012. handleClick(pointX, pointY, exclude) {
  1013. const action = this.getClickAction(pointX, pointY);
  1014. if (!exclude || !exclude.has(action)) {
  1015. switch (action) {
  1016. case 'Down' ://Down
  1017. this.doDown();
  1018. break;
  1019. case 'Up' ://Up
  1020. this.doUp();
  1021. break;
  1022. case 'PgDown' ://PgDown
  1023. this.doPageDown();
  1024. break;
  1025. case 'PgUp' ://PgUp
  1026. this.doPageUp();
  1027. break;
  1028. case 'Menu' :
  1029. this.doToolBarToggle();
  1030. break;
  1031. default :
  1032. // Nothing
  1033. }
  1034. }
  1035. return action;
  1036. }
  1037. }
  1038. //-----------------------------------------------------------------------------
  1039. </script>
  1040. <style scoped>
  1041. .main {
  1042. flex: 1;
  1043. margin: 0;
  1044. padding: 0;
  1045. overflow: hidden;
  1046. position: relative;
  1047. min-width: 200px;
  1048. }
  1049. .layout {
  1050. margin: 0;
  1051. padding: 0;
  1052. position: absolute;
  1053. z-index: 10;
  1054. }
  1055. .over-hidden {
  1056. overflow: hidden;
  1057. }
  1058. .on-top {
  1059. z-index: 100;
  1060. }
  1061. .back {
  1062. z-index: 5;
  1063. }
  1064. .events {
  1065. z-index: 20;
  1066. background-color: rgba(0,0,0,0);
  1067. }
  1068. </style>
  1069. <style>
  1070. .paper1 {
  1071. background: url("images/paper1.jpg") center;
  1072. background-size: cover;
  1073. }
  1074. .paper2 {
  1075. background: url("images/paper2.jpg") center;
  1076. background-size: cover;
  1077. }
  1078. .paper3 {
  1079. background: url("images/paper3.jpg") center;
  1080. background-size: cover;
  1081. }
  1082. .paper4 {
  1083. background: url("images/paper4.jpg") center;
  1084. background-size: cover;
  1085. }
  1086. .paper5 {
  1087. background: url("images/paper5.jpg") center;
  1088. background-size: cover;
  1089. }
  1090. .paper6 {
  1091. background: url("images/paper6.jpg") center;
  1092. background-size: cover;
  1093. }
  1094. .paper7 {
  1095. background: url("images/paper7.jpg") center;
  1096. background-size: cover;
  1097. }
  1098. .paper8 {
  1099. background: url("images/paper8.jpg") center;
  1100. background-size: cover;
  1101. }
  1102. .paper9 {
  1103. background: url("images/paper9.jpg");
  1104. }
  1105. @keyframes page1-animation-thaw {
  1106. 0% { opacity: 0; }
  1107. 100% { opacity: 1; }
  1108. }
  1109. @keyframes page2-animation-thaw {
  1110. 0% { opacity: 1; }
  1111. 100% { opacity: 0; }
  1112. }
  1113. </style>