TextPage.vue 21 KB

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