TextPage.vue 42 KB

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