TextPage.vue 43 KB

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