TextPage.vue 41 KB

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