TextPage.vue 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  1. <template>
  2. <div ref="main" class="main">
  3. <div v-show="activeCanvas" class="layout">
  4. <div v-html="page1"></div>
  5. </div>
  6. <div v-show="!activeCanvas" class="layout">
  7. <div v-html="page2"></div>
  8. </div>
  9. <div v-show="showStatusBar" ref="statusBar" class="layout">
  10. <div v-html="statusBar"></div>
  11. </div>
  12. <div ref="layoutEvents" class="layout events" @mousedown.prevent.stop="onMouseDown" @mouseup.prevent.stop="onMouseUp"
  13. @wheel.prevent.stop="onMouseWheel"
  14. @touchstart.stop="onTouchStart" @touchend.stop="onTouchEnd" @touchcancel.prevent.stop="onTouchCancel"
  15. oncontextmenu="return false;">
  16. <div v-show="showStatusBar" v-html="statusBarClickable" @mousedown.prevent.stop @touchstart.stop
  17. @click.prevent.stop="onStatusBarClick"></div>
  18. </div>
  19. <canvas ref="offscreenCanvas" style="display: none"></canvas>
  20. </div>
  21. </template>
  22. <script>
  23. //-----------------------------------------------------------------------------
  24. import Vue from 'vue';
  25. import Component from 'vue-class-component';
  26. import _ from 'lodash';
  27. import {sleep} from '../../../share/utils';
  28. import bookManager from '../share/bookManager';
  29. import DrawHelper from './DrawHelper';
  30. export default @Component({
  31. watch: {
  32. bookPos: function(newValue) {
  33. this.debouncedEmitPosChange(newValue);
  34. this.draw();
  35. },
  36. },
  37. })
  38. class TextPage extends Vue {
  39. activeCanvas = false;
  40. showStatusBar = false;
  41. page1 = null;
  42. page2 = null;
  43. statusBar = null;
  44. statusBarClickable = null;
  45. lastBook = null;
  46. bookPos = 0;
  47. fontStyle = null;
  48. fontSize = null;
  49. fontName = null;
  50. meta = null;
  51. created() {
  52. this.drawHelper = new DrawHelper();
  53. this.commit = this.$store.commit;
  54. this.dispatch = this.$store.dispatch;
  55. this.config = this.$store.state.config;
  56. this.reader = this.$store.state.reader;
  57. this.debouncedEmitPosChange = _.debounce((newValue) => {
  58. this.$emit('book-pos-changed', {bookPos: newValue});
  59. }, 1000);
  60. this.debouncedStartClickRepeat = _.debounce((x, y) => {
  61. this.startClickRepeat(x, y);
  62. }, 800);
  63. this.debouncedPrepareNextPage = _.debounce(() => {
  64. this.prepareNextPage();
  65. }, 100);
  66. this.debouncedDrawStatusBar = _.throttle(() => {
  67. this.drawStatusBar();
  68. }, 60);
  69. this.$root.$on('resize', () => {this.$nextTick(this.onResize)});
  70. this.mobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent);
  71. }
  72. mounted() {
  73. this.context = this.$refs.offscreenCanvas.getContext('2d');
  74. }
  75. hex2rgba(hex, alpha = 1) {
  76. const [r, g, b] = hex.match(/\w\w/g).map(x => parseInt(x, 16));
  77. return `rgba(${r},${g},${b},${alpha})`;
  78. }
  79. async calcDrawProps() {
  80. this.realWidth = this.$refs.main.clientWidth;
  81. this.realHeight = this.$refs.main.clientHeight;
  82. this.$refs.layoutEvents.style.width = this.realWidth + 'px';
  83. this.$refs.layoutEvents.style.height = this.realHeight + 'px';
  84. this.activeCanvas = false;
  85. this.w = this.realWidth - 2*this.indent;
  86. this.h = this.realHeight - (this.showStatusBar ? this.statusBarHeight : 0);
  87. this.lineHeight = this.fontSize + this.lineInterval;
  88. this.pageLineCount = Math.floor(this.h/this.lineHeight);
  89. if (this.parsed) {
  90. this.parsed.p = this.p;
  91. this.parsed.w = this.w;// px, ширина текста
  92. this.parsed.font = this.font;
  93. this.parsed.wordWrap = this.wordWrap;
  94. this.parsed.measureText = this.measureText;
  95. }
  96. this.statusBarColor = this.hex2rgba(this.textColor, this.statusBarColorAlpha);
  97. this.currentTransition = '';
  98. this.pageChangeDirectionDown = true;
  99. this.fontShift = (this.fontShifts[this.fontName] ? this.fontShifts[this.fontName] : 0)/100;
  100. //drawHelper
  101. this.drawHelper.realWidth = this.realWidth;
  102. this.drawHelper.realHeight = this.realHeight;
  103. this.drawHelper.backgroundColor = this.backgroundColor;
  104. this.drawHelper.statusBarColor = this.statusBarColor;
  105. this.drawHelper.fontName = this.fontName;
  106. this.drawHelper.fontShift = this.fontShift;
  107. this.drawHelper.measureText = this.measureText;
  108. this.drawHelper.measureTextFont = this.measureTextFont;
  109. this.$refs.statusBar.style.left = '0px';
  110. this.$refs.statusBar.style.top = (this.statusBarTop ? 1 : this.realHeight - this.statusBarHeight) + 'px';
  111. this.statusBarClickable = this.drawHelper.statusBarClickable(this.statusBarTop, this.statusBarHeight);
  112. }
  113. measureText(text, style) {// eslint-disable-line no-unused-vars
  114. this.context.font = this.fontByStyle(style);
  115. return this.context.measureText(text).width;
  116. }
  117. measureTextFont(text, font) {// eslint-disable-line no-unused-vars
  118. this.context.font = font;
  119. return this.context.measureText(text).width;
  120. }
  121. async loadFonts() {
  122. let loaded = await Promise.all(this.fontList.map(font => document.fonts.check(font)));
  123. if (loaded.some(r => !r)) {
  124. loaded = await Promise.all(this.fontList.map(font => document.fonts.load(font)));
  125. if (loaded.some(r => !r.length))
  126. throw new Error('some font not loaded');
  127. }
  128. }
  129. showBook() {
  130. this.$refs.main.focus();
  131. this.book = null;
  132. this.meta = null;
  133. this.fb2 = null;
  134. this.parsed = null;
  135. this.linesUp = null;
  136. this.linesDown = null;
  137. //preloaded fonts
  138. this.fontShifts = {//%
  139. ReaderDefault: 0,
  140. Roboto: 0,
  141. OpenSans: 0,
  142. }
  143. this.fontList = [];
  144. for (let fontName in this.fontShifts)
  145. this.fontList.push(`12px ${fontName}`);
  146. //default draw props
  147. this.textColor = '#000000';
  148. this.backgroundColor = '#478355';
  149. this.fontStyle = '';// 'bold','italic'
  150. this.fontSize = 33;// px
  151. this.fontName = 'ReaderDefault';
  152. this.fontCss = '';
  153. this.lineInterval = 7;// px, межстрочный интервал
  154. this.textAlignJustify = true;// выравнивание по ширине
  155. this.p = 50;// px, отступ параграфа
  156. this.indent = 15;// px, отступ всего текста слева и справа
  157. this.wordWrap = true;
  158. this.keepLastToFirst = true;// перенос последней строки в первую при листании
  159. this.showStatusBar = true;
  160. this.statusBarTop = false;// top, bottom
  161. this.statusBarHeight = 19;// px
  162. this.statusBarColorAlpha = 0.4;
  163. this.pageChangeTransition = '';// '' - нет, downShift, rightShift, thaw - протаивание, blink - мерцание
  164. this.pageChangeTransitionSpeed = 50; //0-100%
  165. this.calcDrawProps();
  166. this.draw(true);// пока не загрузили, очистим канвас
  167. if (this.lastBook) {
  168. (async() => {
  169. const isParsed = await bookManager.hasBookParsed(this.lastBook);
  170. if (!isParsed) {
  171. return;
  172. }
  173. this.book = await bookManager.getBook(this.lastBook);
  174. this.meta = bookManager.metaOnly(this.book);
  175. this.fb2 = this.meta.fb2;
  176. const authorName = _.compact([
  177. this.fb2.lastName,
  178. this.fb2.firstName,
  179. this.fb2.middleName
  180. ]).join(' ');
  181. this.title = _.compact([
  182. authorName,
  183. this.fb2.bookTitle
  184. ]).join(' - ');
  185. this.$root.$emit('set-app-title', this.title);
  186. const parsed = this.book.parsed;
  187. this.parsed = parsed;
  188. this.calcDrawProps();
  189. //await this.loadFontCss();
  190. await this.loadFonts();
  191. this.draw();
  192. this.refreshTime();
  193. })();
  194. }
  195. }
  196. onResize() {
  197. this.calcDrawProps();
  198. this.draw(true);
  199. }
  200. get font() {
  201. return `${this.fontStyle} ${this.fontSize}px ${this.fontName}`;
  202. }
  203. fontByStyle(style) {
  204. return `${style.italic ? 'italic' : ''} ${style.bold ? 'bold' : ''} ${this.fontSize}px ${this.fontName}`;
  205. }
  206. draw(immediate) {
  207. if (this.book && this.bookPos > 0 && this.bookPos >= this.parsed.textLength) {
  208. this.doEnd();
  209. return;
  210. }
  211. this.activeCanvas = !this.activeCanvas;
  212. if (immediate) {
  213. if (this.activeCanvas)
  214. this.page1 = this.drawPage(this.bookPos);
  215. else
  216. this.page2 = this.drawPage(this.bookPos);
  217. } else {
  218. if (this.pageChangeDirectionDown && this.pagePrepared && this.bookPos == this.bookPosPrepared) {
  219. this.linesDown = this.linesDownNext;
  220. this.linesUp = this.linesUpNext;
  221. this.pagePrepared = false;
  222. this.debouncedPrepareNextPage();
  223. } else {
  224. if (this.activeCanvas)
  225. this.page1 = this.drawPage(this.bookPos);
  226. else
  227. this.page2 = this.drawPage(this.bookPos);
  228. this.pagePrepared = false;
  229. this.debouncedPrepareNextPage();
  230. }
  231. if (this.currentTransition) {
  232. //this.currentTransition
  233. //this.pageChangeTransitionSpeed
  234. //this.pageChangeDirectionDown
  235. //curr to next transition
  236. //пока заглушка
  237. }
  238. this.currentTransition = '';
  239. this.pageChangeDirectionDown = false;//true только если PgDown
  240. }
  241. this.debouncedDrawStatusBar();
  242. }
  243. drawPage(bookPos, nextChangeLines) {
  244. if (!this.lastBook)
  245. return;
  246. let out = `<div class="layout" style="width: ${this.realWidth}px; height: ${this.realHeight}px;` +
  247. ` color: ${this.textColor}; background-color: ${this.backgroundColor}">`;
  248. if (!this.book || !this.parsed.textLength) {
  249. out += '</div>';
  250. return out;
  251. }
  252. const spaceWidth = this.measureText(' ', {});
  253. const lines = this.parsed.getLines(bookPos, 2*this.pageLineCount);
  254. if (!nextChangeLines) {
  255. this.linesDown = lines;
  256. this.linesUp = this.parsed.getLines(bookPos, -2*this.pageLineCount);
  257. } else {
  258. this.linesDownNext = lines;
  259. this.linesUpNext = this.parsed.getLines(bookPos, -2*this.pageLineCount);
  260. }
  261. let y = -this.lineInterval/2 + (this.h - this.pageLineCount*this.lineHeight)/2 + this.fontSize*this.fontShift;
  262. if (this.showStatusBar)
  263. y += this.statusBarHeight*(this.statusBarTop ? 1 : 0);
  264. let len = lines.length;
  265. len = (len > this.pageLineCount ? len = this.pageLineCount : len);
  266. for (let i = 0; i < len; i++) {
  267. const line = lines[i];
  268. /* line:
  269. {
  270. begin: Number,
  271. end: Number,
  272. first: Boolean,
  273. last: Boolean,
  274. parts: array of {
  275. style: {bold: Boolean, italic: Boolean, center: Boolean}
  276. text: String,
  277. }
  278. }*/
  279. let indent = this.indent + (line.first ? this.p : 0);
  280. let lineText = '';
  281. let center = false;
  282. let centerStyle = {};
  283. for (const part of line.parts) {
  284. lineText += part.text;
  285. center = center || part.style.center;
  286. if (part.style.center)
  287. centerStyle = part.style.center;
  288. }
  289. let filled = false;
  290. // если выравнивание по ширине включено
  291. if (this.textAlignJustify && !line.last && !center) {
  292. const words = lineText.split(' ');
  293. if (words.length > 1) {
  294. const spaceCount = words.length - 1;
  295. const space = (this.w - line.width + spaceWidth*spaceCount)/spaceCount;
  296. let x = indent;
  297. for (const part of line.parts) {
  298. const font = this.fontByStyle(part.style);
  299. let partWords = part.text.split(' ');
  300. for (let i = 0; i < partWords.length; i++) {
  301. let word = partWords[i];
  302. out += this.drawHelper.fillText(word, x, y, font);
  303. x += this.measureText(word, part.style) + (i < partWords.length - 1 ? space : 0);
  304. }
  305. }
  306. filled = true;
  307. }
  308. }
  309. // просто выводим текст
  310. if (!filled) {
  311. let x = indent;
  312. x = (center ? this.indent + (this.w - this.measureText(lineText, centerStyle))/2 : x);
  313. for (const part of line.parts) {
  314. let text = part.text;
  315. const font = this.fontByStyle(part.style);
  316. out += this.drawHelper.fillText(text, x, y, font);
  317. x += this.measureText(text, part.style);
  318. }
  319. }
  320. y += this.lineHeight;
  321. }
  322. out += '</div>';
  323. return out;
  324. }
  325. drawStatusBar() {
  326. if (this.showStatusBar && this.linesDown) {
  327. const lines = this.linesDown;
  328. let i = this.pageLineCount;
  329. if (this.keepLastToFirst)
  330. i--;
  331. i = (i > lines.length - 1 ? lines.length - 1 : i);
  332. this.statusBar = this.drawHelper.drawStatusBar(this.statusBarTop, this.statusBarHeight,
  333. lines[i].end, this.parsed.textLength, this.title);
  334. }
  335. }
  336. async refreshTime() {
  337. if (!this.timeRefreshing) {
  338. this.timeRefreshing = true;
  339. await sleep(60*1000);
  340. if (this.book && this.parsed.textLength) {
  341. this.debouncedDrawStatusBar();
  342. }
  343. this.timeRefreshing = false;
  344. this.refreshTime();
  345. }
  346. }
  347. prepareNextPage() {
  348. // подготовка следующей страницы заранее
  349. if (!this.book || !this.parsed.textLength || !this.linesDown)
  350. return;
  351. if (!this.preparing) {
  352. this.preparing = true;
  353. (async() => {
  354. await sleep(100);
  355. if (this.cancelPrepare) {
  356. this.preparing = false;
  357. return;
  358. }
  359. let i = this.pageLineCount;
  360. if (this.keepLastToFirst)
  361. i--;
  362. if (i >= 0 && this.linesDown.length > i) {
  363. this.bookPosPrepared = this.linesDown[i].begin;
  364. if (this.activeCanvas)
  365. this.page2 = this.drawPage(this.bookPosPrepared, true);//наоборот
  366. else
  367. this.page1 = this.drawPage(this.bookPosPrepared, true);
  368. this.pagePrepared = true;
  369. }
  370. this.preparing = false;
  371. })();
  372. }
  373. }
  374. doDown() {
  375. if (this.linesDown && this.linesDown.length > this.pageLineCount) {
  376. this.bookPos = this.linesDown[1].begin;
  377. }
  378. }
  379. doUp() {
  380. if (this.linesUp && this.linesUp.length > 1) {
  381. this.bookPos = this.linesUp[1].begin;
  382. }
  383. }
  384. doPageDown() {
  385. if (this.linesDown) {
  386. let i = this.pageLineCount;
  387. if (this.keepLastToFirst)
  388. i--;
  389. if (i >= 0 && this.linesDown.length >= 2*i) {
  390. this.currentTransition = this.pageChangeTransition;
  391. this.pageChangeDirectionDown = true;
  392. this.bookPos = this.linesDown[i].begin;
  393. } else
  394. this.doEnd();
  395. }
  396. }
  397. doPageUp() {
  398. if (this.linesUp) {
  399. let i = this.pageLineCount;
  400. if (this.keepLastToFirst)
  401. i--;
  402. i = (i > this.linesUp.length - 1 ? this.linesUp.length - 1 : i);
  403. if (i >= 0 && this.linesUp.length > i) {
  404. this.currentTransition = this.pageChangeTransition;
  405. this.pageChangeDirectionDown = false;
  406. this.bookPos = this.linesUp[i].begin;
  407. }
  408. }
  409. }
  410. doHome() {
  411. this.bookPos = 0;
  412. }
  413. doEnd() {
  414. if (this.parsed.para.length) {
  415. let i = this.parsed.para.length - 1;
  416. let lastPos = this.parsed.para[i].offset + this.parsed.para[i].length - 1;
  417. const lines = this.parsed.getLines(lastPos, -this.pageLineCount);
  418. i = this.pageLineCount - 1;
  419. i = (i > lines.length - 1 ? lines.length - 1 : i);
  420. this.bookPos = lines[i].begin;
  421. }
  422. }
  423. doToolBarToggle() {
  424. this.$emit('tool-bar-toggle');
  425. }
  426. keyHook(event) {
  427. if (event.type == 'keydown') {
  428. switch (event.code) {
  429. case 'ArrowDown':
  430. this.doDown();
  431. break;
  432. case 'ArrowUp':
  433. this.doUp();
  434. break;
  435. case 'PageDown':
  436. case 'ArrowRight':
  437. case 'Enter':
  438. case 'Space':
  439. this.doPageDown();
  440. break;
  441. case 'PageUp':
  442. case 'ArrowLeft':
  443. case 'Backspace':
  444. this.doPageUp();
  445. break;
  446. case 'Home':
  447. this.doHome();
  448. break;
  449. case 'End':
  450. this.doEnd();
  451. break;
  452. }
  453. }
  454. }
  455. async startClickRepeat(pointX, pointY) {
  456. this.repX = pointX;
  457. this.repY = pointY;
  458. if (!this.repInit && this.repDoing) {
  459. this.repInit = true;
  460. let delay = 400;
  461. while (this.repDoing) {
  462. this.handleClick(pointX, pointY);
  463. await sleep(delay);
  464. if (delay > 15)
  465. delay *= 0.8;
  466. }
  467. this.repInit = false;
  468. }
  469. }
  470. endClickRepeat() {
  471. this.repDoing = false;
  472. }
  473. onTouchStart(event) {
  474. if (!this.mobile)
  475. return;
  476. this.endClickRepeat();
  477. if (event.touches.length == 1) {
  478. const touch = event.touches[0];
  479. const rect = event.target.getBoundingClientRect();
  480. const x = touch.pageX - rect.left;
  481. const y = touch.pageY - rect.top;
  482. if (this.handleClick(x, y)) {
  483. this.repDoing = true;
  484. this.debouncedStartClickRepeat(x, y);
  485. }
  486. }
  487. }
  488. onTouchEnd() {
  489. if (!this.mobile)
  490. return;
  491. this.endClickRepeat();
  492. }
  493. onTouchCancel() {
  494. if (!this.mobile)
  495. return;
  496. this.endClickRepeat();
  497. }
  498. onMouseDown(event) {
  499. if (this.mobile)
  500. return;
  501. this.endClickRepeat();
  502. if (event.button == 0) {
  503. if (this.handleClick(event.offsetX, event.offsetY)) {
  504. this.repDoing = true;
  505. this.debouncedStartClickRepeat(event.offsetX, event.offsetY);
  506. }
  507. } else if (event.button == 2) {
  508. this.doToolBarToggle();
  509. }
  510. }
  511. onMouseUp() {
  512. if (this.mobile)
  513. return;
  514. this.endClickRepeat();
  515. }
  516. onMouseWheel(event) {
  517. if (this.mobile)
  518. return;
  519. if (event.deltaY > 0) {
  520. this.doDown();
  521. } else if (event.deltaY < 0) {
  522. this.doUp();
  523. }
  524. }
  525. onStatusBarClick() {
  526. window.open(this.meta.url, '_blank');
  527. }
  528. handleClick(pointX, pointY) {
  529. const mouseLegend = {
  530. 40: {30: 'PgUp', 100: 'PgDown'},
  531. 60: {40: 'Up', 60: 'Menu', 100: 'Down'},
  532. 100: {30: 'PgUp', 100: 'PgDown'}
  533. };
  534. const w = pointX/this.realWidth*100;
  535. const h = pointY/this.realHeight*100;
  536. let action = '';
  537. loops: {
  538. for (const x in mouseLegend) {
  539. for (const y in mouseLegend[x]) {
  540. if (w < x && h < y) {
  541. action = mouseLegend[x][y];
  542. break loops;
  543. }
  544. }
  545. }
  546. }
  547. switch (action) {
  548. case 'Down' ://Down
  549. this.doDown();
  550. break;
  551. case 'Up' ://Up
  552. this.doUp();
  553. break;
  554. case 'PgDown' ://PgDown
  555. this.doPageDown();
  556. break;
  557. case 'PgUp' ://PgUp
  558. this.doPageUp();
  559. break;
  560. case 'Menu' :
  561. this.doToolBarToggle();
  562. break;
  563. default :
  564. // Nothing
  565. }
  566. return (action && action != 'Menu');
  567. }
  568. }
  569. //-----------------------------------------------------------------------------
  570. </script>
  571. <style scoped>
  572. .main {
  573. flex: 1;
  574. margin: 0;
  575. padding: 0;
  576. overflow: hidden;
  577. position: relative;
  578. }
  579. .layout {
  580. margin: 0;
  581. padding: 0;
  582. position: absolute;
  583. z-index: 10;
  584. }
  585. .events {
  586. z-index: 20;
  587. background-color: rgba(0,0,0,0);
  588. }
  589. </style>