TextPage.vue 42 KB

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