TextPage.vue 21 KB

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