TextPage.vue 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295
  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. },
  64. bookPosSeen: function() {
  65. this.$emit('book-pos-changed', {bookPos: this.bookPos, bookPosSeen: this.bookPosSeen});
  66. },
  67. settings: function() {
  68. this.debouncedLoadSettings();
  69. },
  70. toggleLayout: function() {
  71. this.updateLayout();
  72. },
  73. inAnimation: function() {
  74. this.updateLayout();
  75. },
  76. },
  77. };
  78. class TextPage {
  79. _options = componentOptions;
  80. toggleLayout = false;
  81. showStatusBar = false;
  82. clickControl = true;
  83. background = null;
  84. pageDivider = null;
  85. page1 = null;
  86. page2 = null;
  87. statusBar = null;
  88. statusBarClickable = null;
  89. lastBook = null;
  90. bookPos = 0;
  91. bookPosSeen = null;
  92. fontStyle = null;
  93. fontSize = null;
  94. fontName = null;
  95. fontWeight = null;
  96. inAnimation = false;
  97. meta = null;
  98. created() {
  99. this.drawHelper = new DrawHelper();
  100. this.commit = this.$store.commit;
  101. this.dispatch = this.$store.dispatch;
  102. this.config = this.$store.state.config;
  103. this.reader = this.$store.state.reader;
  104. this.debouncedStartClickRepeat = _.debounce((x, y) => {
  105. this.startClickRepeat(x, y);
  106. }, 800);
  107. this.debouncedPrepareNextPage = _.debounce(() => {
  108. this.prepareNextPage();
  109. }, 100);
  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.toggleLayout = !this.toggleLayout;
  122. else {
  123. this.page2 = this.page1;
  124. this.toggleLayout = true;
  125. }
  126. if (this.toggleLayout)
  127. this.page1 = this.drawHelper.drawPage(lines);
  128. else
  129. this.page2 = this.drawHelper.drawPage(lines);
  130. await this.doPageAnimation();
  131. }, 10);
  132. this.$root.addEventHook('resize', async() => {
  133. this.$nextTick(this.onResize);
  134. await utils.sleep(500);
  135. this.$nextTick(this.onResize);
  136. });
  137. }
  138. mounted() {
  139. this.context = this.$refs.offscreenCanvas.getContext('2d');
  140. }
  141. hex2rgba(hex, alpha = 1) {
  142. const [r, g, b] = hex.match(/\w\w/g).map(x => parseInt(x, 16));
  143. return `rgba(${r},${g},${b},${alpha})`;
  144. }
  145. calcDrawProps() {
  146. const wideLetter = 'Щ';
  147. //preloaded fonts
  148. this.fontList = [`12px '${this.fontName}'`];
  149. //widths
  150. this.realWidth = this.$refs.main.clientWidth;
  151. this.realHeight = this.$refs.main.clientHeight;
  152. this.$refs.layoutEvents.style.width = this.realWidth + 'px';
  153. this.$refs.layoutEvents.style.height = this.realHeight + 'px';
  154. const dual = (this.dualPageMode ? 2 : 1);
  155. this.boxW = this.realWidth - 2*this.indentLR;
  156. this.w = this.boxW/dual - (this.dualPageMode ? 2*this.dualIndentLR : 0);
  157. this.scrollHeight = this.realHeight - (this.showStatusBar ? this.statusBarHeight : 0);
  158. this.h = this.scrollHeight - 2*this.indentTB;
  159. this.lineHeight = this.fontSize + this.lineInterval;
  160. this.pageRowsCount = 1 + Math.floor((this.h - this.lineHeight + this.lineInterval/2)/this.lineHeight);
  161. this.pageLineCount = (this.dualPageMode ? this.pageRowsCount*2 : this.pageRowsCount)
  162. //stuff
  163. this.currentAnimation = '';
  164. this.pageChangeDirectionDown = true;
  165. this.fontShift = this.fontVertShift/100;
  166. this.textShift = this.textVertShift/100 + this.fontShift;
  167. //statusBar
  168. this.$refs.statusBar.style.left = '0px';
  169. this.$refs.statusBar.style.top = (this.statusBarTop ? 1 : this.realHeight - this.statusBarHeight) + 'px';
  170. const sbColor = (this.statusBarColorAsText ? this.textColor : this.statusBarColor);
  171. this.statusBarRgbaColor = this.hex2rgba(sbColor || '#000000', this.statusBarColorAlpha);
  172. const ddColor = (this.dualDivColorAsText ? this.textColor : this.dualDivColor);
  173. this.dualDivRgbaColor = this.hex2rgba(ddColor || '#000000', this.dualDivColorAlpha);
  174. //drawHelper
  175. this.drawHelper.realWidth = this.realWidth;
  176. this.drawHelper.realHeight = this.realHeight;
  177. this.drawHelper.lastBook = this.lastBook;
  178. this.drawHelper.book = this.book;
  179. this.drawHelper.parsed = this.parsed;
  180. this.drawHelper.pageRowsCount = this.pageRowsCount;
  181. this.drawHelper.pageLineCount = this.pageLineCount;
  182. this.drawHelper.dualPageMode = this.dualPageMode;
  183. this.drawHelper.dualIndentLR = this.dualIndentLR;
  184. /*this.drawHelper.dualDivWidth = this.dualDivWidth;
  185. this.drawHelper.dualDivHeight = this.dualDivHeight;
  186. this.drawHelper.dualDivRgbaColor = this.dualDivRgbaColor;
  187. this.drawHelper.dualDivStrokeFill = this.dualDivStrokeFill;
  188. this.drawHelper.dualDivStrokeGap = this.dualDivStrokeGap;
  189. this.drawHelper.dualDivShadowWidth = this.dualDivShadowWidth;*/
  190. this.drawHelper.backgroundColor = this.backgroundColor;
  191. this.drawHelper.statusBarRgbaColor = this.statusBarRgbaColor;
  192. this.drawHelper.fontStyle = this.fontStyle;
  193. this.drawHelper.fontWeight = this.fontWeight;
  194. this.drawHelper.fontSize = this.fontSize;
  195. this.drawHelper.fontName = this.fontName;
  196. this.drawHelper.fontShift = this.fontShift;
  197. this.drawHelper.textColor = this.textColor;
  198. this.drawHelper.textShift = this.textShift;
  199. this.drawHelper.p = this.p;
  200. this.drawHelper.boxW = this.boxW;
  201. this.drawHelper.w = this.w;
  202. this.drawHelper.h = this.h;
  203. this.drawHelper.indentLR = this.indentLR;
  204. this.drawHelper.textAlignJustify = this.textAlignJustify;
  205. this.drawHelper.lineHeight = this.lineHeight;
  206. this.drawHelper.context = this.context;
  207. //альтернатива context.measureText
  208. if (!this.context.measureText(wideLetter).width) {
  209. const ctx = this.$refs.measureWidth;
  210. this.drawHelper.measureText = function(text, style) {
  211. ctx.innerText = text;
  212. ctx.style.font = this.fontByStyle(style);
  213. return ctx.clientWidth;
  214. };
  215. this.drawHelper.measureTextFont = function(text, font) {
  216. ctx.innerText = text;
  217. ctx.style.font = font;
  218. return ctx.clientWidth;
  219. }
  220. }
  221. //statusBar
  222. this.statusBarClickable = this.drawHelper.statusBarClickable(this.statusBarTop, this.statusBarHeight);
  223. //parsed
  224. if (this.parsed) {
  225. let wideLine = wideLetter;
  226. if (!this.drawHelper.measureText(wideLine, {}))
  227. throw new Error('Ошибка measureText');
  228. while (this.drawHelper.measureText(wideLine, {}) < this.w) wideLine += wideLetter;
  229. this.parsed.setSettings({
  230. p: this.p,
  231. w: this.w,
  232. font: this.font,
  233. fontSize: this.fontSize,
  234. wordWrap: this.wordWrap,
  235. cutEmptyParagraphs: this.cutEmptyParagraphs,
  236. addEmptyParagraphs: this.addEmptyParagraphs,
  237. maxWordLength: wideLine.length - 1,
  238. lineHeight: this.lineHeight,
  239. showImages: this.showImages,
  240. showInlineImagesInCenter: this.showInlineImagesInCenter,
  241. imageHeightLines: this.imageHeightLines,
  242. imageFitWidth: this.imageFitWidth,
  243. compactTextPerc: this.compactTextPerc,
  244. testWidth: 0,
  245. measureText: this.drawHelper.measureText.bind(this.drawHelper),
  246. });
  247. }
  248. //scrolling page
  249. const pageSpace = this.scrollHeight - this.pageRowsCount*this.lineHeight;
  250. let top = pageSpace/2;
  251. if (this.showStatusBar)
  252. top += this.statusBarHeight*(this.statusBarTop ? 1 : 0);
  253. let page1 = this.$refs.scrollBox1.style;
  254. let page2 = this.$refs.scrollBox2.style;
  255. page1.perspective = page2.perspective = '3072px';
  256. page1.width = page2.width = this.boxW + this.indentLR + 'px';
  257. page1.height = page2.height = this.scrollHeight - (pageSpace > 0 ? pageSpace : 0) + 'px';
  258. page1.top = page2.top = top + 'px';
  259. page1.left = page2.left = this.indentLR + 'px';
  260. page1 = this.$refs.scrollingPage1.style;
  261. page2 = this.$refs.scrollingPage2.style;
  262. page1.width = page2.width = this.boxW + this.indentLR + 'px';
  263. page1.height = page2.height = this.scrollHeight + this.lineHeight + 'px';
  264. }
  265. async checkLoadedFonts() {
  266. let loaded = await Promise.all(this.fontList.map(font => document.fonts.check(font)));
  267. if (loaded.some(r => !r)) {
  268. await Promise.all(this.fontList.map(font => document.fonts.load(font)));
  269. }
  270. }
  271. async loadFonts() {
  272. this.fontsLoading = true;
  273. let close = null;
  274. (async() => {
  275. await utils.sleep(500);
  276. if (this.fontsLoading)
  277. close = this.$root.notify.info('Загрузка шрифта &nbsp;<i class="la la-snowflake icon-rotate" style="font-size: 150%"></i>');
  278. })();
  279. if (!this.fontsLoaded)
  280. this.fontsLoaded = {};
  281. //загрузка дин.шрифта
  282. const loaded = this.fontsLoaded[this.fontCssUrl];
  283. if (this.fontCssUrl && !loaded) {
  284. loadCSS(this.fontCssUrl);
  285. this.fontsLoaded[this.fontCssUrl] = 1;
  286. }
  287. try {
  288. await this.checkLoadedFonts();
  289. } catch (e) {
  290. this.$root.notify.error('Некоторые шрифты не удалось загрузить', 'Ошибка загрузки');
  291. }
  292. this.fontsLoading = false;
  293. if (close)
  294. close();
  295. }
  296. getSettings() {
  297. const settings = this.settings;
  298. for (let prop in rstore.settingDefaults) {
  299. this[prop] = settings[prop];
  300. }
  301. const wf = this.webFontName;
  302. const i = _.findIndex(rstore.webFonts, ['name', wf]);
  303. if (wf && i >= 0) {
  304. this.fontName = wf;
  305. this.fontCssUrl = rstore.webFonts[i].css;
  306. this.fontVertShift = settings.fontShifts[wf] || 0;
  307. }
  308. }
  309. async calcPropsAndLoadFonts(omitLoadFonts) {
  310. this.calcDrawProps();
  311. this.setBackground();
  312. if (!omitLoadFonts)
  313. await this.loadFonts();
  314. if (omitLoadFonts) {
  315. this.draw();
  316. } else {
  317. // ширина шрифта некоторое время выдается неверно,
  318. // не удалось событийно отловить этот момент, поэтому костыль
  319. while (this.checkingFont) {
  320. this.stopCheckingFont = true;
  321. await utils.sleep(100);
  322. }
  323. this.checkingFont = true;
  324. this.stopCheckingFont = false;
  325. try {
  326. const parsed = this.parsed;
  327. let i = 0;
  328. const t = 'Это тестовый текст. Его ширина выдается системой неправильно некоторое время.';
  329. let twprev = 0;
  330. //5 секунд проверяем изменения шрифта
  331. while (!this.stopCheckingFont && i++ < 50 && this.parsed === parsed) {
  332. const tw = this.drawHelper.measureText(t, {});
  333. if (tw !== twprev) {
  334. this.parsed.setSettings({testWidth: tw});
  335. this.draw();
  336. twprev = tw;
  337. }
  338. await utils.sleep(100);
  339. }
  340. } finally {
  341. this.checkingFont = false;
  342. }
  343. }
  344. }
  345. loadSettings() {
  346. (async() => {
  347. let fontName = this.fontName;
  348. this.getSettings();
  349. await this.calcPropsAndLoadFonts(fontName == this.fontName);
  350. })();
  351. }
  352. showBook() {
  353. this.$refs.main.focus();
  354. this.toggleLayout = false;
  355. this.updateLayout();
  356. this.book = null;
  357. this.meta = null;
  358. this.parsed = null;
  359. this.linesUp = null;
  360. this.linesDown = null;
  361. this.statusBarMessage = '';
  362. this.getSettings();
  363. this.calcDrawProps();
  364. this.draw();// пока не загрузили, очистим канвас
  365. if (this.lastBook) {
  366. (async() => {
  367. try {
  368. //подождем ленивый парсинг
  369. this.stopLazyParse = true;
  370. while (this.doingLazyParse) await utils.sleep(10);
  371. const isParsed = await bookManager.hasBookParsed(this.lastBook);
  372. if (!isParsed) {
  373. return;
  374. }
  375. this.book = await bookManager.getBook(this.lastBook);
  376. this.meta = bookManager.metaOnly(this.book);
  377. const bt = utils.getBookTitle(this.meta.fb2);
  378. this.title = bt.fullTitle;
  379. this.$root.setAppTitle(this.title);
  380. this.parsed = this.book.parsed;
  381. this.page1 = null;
  382. this.page2 = null;
  383. this.statusBar = null;
  384. await this.stopTextScrolling();
  385. await this.calcPropsAndLoadFonts();
  386. this.refreshTime();
  387. if (this.lazyParseEnabled)
  388. this.lazyParsePara();
  389. } catch (e) {
  390. this.$root.stdDialog.alert(e.message, 'Ошибка', {color: 'negative'});
  391. }
  392. })();
  393. }
  394. }
  395. updateLayout() {
  396. if (this.inAnimation) {
  397. this.$refs.scrollBox1.style.visibility = 'visible';
  398. this.$refs.scrollBox2.style.visibility = 'visible';
  399. } else if (this.toggleLayout) {
  400. this.$refs.scrollBox1.style.visibility = 'visible';
  401. this.$refs.scrollBox2.style.visibility = 'hidden';
  402. } else {
  403. this.$refs.scrollBox1.style.visibility = 'hidden';
  404. this.$refs.scrollBox2.style.visibility = 'visible';
  405. }
  406. }
  407. setBackground() {
  408. if (this.wallpaperIgnoreStatusBar) {
  409. this.background = `<div class="layout" style="width: ${this.realWidth}px; height: ${this.realHeight}px;` +
  410. ` background-color: ${this.backgroundColor}">` +
  411. `<div class="layout ${this.wallpaper}" style="width: ${this.realWidth}px; height: ${this.scrollHeight}px; ` +
  412. `top: ${(this.showStatusBar && this.statusBarTop ? this.statusBarHeight + 1 : 0)}px; position: relative;">` +
  413. `</div>` +
  414. `</div>`;
  415. } else {
  416. this.background = `<div class="layout ${this.wallpaper}" style="width: ${this.realWidth}px; height: ${this.realHeight}px;` +
  417. ` background-color: ${this.backgroundColor}"></div>`;
  418. }
  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.$root.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.$root.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.$root.isMobileDevice)
  955. return;
  956. this.endClickRepeat();
  957. }
  958. onMouseDown(event) {
  959. if (this.$root.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.$root.isMobileDevice)
  976. return;
  977. this.endClickRepeat();
  978. }
  979. onMouseWheel(event) {
  980. if (this.$root.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. copyText(event) {
  1038. //все это для того, чтобы правильно расставить переносы \n при копировании текста
  1039. //прямо с текущей страницы
  1040. //подготовка, вытаскиваем весь текст страницы
  1041. const lines = this.getLines(this.bookPos);
  1042. const decodedLines = [];
  1043. for (const line of lines.linesDown) {
  1044. let lineText = '';
  1045. for (const part of line.parts) {
  1046. lineText += part.text;
  1047. }
  1048. decodedLines.push({text: he.decode(lineText), first: line.first});
  1049. }
  1050. let i = 0;
  1051. const findDecoded = (line) => {
  1052. for (let j = i; j < decodedLines.length; j++) {
  1053. const decoded = decodedLines[j];
  1054. if (decoded.text.indexOf(line) >= 0) {
  1055. i = j;
  1056. return decoded;
  1057. }
  1058. }
  1059. return;
  1060. }
  1061. const selection = document.getSelection();
  1062. const splitted = selection.toString().split(/[\n\r]/);
  1063. let filtered = '';
  1064. //формируем filtered, учитывая переносы из decodedLines
  1065. for (const line of splitted) {
  1066. const found = findDecoded(line);
  1067. if (found && found.first) {
  1068. filtered += (filtered ? '\n' : '') + line;
  1069. } else {
  1070. filtered += (filtered ? '\r ' : '') + line;
  1071. }
  1072. }
  1073. //маленькие хитрости, убираем переносы по слогам
  1074. filtered = filtered.replace(/-\r /g, '').replace(/\r /g, ' ');
  1075. event.clipboardData.setData('text/plain', filtered);
  1076. }
  1077. }
  1078. export default vueComponent(TextPage);
  1079. //-----------------------------------------------------------------------------
  1080. </script>
  1081. <style scoped>
  1082. .main {
  1083. flex: 1;
  1084. margin: 0;
  1085. padding: 0;
  1086. overflow: hidden;
  1087. position: relative;
  1088. min-width: 200px;
  1089. }
  1090. .layout {
  1091. margin: 0;
  1092. padding: 0;
  1093. position: absolute;
  1094. z-index: 10;
  1095. }
  1096. .over-hidden {
  1097. overflow: hidden;
  1098. }
  1099. .on-top {
  1100. z-index: 100;
  1101. }
  1102. .back {
  1103. z-index: 5;
  1104. }
  1105. .events {
  1106. z-index: 20;
  1107. background-color: rgba(0,0,0,0);
  1108. }
  1109. </style>