TextPage.vue 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. <template>
  2. <div ref="main" class="main">
  3. <canvas ref="canvas" class="canvas" @mousedown.prevent.stop="onMouseDown" @wheel.prevent.stop="onMouseWheel"
  4. @touchstart.prevent.stop="onTouchStart" oncontextmenu="return false;"></canvas>
  5. </div>
  6. </template>
  7. <script>
  8. //-----------------------------------------------------------------------------
  9. import Vue from 'vue';
  10. import Component from 'vue-class-component';
  11. import _ from 'lodash';
  12. import bookManager from '../share/bookManager';
  13. export default @Component({
  14. watch: {
  15. bookPos: function(newValue) {
  16. this.debouncedEmitPosChange(newValue);
  17. this.drawPage();
  18. },
  19. },
  20. })
  21. class TextPage extends Vue {
  22. lastBook = null;
  23. bookPos = 0;
  24. //убрать
  25. meta = null;
  26. items = null;
  27. created() {
  28. this.commit = this.$store.commit;
  29. this.dispatch = this.$store.dispatch;
  30. this.config = this.$store.state.config;
  31. this.reader = this.$store.state.reader;
  32. this.debouncedEmitPosChange = _.debounce((newValue) => {
  33. this.$emit('book-pos-changed', {bookPos: newValue});
  34. }, 1000);
  35. this.$root.$on('resize', () => {this.$nextTick(this.onResize)});
  36. }
  37. mounted() {
  38. this.canvas = this.$refs.canvas;
  39. this.context = this.canvas.getContext('2d');
  40. }
  41. async calcDrawProps() {
  42. this.realWidth = this.$refs.main.clientWidth;
  43. this.realHeight = this.$refs.main.clientHeight;
  44. let ratio = window.devicePixelRatio;
  45. if (ratio) {
  46. this.canvas.width = this.realWidth*ratio;
  47. this.canvas.height = this.realHeight*ratio;
  48. this.canvas.style.width = this.$refs.main.clientWidth + 'px';
  49. this.canvas.style.height = this.$refs.main.clientHeight + 'px';
  50. this.context.scale(ratio, ratio);
  51. } else {
  52. this.canvas.width = this.realWidth;
  53. this.canvas.height = this.realHeight;
  54. }
  55. this.lineHeight = this.fontSize + this.lineInterval;
  56. this.pageLineCount = Math.floor(this.realHeight/this.lineHeight);
  57. this.w = this.realWidth - 2*this.indent;
  58. this.h = this.realHeight;
  59. this.context.textAlign = 'left';
  60. this.context.textBaseline = 'bottom';
  61. if (this.parsed) {
  62. this.parsed.p = this.p;
  63. this.parsed.w = this.w;// px, ширина текста
  64. this.parsed.font = this.font;
  65. this.parsed.wordWrap = this.wordWrap;
  66. this.measureText = (text, style) => {// eslint-disable-line no-unused-vars
  67. if (style)
  68. this.context.font = this.fontByStyle(style);
  69. return this.context.measureText(text).width;
  70. };
  71. this.parsed.measureText = this.measureText;
  72. }
  73. }
  74. async loadFonts() {
  75. let loaded = await Promise.all(this.fontList.map(font => document.fonts.check(font)));
  76. if (loaded.some(r => !r)) {
  77. loaded = await Promise.all(this.fontList.map(font => document.fonts.load(font)));
  78. if (loaded.some(r => !r.length))
  79. throw new Error('some font not loaded');
  80. }
  81. }
  82. showBook() {
  83. this.$refs.main.focus();
  84. this.book = null;
  85. this.meta = null;
  86. this.fb2 = null;
  87. this.parsed = null;
  88. this.linesUp = null;
  89. this.linesDown = null;
  90. //preloaded fonts
  91. this.fontList = ['12px ReaderDefault', '12px Arial', '12px ComicSansMS', '12px OpenSans', '12px Roboto', '12px ArialNarrow',
  92. '12px Georgia', '12px Tahoma', '12px Helvetica', '12px CenturySchoolbook'];
  93. //draw props
  94. this.textColor = 'black';
  95. this.backgroundColor = '#478355';
  96. this.fontStyle = '';// 'bold','italic'
  97. this.fontSize = 34;// px
  98. this.fontName = 'Arial';
  99. this.lineInterval = 7;// px, межстрочный интервал
  100. this.textAlignJustify = true;// выравнивание по ширине
  101. this.p = 50;// px, отступ параграфа
  102. this.indent = 15;// px, отступ всего текста слева и справа
  103. this.wordWrap = true;
  104. this.calcDrawProps();
  105. this.drawPage();// пока не загрузили, очистим канвас
  106. if (this.lastBook) {
  107. (async() => {
  108. const isParsed = await bookManager.hasBookParsed(this.lastBook);
  109. if (!isParsed) {
  110. return;
  111. }
  112. this.book = await bookManager.getBook(this.lastBook);
  113. this.meta = bookManager.metaOnly(this.book);
  114. this.fb2 = this.meta.fb2;
  115. this.$root.$emit('set-app-title', _.compact([
  116. this.fb2.lastName,
  117. this.fb2.middleName,
  118. this.fb2.firstName,
  119. '-',
  120. this.fb2.bookTitle
  121. ]).join(' '));
  122. const parsed = this.book.parsed;
  123. this.parsed = parsed;
  124. this.calcDrawProps();
  125. await this.loadFonts();
  126. this.drawPage();
  127. })();
  128. }
  129. }
  130. onResize() {
  131. this.calcDrawProps();
  132. this.drawPage();
  133. }
  134. get font() {
  135. return `${this.fontStyle} ${this.fontSize}px ${this.fontName}`;
  136. }
  137. fontByStyle(style) {
  138. return `${style.italic ? 'italic' : ''} ${style.bold ? 'bold' : ''} ${this.fontSize}px ${this.fontName}`;
  139. }
  140. drawPage() {
  141. if (!this.lastBook)
  142. return;
  143. //пустой канвас
  144. const canvas = this.canvas;
  145. const context = this.context;
  146. context.fillStyle = this.backgroundColor;
  147. context.fillRect(0, 0, canvas.width, canvas.height);
  148. if (!this.book)
  149. return;
  150. context.font = this.font;
  151. context.fillStyle = this.textColor;
  152. const spaceWidth = this.context.measureText(' ').width;
  153. const lines = this.parsed.getLines(this.bookPos, this.pageLineCount + 1);
  154. let len = lines.length;
  155. len = (len > this.pageLineCount ? len = this.pageLineCount : len);
  156. let y = -this.lineInterval/2 + (this.h - this.pageLineCount*this.lineHeight)/2;
  157. for (let i = 0; i < len; i++) {
  158. const line = lines[i];
  159. /* line:
  160. {
  161. begin: Number,
  162. end: Number,
  163. first: Boolean,
  164. last: Boolean,
  165. parts: array of {
  166. style: {bold: Boolean, italic: Boolean}
  167. text: String,
  168. }
  169. }*/
  170. let indent = this.indent + (line.first ? this.p : 0);
  171. y += this.lineHeight;
  172. let filled = false;
  173. if (this.textAlignJustify && !line.last) {
  174. let lineText = '';
  175. for (const part of line.parts) {
  176. lineText += part.text;
  177. }
  178. const words = lineText.split(' ');
  179. if (words.length > 1) {
  180. const spaceCount = words.length - 1;
  181. const space = (this.w - line.width + spaceWidth*spaceCount)/spaceCount;
  182. let x = indent;
  183. for (const part of line.parts) {
  184. context.font = this.fontByStyle(part.style);
  185. let partWords = part.text.split(' ');
  186. for (let i = 0; i < partWords.length; i++) {
  187. let word = partWords[i];
  188. context.fillText(word, x, y);
  189. x += this.measureText(word, part.style) + (i < partWords.length - 1 ? space : 0);
  190. }
  191. }
  192. filled = true;
  193. }
  194. }
  195. if (!filled) {
  196. let x = indent;
  197. for (const part of line.parts) {
  198. let text = part.text;
  199. context.font = this.fontByStyle(part.style);
  200. context.fillText(text, x, y);
  201. x += this.measureText(text, part.style);
  202. }
  203. }
  204. }
  205. this.linesUp = this.parsed.getLines(this.bookPos, -(this.pageLineCount + 1));
  206. this.linesDown = lines;
  207. }
  208. doDown() {
  209. if (this.linesDown && this.linesDown.length > 1) {
  210. this.bookPos = this.linesDown[1].begin;
  211. }
  212. }
  213. doUp() {
  214. if (this.linesUp && this.linesUp.length > 1) {
  215. this.bookPos = this.linesUp[1].begin;
  216. }
  217. }
  218. doPageDown() {
  219. if (this.linesDown) {
  220. let i = this.pageLineCount;
  221. i--;
  222. if (i >= 0 && this.linesDown.length > i) {
  223. this.bookPos = this.linesDown[i].begin;
  224. }
  225. }
  226. }
  227. doPageUp() {
  228. if (this.linesUp) {
  229. let i = this.pageLineCount;
  230. i--;
  231. i = (i > this.linesUp.length - 1 ? this.linesUp.length - 1 : i);
  232. if (i >= 0 && this.linesUp.length > i) {
  233. this.bookPos = this.linesUp[i].begin;
  234. }
  235. }
  236. }
  237. doHome() {
  238. this.bookPos = 0;
  239. }
  240. doEnd() {
  241. if (this.parsed.para.length) {
  242. const lastPara = this.parsed.para[this.parsed.para.length - 1];
  243. this.bookPos = lastPara.offset + lastPara.length - 1;
  244. }
  245. }
  246. doToolBarToggle() {
  247. this.$emit('tool-bar-toggle');
  248. }
  249. keyHook(event) {
  250. if (event.type == 'keydown') {
  251. switch (event.code) {
  252. case 'ArrowDown':
  253. this.doDown();
  254. break;
  255. case 'ArrowUp':
  256. this.doUp();
  257. break;
  258. case 'PageDown':
  259. case 'ArrowRight':
  260. case 'Enter':
  261. case 'Space':
  262. this.doPageDown();
  263. break;
  264. case 'PageUp':
  265. case 'ArrowLeft':
  266. case 'Backspace':
  267. this.doPageUp();
  268. break;
  269. case 'Home':
  270. this.doHome();
  271. break;
  272. case 'End':
  273. this.doEnd();
  274. break;
  275. }
  276. }
  277. }
  278. onTouchStart(event) {
  279. if (event.touches.length == 1) {
  280. const touch = event.touches[0];
  281. this.handleClick(touch.clientX, touch.clientY)
  282. }
  283. }
  284. onMouseDown(event) {
  285. if (event.button == 0) {
  286. this.handleClick(event.clientX, event.clientY);
  287. } else if (event.button == 2) {
  288. this.doToolBarToggle();
  289. }
  290. }
  291. onMouseWheel(event) {
  292. if (event.deltaY > 0) {
  293. this.doDown();
  294. } else if (event.deltaY < 0) {
  295. this.doUp();
  296. }
  297. }
  298. handleClick(pointX, pointY) {
  299. const mouseLegend = {
  300. 40: {30: 'PgUp', 100: 'PgDown'},
  301. 60: {40: 'Up', 60: 'Menu', 100: 'Down'},
  302. 100: {30: 'PgUp', 100: 'PgDown'}
  303. };
  304. const w = pointX/this.realWidth*100;
  305. const h = pointY/this.realHeight*100;
  306. let action = '';
  307. loops: {
  308. for (const x in mouseLegend) {
  309. for (const y in mouseLegend[x]) {
  310. if (w < x && h < y) {
  311. action = mouseLegend[x][y];
  312. break loops;
  313. }
  314. }
  315. }
  316. }
  317. switch (action) {
  318. case 'Down' ://Down
  319. this.doDown();
  320. break;
  321. case 'Up' ://Up
  322. this.doUp();
  323. break;
  324. case 'PgDown' ://PgDown
  325. this.doPageDown();
  326. break;
  327. case 'PgUp' ://PgUp
  328. this.doPageUp();
  329. break;
  330. case 'Menu' :
  331. this.doToolBarToggle();
  332. break;
  333. default :
  334. // Nothing
  335. }
  336. return !!action;
  337. }
  338. }
  339. //-----------------------------------------------------------------------------
  340. </script>
  341. <style scoped>
  342. .main {
  343. flex: 1;
  344. margin: 0;
  345. padding: 0;
  346. overflow: hidden;
  347. }
  348. .canvas {
  349. margin: 0;
  350. padding: 0;
  351. }
  352. </style>