TextPage.vue 41 KB

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