TextPage.vue 41 KB

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