TextPage.vue 43 KB

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