TextPage.vue 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  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. Arial: 5,
  141. ComicSansMS: -12,
  142. OpenSans: 0,
  143. Roboto: 0,
  144. ArialNarrow: 0,
  145. Georgia: 0,
  146. Tahoma: 0,
  147. Helvetica: 0,
  148. CenturySchoolbook: 0,
  149. }
  150. this.fontList = [];
  151. for (let fontName in this.fontShifts)
  152. this.fontList.push(`12px ${fontName}`);
  153. //default draw props
  154. this.textColor = '#000000';
  155. this.backgroundColor = '#478355';
  156. this.fontStyle = '';// 'bold','italic'
  157. this.fontSize = 35;// px
  158. this.fontName = 'ComicSansMS';
  159. this.lineInterval = 7;// px, межстрочный интервал
  160. this.textAlignJustify = true;// выравнивание по ширине
  161. this.p = 50;// px, отступ параграфа
  162. this.indent = 15;// px, отступ всего текста слева и справа
  163. this.wordWrap = true;
  164. this.keepLastToFirst = true;// перенос последней строки в первую при листании
  165. this.showStatusBar = true;
  166. this.statusBarTop = false;// top, bottom
  167. this.statusBarHeight = 20;// px
  168. this.statusBarColorAlpha = 0.4;
  169. this.pageChangeTransition = '';// '' - нет, downShift, rightShift, thaw - протаивание, blink - мерцание
  170. this.pageChangeTransitionSpeed = 50; //0-100%
  171. this.calcDrawProps();
  172. this.draw(true);// пока не загрузили, очистим канвас
  173. if (this.lastBook) {
  174. (async() => {
  175. const isParsed = await bookManager.hasBookParsed(this.lastBook);
  176. if (!isParsed) {
  177. return;
  178. }
  179. this.book = await bookManager.getBook(this.lastBook);
  180. this.meta = bookManager.metaOnly(this.book);
  181. this.fb2 = this.meta.fb2;
  182. const authorName = _.compact([
  183. this.fb2.lastName,
  184. this.fb2.firstName,
  185. this.fb2.middleName
  186. ]).join(' ');
  187. this.title = _.compact([
  188. authorName,
  189. this.fb2.bookTitle
  190. ]).join(' - ');
  191. this.$root.$emit('set-app-title', this.title);
  192. const parsed = this.book.parsed;
  193. this.parsed = parsed;
  194. this.calcDrawProps();
  195. await this.loadFonts();
  196. this.draw();
  197. this.refreshTime();
  198. })();
  199. }
  200. }
  201. onResize() {
  202. this.calcDrawProps();
  203. this.draw(true);
  204. }
  205. get font() {
  206. return `${this.fontStyle} ${this.fontSize}px ${this.fontName}`;
  207. }
  208. fontByStyle(style) {
  209. return `${style.italic ? 'italic' : ''} ${style.bold ? 'bold' : ''} ${this.fontSize}px ${this.fontName}`;
  210. }
  211. draw(immediate) {
  212. if (this.book && this.bookPos > 0 && this.bookPos >= this.parsed.textLength) {
  213. this.doEnd();
  214. return;
  215. }
  216. this.activeCanvas = !this.activeCanvas;
  217. if (immediate) {
  218. if (this.activeCanvas)
  219. this.page1 = this.drawPage(this.bookPos);
  220. else
  221. this.page2 = this.drawPage(this.bookPos);
  222. } else {
  223. if (this.pageChangeDirectionDown && this.pagePrepared && this.bookPos == this.bookPosPrepared) {
  224. this.linesDown = this.linesDownNext;
  225. this.linesUp = this.linesUpNext;
  226. this.pagePrepared = false;
  227. this.debouncedPrepareNextPage();
  228. } else {
  229. if (this.activeCanvas)
  230. this.page1 = this.drawPage(this.bookPos);
  231. else
  232. this.page2 = this.drawPage(this.bookPos);
  233. this.pagePrepared = false;
  234. this.debouncedPrepareNextPage();
  235. }
  236. if (this.currentTransition) {
  237. //this.currentTransition
  238. //this.pageChangeTransitionSpeed
  239. //this.pageChangeDirectionDown
  240. //curr to next transition
  241. //пока заглушка
  242. }
  243. this.currentTransition = '';
  244. this.pageChangeDirectionDown = false;//true только если PgDown
  245. }
  246. this.debouncedDrawStatusBar();
  247. }
  248. drawPage(bookPos, nextChangeLines) {
  249. if (!this.lastBook)
  250. return;
  251. let out = `<div class="layout" style="width: ${this.realWidth}px; height: ${this.realHeight}px;` +
  252. ` color: ${this.textColor}; background-color: ${this.backgroundColor}">`;
  253. if (!this.book || !this.parsed.textLength) {
  254. out += '</div>';
  255. return out;
  256. }
  257. const spaceWidth = this.measureText(' ', {});
  258. const lines = this.parsed.getLines(bookPos, 2*this.pageLineCount);
  259. if (!nextChangeLines) {
  260. this.linesDown = lines;
  261. this.linesUp = this.parsed.getLines(bookPos, -2*this.pageLineCount);
  262. } else {
  263. this.linesDownNext = lines;
  264. this.linesUpNext = this.parsed.getLines(bookPos, -2*this.pageLineCount);
  265. }
  266. let y = -this.lineInterval/2 + (this.h - this.pageLineCount*this.lineHeight)/2 + this.fontSize*this.fontShift;
  267. if (this.showStatusBar)
  268. y += this.statusBarHeight*(this.statusBarTop ? 1 : 0);
  269. let len = lines.length;
  270. len = (len > this.pageLineCount ? len = this.pageLineCount : len);
  271. for (let i = 0; i < len; i++) {
  272. const line = lines[i];
  273. /* line:
  274. {
  275. begin: Number,
  276. end: Number,
  277. first: Boolean,
  278. last: Boolean,
  279. parts: array of {
  280. style: {bold: Boolean, italic: Boolean, center: Boolean}
  281. text: String,
  282. }
  283. }*/
  284. let indent = this.indent + (line.first ? this.p : 0);
  285. let lineText = '';
  286. let center = false;
  287. let centerStyle = {};
  288. for (const part of line.parts) {
  289. lineText += part.text;
  290. center = center || part.style.center;
  291. if (part.style.center)
  292. centerStyle = part.style.center;
  293. }
  294. let filled = false;
  295. // если выравнивание по ширине включено
  296. if (this.textAlignJustify && !line.last && !center) {
  297. const words = lineText.split(' ');
  298. if (words.length > 1) {
  299. const spaceCount = words.length - 1;
  300. const space = (this.w - line.width + spaceWidth*spaceCount)/spaceCount;
  301. let x = indent;
  302. for (const part of line.parts) {
  303. const font = this.fontByStyle(part.style);
  304. let partWords = part.text.split(' ');
  305. for (let i = 0; i < partWords.length; i++) {
  306. let word = partWords[i];
  307. out += this.drawHelper.fillText(word, x, y, font);
  308. x += this.measureText(word, part.style) + (i < partWords.length - 1 ? space : 0);
  309. }
  310. }
  311. filled = true;
  312. }
  313. }
  314. // просто выводим текст
  315. if (!filled) {
  316. let x = indent;
  317. x = (center ? this.indent + (this.w - this.measureText(lineText, centerStyle))/2 : x);
  318. for (const part of line.parts) {
  319. let text = part.text;
  320. const font = this.fontByStyle(part.style);
  321. out += this.drawHelper.fillText(text, x, y, font);
  322. x += this.measureText(text, part.style);
  323. }
  324. }
  325. y += this.lineHeight;
  326. }
  327. out += '</div>';
  328. return out;
  329. }
  330. drawStatusBar() {
  331. if (this.showStatusBar && this.linesDown) {
  332. const lines = this.linesDown;
  333. let i = this.pageLineCount;
  334. if (this.keepLastToFirst)
  335. i--;
  336. i = (i > lines.length - 1 ? lines.length - 1 : i);
  337. this.statusBar = this.drawHelper.drawStatusBar(this.statusBarTop, this.statusBarHeight,
  338. lines[i].end, this.parsed.textLength, this.title);
  339. }
  340. }
  341. async refreshTime() {
  342. if (!this.timeRefreshing) {
  343. this.timeRefreshing = true;
  344. await sleep(60*1000);
  345. if (this.book && this.parsed.textLength) {
  346. this.debouncedDrawStatusBar();
  347. }
  348. this.timeRefreshing = false;
  349. this.refreshTime();
  350. }
  351. }
  352. prepareNextPage() {
  353. // подготовка следующей страницы заранее
  354. if (!this.book || !this.parsed.textLength)
  355. return;
  356. if (!this.preparing) {
  357. this.preparing = true;
  358. (async() => {
  359. await sleep(100);
  360. if (this.cancelPrepare) {
  361. this.preparing = false;
  362. return;
  363. }
  364. let i = this.pageLineCount;
  365. if (this.keepLastToFirst)
  366. i--;
  367. if (i >= 0 && this.linesDown.length > i) {
  368. this.bookPosPrepared = this.linesDown[i].begin;
  369. if (this.activeCanvas)
  370. this.page2 = this.drawPage(this.bookPosPrepared, true);//наоборот
  371. else
  372. this.page1 = this.drawPage(this.bookPosPrepared, true);
  373. this.pagePrepared = true;
  374. }
  375. this.preparing = false;
  376. })();
  377. }
  378. }
  379. doDown() {
  380. if (this.linesDown && this.linesDown.length > this.pageLineCount) {
  381. this.bookPos = this.linesDown[1].begin;
  382. }
  383. }
  384. doUp() {
  385. if (this.linesUp && this.linesUp.length > 1) {
  386. this.bookPos = this.linesUp[1].begin;
  387. }
  388. }
  389. doPageDown() {
  390. if (this.linesDown) {
  391. let i = this.pageLineCount;
  392. if (this.keepLastToFirst)
  393. i--;
  394. if (i >= 0 && this.linesDown.length >= 2*i) {
  395. this.currentTransition = this.pageChangeTransition;
  396. this.pageChangeDirectionDown = true;
  397. this.bookPos = this.linesDown[i].begin;
  398. } else
  399. this.doEnd();
  400. }
  401. }
  402. doPageUp() {
  403. if (this.linesUp) {
  404. let i = this.pageLineCount;
  405. if (this.keepLastToFirst)
  406. i--;
  407. i = (i > this.linesUp.length - 1 ? this.linesUp.length - 1 : i);
  408. if (i >= 0 && this.linesUp.length > i) {
  409. this.currentTransition = this.pageChangeTransition;
  410. this.pageChangeDirectionDown = false;
  411. this.bookPos = this.linesUp[i].begin;
  412. }
  413. }
  414. }
  415. doHome() {
  416. this.bookPos = 0;
  417. }
  418. doEnd() {
  419. if (this.parsed.para.length) {
  420. let i = this.parsed.para.length - 1;
  421. let lastPos = this.parsed.para[i].offset + this.parsed.para[i].length - 1;
  422. const lines = this.parsed.getLines(lastPos, -this.pageLineCount);
  423. i = this.pageLineCount - 1;
  424. i = (i > lines.length - 1 ? lines.length - 1 : i);
  425. this.bookPos = lines[i].begin;
  426. }
  427. }
  428. doToolBarToggle() {
  429. this.$emit('tool-bar-toggle');
  430. }
  431. keyHook(event) {
  432. if (event.type == 'keydown') {
  433. switch (event.code) {
  434. case 'ArrowDown':
  435. this.doDown();
  436. break;
  437. case 'ArrowUp':
  438. this.doUp();
  439. break;
  440. case 'PageDown':
  441. case 'ArrowRight':
  442. case 'Enter':
  443. case 'Space':
  444. this.doPageDown();
  445. break;
  446. case 'PageUp':
  447. case 'ArrowLeft':
  448. case 'Backspace':
  449. this.doPageUp();
  450. break;
  451. case 'Home':
  452. this.doHome();
  453. break;
  454. case 'End':
  455. this.doEnd();
  456. break;
  457. }
  458. }
  459. }
  460. async startClickRepeat(pointX, pointY) {
  461. this.repX = pointX;
  462. this.repY = pointY;
  463. if (!this.repInit && this.repDoing) {
  464. this.repInit = true;
  465. let delay = 400;
  466. while (this.repDoing) {
  467. this.handleClick(pointX, pointY);
  468. await sleep(delay);
  469. if (delay > 15)
  470. delay *= 0.8;
  471. }
  472. this.repInit = false;
  473. }
  474. }
  475. endClickRepeat() {
  476. this.repDoing = false;
  477. }
  478. onTouchStart(event) {
  479. if (!this.mobile)
  480. return;
  481. this.endClickRepeat();
  482. if (event.touches.length == 1) {
  483. const touch = event.touches[0];
  484. const rect = event.target.getBoundingClientRect();
  485. const x = touch.pageX - rect.left;
  486. const y = touch.pageY - rect.top;
  487. if (this.handleClick(x, y)) {
  488. this.repDoing = true;
  489. this.debouncedStartClickRepeat(x, y);
  490. }
  491. }
  492. }
  493. onTouchEnd() {
  494. if (!this.mobile)
  495. return;
  496. this.endClickRepeat();
  497. }
  498. onTouchCancel() {
  499. if (!this.mobile)
  500. return;
  501. this.endClickRepeat();
  502. }
  503. onMouseDown(event) {
  504. if (this.mobile)
  505. return;
  506. this.endClickRepeat();
  507. if (event.button == 0) {
  508. if (this.handleClick(event.offsetX, event.offsetY)) {
  509. this.repDoing = true;
  510. this.debouncedStartClickRepeat(event.offsetX, event.offsetY);
  511. }
  512. } else if (event.button == 2) {
  513. this.doToolBarToggle();
  514. }
  515. }
  516. onMouseUp() {
  517. if (this.mobile)
  518. return;
  519. this.endClickRepeat();
  520. }
  521. onMouseWheel(event) {
  522. if (this.mobile)
  523. return;
  524. if (event.deltaY > 0) {
  525. this.doDown();
  526. } else if (event.deltaY < 0) {
  527. this.doUp();
  528. }
  529. }
  530. onStatusBarClick() {
  531. window.open(this.meta.url, '_blank');
  532. }
  533. handleClick(pointX, pointY) {
  534. const mouseLegend = {
  535. 40: {30: 'PgUp', 100: 'PgDown'},
  536. 60: {40: 'Up', 60: 'Menu', 100: 'Down'},
  537. 100: {30: 'PgUp', 100: 'PgDown'}
  538. };
  539. const w = pointX/this.realWidth*100;
  540. const h = pointY/this.realHeight*100;
  541. let action = '';
  542. loops: {
  543. for (const x in mouseLegend) {
  544. for (const y in mouseLegend[x]) {
  545. if (w < x && h < y) {
  546. action = mouseLegend[x][y];
  547. break loops;
  548. }
  549. }
  550. }
  551. }
  552. switch (action) {
  553. case 'Down' ://Down
  554. this.doDown();
  555. break;
  556. case 'Up' ://Up
  557. this.doUp();
  558. break;
  559. case 'PgDown' ://PgDown
  560. this.doPageDown();
  561. break;
  562. case 'PgUp' ://PgUp
  563. this.doPageUp();
  564. break;
  565. case 'Menu' :
  566. this.doToolBarToggle();
  567. break;
  568. default :
  569. // Nothing
  570. }
  571. return (action && action != 'Menu');
  572. }
  573. }
  574. //-----------------------------------------------------------------------------
  575. </script>
  576. <style scoped>
  577. .main {
  578. flex: 1;
  579. margin: 0;
  580. padding: 0;
  581. overflow: hidden;
  582. position: relative;
  583. }
  584. .layout {
  585. margin: 0;
  586. padding: 0;
  587. position: absolute;
  588. z-index: 10;
  589. }
  590. .events {
  591. z-index: 20;
  592. background-color: rgba(0,0,0,0);
  593. }
  594. </style>