TextPage.vue 41 KB

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