TextPage.vue 22 KB

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