Reader.vue 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237
  1. <template>
  2. <el-container>
  3. <el-header v-show="toolBarActive" height='50px'>
  4. <div ref="header" class="header">
  5. <el-tooltip content="Загрузить книгу" :open-delay="1000" effect="light">
  6. <el-button ref="loader" class="tool-button" :class="buttonActiveClass('loader')" @click="buttonClick('loader')"><i class="el-icon-back"></i></el-button>
  7. </el-tooltip>
  8. <div>
  9. <el-tooltip v-show="showToolButton['undoAction']" content="Действие назад" :open-delay="1000" effect="light">
  10. <el-button ref="undoAction" class="tool-button" :class="buttonActiveClass('undoAction')" @click="buttonClick('undoAction')" ><i class="el-icon-arrow-left"></i></el-button>
  11. </el-tooltip>
  12. <el-tooltip v-show="showToolButton['redoAction']" content="Действие вперед" :open-delay="1000" effect="light">
  13. <el-button ref="redoAction" class="tool-button" :class="buttonActiveClass('redoAction')" @click="buttonClick('redoAction')" ><i class="el-icon-arrow-right"></i></el-button>
  14. </el-tooltip>
  15. <div class="space"></div>
  16. <el-tooltip v-show="showToolButton['fullScreen']" content="На весь экран" :open-delay="1000" effect="light">
  17. <el-button ref="fullScreen" class="tool-button" :class="buttonActiveClass('fullScreen')" @click="buttonClick('fullScreen')"><i class="el-icon-rank"></i></el-button>
  18. </el-tooltip>
  19. <el-tooltip v-show="showToolButton['scrolling']" content="Плавный скроллинг" :open-delay="1000" effect="light">
  20. <el-button ref="scrolling" class="tool-button" :class="buttonActiveClass('scrolling')" @click="buttonClick('scrolling')"><i class="el-icon-sort"></i></el-button>
  21. </el-tooltip>
  22. <el-tooltip v-show="showToolButton['setPosition']" content="На страницу" :open-delay="1000" effect="light">
  23. <el-button ref="setPosition" class="tool-button" :class="buttonActiveClass('setPosition')" @click="buttonClick('setPosition')"><i class="el-icon-d-arrow-right"></i></el-button>
  24. </el-tooltip>
  25. <el-tooltip v-show="showToolButton['search']" content="Найти в тексте" :open-delay="1000" effect="light">
  26. <el-button ref="search" class="tool-button" :class="buttonActiveClass('search')" @click="buttonClick('search')"><i class="el-icon-search"></i></el-button>
  27. </el-tooltip>
  28. <el-tooltip v-show="showToolButton['copyText']" content="Скопировать текст со страницы" :open-delay="1000" effect="light">
  29. <el-button ref="copyText" class="tool-button" :class="buttonActiveClass('copyText')" @click="buttonClick('copyText')"><i class="el-icon-edit-outline"></i></el-button>
  30. </el-tooltip>
  31. <el-tooltip v-show="showToolButton['refresh']" content="Принудительно обновить книгу в обход кэша" :open-delay="1000" effect="light">
  32. <el-button ref="refresh" class="tool-button" :class="buttonActiveClass('refresh')" @click="buttonClick('refresh')">
  33. <i class="el-icon-refresh" :class="{clear: !showRefreshIcon}"></i>
  34. </el-button>
  35. </el-tooltip>
  36. <div class="space"></div>
  37. <el-tooltip v-show="showToolButton['offlineMode']" content="Автономный режим (без интернета)" :open-delay="1000" effect="light">
  38. <el-button ref="offlineMode" class="tool-button" :class="buttonActiveClass('offlineMode')" @click="buttonClick('offlineMode')"><i class="el-icon-connection"></i></el-button>
  39. </el-tooltip>
  40. <el-tooltip v-show="showToolButton['recentBooks']" content="Открыть недавние" :open-delay="1000" effect="light">
  41. <el-button ref="recentBooks" class="tool-button" :class="buttonActiveClass('recentBooks')" @click="buttonClick('recentBooks')"><i class="el-icon-document"></i></el-button>
  42. </el-tooltip>
  43. </div>
  44. <el-tooltip content="Настроить" :open-delay="1000" effect="light">
  45. <el-button ref="settings" class="tool-button" :class="buttonActiveClass('settings')" @click="buttonClick('settings')"><i class="el-icon-setting"></i></el-button>
  46. </el-tooltip>
  47. </div>
  48. </el-header>
  49. <el-main>
  50. <keep-alive>
  51. <component ref="page" :is="activePage"
  52. @load-book="loadBook"
  53. @load-file="loadFile"
  54. @book-pos-changed="bookPosChanged"
  55. @tool-bar-toggle="toolBarToggle"
  56. @full-screen-toogle="fullScreenToggle"
  57. @stop-scrolling="stopScrolling"
  58. @scrolling-toggle="scrollingToggle"
  59. @help-toggle="helpToggle"
  60. @donate-toggle="donateToggle"
  61. ></component>
  62. </keep-alive>
  63. <SetPositionPage v-if="setPositionActive" ref="setPositionPage" @set-position-toggle="setPositionToggle" @book-pos-changed="bookPosChanged"></SetPositionPage>
  64. <SearchPage v-show="searchActive" ref="searchPage"
  65. @search-toggle="searchToggle"
  66. @book-pos-changed="bookPosChanged"
  67. @start-text-search="startTextSearch"
  68. @stop-text-search="stopTextSearch">
  69. </SearchPage>
  70. <CopyTextPage v-if="copyTextActive" ref="copyTextPage" @copy-text-toggle="copyTextToggle"></CopyTextPage>
  71. <RecentBooksPage v-show="recentBooksActive" ref="recentBooksPage" @load-book="loadBook" @recent-books-toggle="recentBooksToggle"></RecentBooksPage>
  72. <SettingsPage v-if="settingsActive" ref="settingsPage" @settings-toggle="settingsToggle"></SettingsPage>
  73. <HelpPage v-if="helpActive" ref="helpPage" @help-toggle="helpToggle"></HelpPage>
  74. <ClickMapPage v-show="clickMapActive" ref="clickMapPage"></ClickMapPage>
  75. <ServerStorage v-show="hidden" ref="serverStorage"></ServerStorage>
  76. <el-dialog
  77. title="Что нового:"
  78. :visible.sync="whatsNewVisible"
  79. width="80%">
  80. <div style="line-height: 20px" v-html="whatsNewContent"></div>
  81. <span class="clickable" @click="openVersionHistory">Посмотреть историю версий</span>
  82. <span slot="footer" class="dialog-footer">
  83. <el-button @click="whatsNewDisable">Больше не показывать</el-button>
  84. </span>
  85. </el-dialog>
  86. <el-dialog
  87. title="Здравствуйте, уважаемые читатели!"
  88. :visible.sync="donationVisible"
  89. width="90%">
  90. <div style="word-break: normal">
  91. Стартовала ежегодная акция "Оплатим хостинг вместе".<br><br>
  92. Для оплаты годового хостинга читалки, необходимо собрать около 2000 рублей.
  93. В настоящий момент у автора эта сумма есть в наличии. Однако будет справедливо, если каждый
  94. сможет проголосовать рублем за то, чтобы читалка так и оставалась:
  95. <ul>
  96. <li>непрерывно улучшаемой</li>
  97. <li>без рекламы</li>
  98. <li>без регистрации</li>
  99. <li>Open Source</li>
  100. </ul>
  101. Автор также обращается с просьбой о помощи в распространении
  102. <a href="https://omnireader.ru" target="_blank">ссылки</a>
  103. <el-tooltip :open-delay="500" effect="light">
  104. <template slot="content">
  105. Скопировать
  106. </template>
  107. <i class="el-icon-copy-document" style="cursor: pointer; font-size: 100%" @click="copyLink('https://omnireader.ru')"></i>
  108. </el-tooltip>
  109. на читалку через тематические форумы, соцсети, мессенджеры и пр.
  110. Чем нас больше, тем легче оставаться на плаву и тем больше мотивации у разработчика, чтобы продолжать работать над проектом.
  111. <br><br>
  112. Если соберется бóльшая сумма, то разработка децентрализованной библиотеки для свободного обмена книгами будет по возможности ускорена.
  113. <br><br>
  114. P.S. При необходимости можно воспользоваться подходящим обменником на <a href="https://www.bestchange.ru" target="_blank">bestchange.ru</a>
  115. <br><br>
  116. <el-row type="flex" justify="center">
  117. <el-button type="success" round @click="openDonate">Помочь проекту</el-button>
  118. </el-row>
  119. </div>
  120. <span slot="footer" class="dialog-footer">
  121. <span class="clickable" style="font-size: 60%; color: grey" @click="donationDialogDisable">Больше не показывать</span>
  122. <br><br>
  123. <el-button @click="donationDialogRemind">Напомнить позже</el-button>
  124. </span>
  125. </el-dialog>
  126. </el-main>
  127. </el-container>
  128. </template>
  129. <script>
  130. //-----------------------------------------------------------------------------
  131. import Vue from 'vue';
  132. import Component from 'vue-class-component';
  133. import _ from 'lodash';
  134. import {Buffer} from 'safe-buffer';
  135. import LoaderPage from './LoaderPage/LoaderPage.vue';
  136. import TextPage from './TextPage/TextPage.vue';
  137. import ProgressPage from './ProgressPage/ProgressPage.vue';
  138. import SetPositionPage from './SetPositionPage/SetPositionPage.vue';
  139. import SearchPage from './SearchPage/SearchPage.vue';
  140. import CopyTextPage from './CopyTextPage/CopyTextPage.vue';
  141. import RecentBooksPage from './RecentBooksPage/RecentBooksPage.vue';
  142. import SettingsPage from './SettingsPage/SettingsPage.vue';
  143. import HelpPage from './HelpPage/HelpPage.vue';
  144. import ClickMapPage from './ClickMapPage/ClickMapPage.vue';
  145. import ServerStorage from './ServerStorage/ServerStorage.vue';
  146. import bookManager from './share/bookManager';
  147. import readerApi from '../../api/reader';
  148. import * as utils from '../../share/utils';
  149. import {versionHistory} from './versionHistory';
  150. export default @Component({
  151. components: {
  152. LoaderPage,
  153. TextPage,
  154. ProgressPage,
  155. SetPositionPage,
  156. SearchPage,
  157. CopyTextPage,
  158. RecentBooksPage,
  159. SettingsPage,
  160. HelpPage,
  161. ClickMapPage,
  162. ServerStorage,
  163. },
  164. watch: {
  165. bookPos: function(newValue) {
  166. if (newValue !== undefined && this.activePage == 'TextPage') {
  167. const textPage = this.$refs.page;
  168. if (textPage.bookPos != newValue) {
  169. textPage.bookPos = newValue;
  170. }
  171. if (!this.scrollingActive)
  172. this.debouncedSetRecentBook(newValue);
  173. else
  174. this.scrollingSetRecentBook(newValue);
  175. }
  176. },
  177. routeParamPos: function(newValue) {
  178. if (!this.paramPosIgnore && newValue !== undefined && newValue != this.bookPos) {
  179. this.bookPos = newValue;
  180. }
  181. },
  182. routeParamUrl: function(newValue) {
  183. if (newValue !== '' && newValue !== this.mostRecentBook().url) {
  184. this.loadBook({url: newValue, bookPos: this.routeParamPos});
  185. }
  186. },
  187. settings: function() {
  188. this.loadSettings();
  189. this.updateRoute();
  190. },
  191. loaderActive: function(newValue) {
  192. (async() => {
  193. const recent = this.mostRecentBook();
  194. if (!newValue && !this.loading && recent && !await bookManager.hasBookParsed(recent)) {
  195. this.loadBook(recent);
  196. }
  197. })();
  198. },
  199. },
  200. })
  201. class Reader extends Vue {
  202. loaderActive = false;
  203. progressActive = false;
  204. fullScreenActive = false;
  205. scrollingActive = false;
  206. setPositionActive = false;
  207. searchActive = false;
  208. copyTextActive = false;
  209. recentBooksActive = false;
  210. offlineModeActive = false;
  211. settingsActive = false;
  212. helpActive = false;
  213. clickMapActive = false;
  214. bookPos = null;
  215. allowUrlParamBookPos = false;
  216. showRefreshIcon = true;
  217. mostRecentBookReactive = null;
  218. showToolButton = {};
  219. actionList = [];
  220. actionCur = -1;
  221. hidden = false;
  222. whatsNewVisible = false;
  223. whatsNewContent = '';
  224. donationVisible = false;
  225. created() {
  226. this.loading = true;
  227. this.commit = this.$store.commit;
  228. this.dispatch = this.$store.dispatch;
  229. this.reader = this.$store.state.reader;
  230. this.config = this.$store.state.config;
  231. this.$root.addKeyHook(this.keyHook);
  232. this.lastActivePage = false;
  233. this.debouncedSetRecentBook = _.debounce(async(newValue) => {
  234. const recent = this.mostRecentBook();
  235. if (recent && (recent.bookPos != newValue || recent.bookPosSeen !== this.bookPosSeen)) {
  236. await bookManager.setRecentBook(Object.assign({}, recent, {bookPos: newValue, bookPosSeen: this.bookPosSeen}));
  237. if (this.actionCur < 0 || (this.actionCur >= 0 && this.actionList[this.actionCur] != newValue))
  238. this.addAction(newValue);
  239. this.paramPosIgnore = true;
  240. this.updateRoute();
  241. await this.$nextTick();
  242. this.paramPosIgnore = false;
  243. }
  244. }, 500, {'maxWait':5000});
  245. this.scrollingSetRecentBook = _.debounce((newValue) => {
  246. this.debouncedSetRecentBook(newValue);
  247. }, 15000, {'maxWait':20000});
  248. document.addEventListener('fullscreenchange', () => {
  249. this.fullScreenActive = (document.fullscreenElement !== null);
  250. });
  251. this.loadSettings();
  252. }
  253. mounted() {
  254. this.updateHeaderMinWidth();
  255. (async() => {
  256. await bookManager.init(this.settings);
  257. bookManager.addEventListener(this.bookManagerEvent);
  258. if (this.$root.rootRoute == '/reader') {
  259. if (this.routeParamUrl) {
  260. await this.loadBook({url: this.routeParamUrl, bookPos: this.routeParamPos, force: this.routeParamRefresh});
  261. } else {
  262. this.loaderActive = true;
  263. }
  264. }
  265. await this.$refs.serverStorage.init();
  266. this.checkSetStorageAccessKey();
  267. this.checkActivateDonateHelpPage();
  268. this.loading = false;
  269. this.updateRoute();
  270. await this.showWhatsNew();
  271. await this.showDonation();
  272. })();
  273. }
  274. loadSettings() {
  275. const settings = this.settings;
  276. this.allowUrlParamBookPos = settings.allowUrlParamBookPos;
  277. this.copyFullText = settings.copyFullText;
  278. this.showClickMapPage = settings.showClickMapPage;
  279. this.clickControl = settings.clickControl;
  280. this.blinkCachedLoad = settings.blinkCachedLoad;
  281. this.showWhatsNewDialog = settings.showWhatsNewDialog;
  282. this.showDonationDialog2020 = settings.showDonationDialog2020;
  283. this.showToolButton = settings.showToolButton;
  284. this.enableSitesFilter = settings.enableSitesFilter;
  285. this.updateHeaderMinWidth();
  286. }
  287. updateHeaderMinWidth() {
  288. const showButtonCount = Object.values(this.showToolButton).reduce((a, b) => a + (b ? 1 : 0), 0);
  289. if (this.$refs.header)
  290. this.$refs.header.style.minWidth = 65*showButtonCount + 'px';
  291. }
  292. checkSetStorageAccessKey() {
  293. const q = this.$route.query;
  294. if (q['setStorageAccessKey']) {
  295. this.$router.replace(`/reader`);
  296. this.settingsToggle();
  297. this.$nextTick(() => {
  298. this.$refs.settingsPage.enterServerStorageKey(
  299. Buffer.from(utils.fromBase58(q['setStorageAccessKey'])).toString()
  300. );
  301. });
  302. }
  303. }
  304. checkActivateDonateHelpPage() {
  305. const q = this.$route.query;
  306. if (q['donate']) {
  307. this.$router.replace(`/reader`);
  308. this.helpToggle();
  309. this.$nextTick(() => {
  310. this.$refs.helpPage.activateDonateHelpPage();
  311. });
  312. }
  313. }
  314. checkBookPosPercent() {
  315. const q = this.$route.query;
  316. if (q['__pp']) {
  317. let pp = q['__pp'];
  318. if (pp) {
  319. pp = parseFloat(pp) || 0;
  320. const recent = this.mostRecentBook();
  321. (async() => {
  322. await utils.sleep(100);
  323. this.bookPos = Math.floor(recent.textLength*pp/100);
  324. })();
  325. }
  326. }
  327. }
  328. async showWhatsNew() {
  329. await utils.sleep(2000);
  330. const whatsNew = versionHistory[0];
  331. if (this.showWhatsNewDialog &&
  332. whatsNew.showUntil >= utils.formatDate(new Date(), 'coDate') &&
  333. whatsNew.header != this.whatsNewContentHash) {
  334. this.whatsNewContent = 'Версия ' + whatsNew.header + whatsNew.content;
  335. this.whatsNewVisible = true;
  336. }
  337. }
  338. async showDonation() {
  339. await utils.sleep(3000);
  340. const today = utils.formatDate(new Date(), 'coDate');
  341. if (this.mode == 'omnireader' && today < '2020-03-01' && this.showDonationDialog2020 && this.donationRemindDate != today) {
  342. this.donationVisible = true;
  343. }
  344. }
  345. donationDialogDisable() {
  346. this.donationVisible = false;
  347. if (this.showDonationDialog2020) {
  348. const newSettings = Object.assign({}, this.settings, { showDonationDialog2020: false });
  349. this.commit('reader/setSettings', newSettings);
  350. }
  351. }
  352. donationDialogRemind() {
  353. this.donationVisible = false;
  354. this.commit('reader/setDonationRemindDate', utils.formatDate(new Date(), 'coDate'));
  355. }
  356. openDonate() {
  357. this.donationVisible = false;
  358. this.donateToggle();
  359. }
  360. async copyLink(link) {
  361. const result = await utils.copyTextToClipboard(link);
  362. if (result)
  363. this.$notify.success({message: `Ссылка ${link} успешно скопирована в буфер обмена`});
  364. else
  365. this.$notify.error({message: 'Копирование не удалось'});
  366. }
  367. openVersionHistory() {
  368. this.whatsNewVisible = false;
  369. this.versionHistoryToggle();
  370. }
  371. whatsNewDisable() {
  372. this.whatsNewVisible = false;
  373. const whatsNew = versionHistory[0];
  374. this.commit('reader/setWhatsNewContentHash', whatsNew.header);
  375. }
  376. get routeParamPos() {
  377. let result = undefined;
  378. const q = this.$route.query;
  379. if (q['__p']) {
  380. result = q['__p'];
  381. if (Array.isArray(result))
  382. result = result[0];
  383. }
  384. return (result ? parseInt(result, 10) || 0 : result);
  385. }
  386. updateRoute(isNewRoute) {
  387. if (this.loading)
  388. return;
  389. const recent = this.mostRecentBook();
  390. const pos = (recent && recent.bookPos && this.allowUrlParamBookPos ? `__p=${recent.bookPos}&` : '');
  391. const url = (recent ? `url=${recent.url}` : '');
  392. if (isNewRoute)
  393. this.$router.push(`/reader?${pos}${url}`).catch(() => {});
  394. else
  395. this.$router.replace(`/reader?${pos}${url}`).catch(() => {});
  396. }
  397. get mode() {
  398. return this.$store.state.config.mode;
  399. }
  400. get routeParamUrl() {
  401. let result = '';
  402. const path = this.$route.fullPath;
  403. const i = path.indexOf('url=');
  404. if (i >= 0) {
  405. result = path.substr(i + 4);
  406. }
  407. return decodeURIComponent(result);
  408. }
  409. get routeParamRefresh() {
  410. const q = this.$route.query;
  411. return !!q['__refresh'];
  412. }
  413. bookPosChanged(event) {
  414. if (event.bookPosSeen !== undefined)
  415. this.bookPosSeen = event.bookPosSeen;
  416. this.bookPos = event.bookPos;
  417. }
  418. async bookManagerEvent(eventName, value) {
  419. if (eventName == 'set-recent' || eventName == 'recent-deleted') {
  420. const oldBook = (this.textPage ? this.textPage.lastBook : null);
  421. const oldPos = (this.textPage ? this.textPage.bookPos : null);
  422. const newBook = bookManager.mostRecentBook();
  423. if (!(oldBook && newBook && oldBook.key == newBook.key)) {
  424. this.mostRecentBook();
  425. }
  426. if (oldBook && newBook) {
  427. if (oldBook.key != newBook.key || oldBook.path != newBook.path) {
  428. this.loadingBook = true;
  429. try {
  430. await this.loadBook(newBook);
  431. } finally {
  432. this.loadingBook = false;
  433. }
  434. } else if (oldPos != newBook.bookPos) {
  435. while (this.loadingBook) await utils.sleep(100);
  436. this.bookPosChanged({bookPos: newBook.bookPos});
  437. }
  438. }
  439. }
  440. if (eventName == 'recent-changed') {
  441. if (this.recentBooksActive) {
  442. await this.$refs.recentBooksPage.updateTableData();
  443. }
  444. //сохранение в serverStorage
  445. if (value) {
  446. await utils.sleep(500);
  447. await this.$refs.serverStorage.saveRecent(value);
  448. }
  449. }
  450. }
  451. get toolBarActive() {
  452. return this.reader.toolBarActive;
  453. }
  454. mostRecentBook() {
  455. const result = bookManager.mostRecentBook();
  456. this.mostRecentBookReactive = result;
  457. return result;
  458. }
  459. get settings() {
  460. return this.$store.state.reader.settings;
  461. }
  462. get whatsNewContentHash() {
  463. return this.$store.state.reader.whatsNewContentHash;
  464. }
  465. get donationRemindDate() {
  466. return this.$store.state.reader.donationRemindDate;
  467. }
  468. addAction(pos) {
  469. let a = this.actionList;
  470. if (!a.length || a[a.length - 1] != pos) {
  471. a.push(pos);
  472. if (a.length > 20)
  473. a.shift();
  474. this.actionCur = a.length - 1;
  475. }
  476. }
  477. toolBarToggle() {
  478. this.commit('reader/setToolBarActive', !this.toolBarActive);
  479. this.$root.$emit('resize');
  480. }
  481. fullScreenToggle() {
  482. this.fullScreenActive = !this.fullScreenActive;
  483. if (this.fullScreenActive) {
  484. this.$q.fullscreen.request();
  485. } else {
  486. this.$q.fullscreen.exit();
  487. }
  488. }
  489. closeAllTextPages() {
  490. this.setPositionActive = false;
  491. this.copyTextActive = false;
  492. this.recentBooksActive = false;
  493. this.settingsActive = false;
  494. this.stopScrolling();
  495. this.stopSearch();
  496. this.helpActive = false;
  497. }
  498. loaderToggle() {
  499. this.loaderActive = !this.loaderActive;
  500. if (this.loaderActive) {
  501. this.closeAllTextPages();
  502. }
  503. }
  504. setPositionToggle() {
  505. this.setPositionActive = !this.setPositionActive;
  506. if (this.setPositionActive && this.activePage == 'TextPage' && this.mostRecentBook()) {
  507. this.closeAllTextPages();
  508. this.setPositionActive = true;
  509. this.$nextTick(() => {
  510. const recent = this.mostRecentBook();
  511. this.$refs.setPositionPage.init(recent.bookPos, recent.textLength - 1);
  512. });
  513. } else {
  514. this.setPositionActive = false;
  515. }
  516. }
  517. stopScrolling() {
  518. if (this.scrollingActive)
  519. this.scrollingToggle();
  520. }
  521. scrollingToggle() {
  522. this.scrollingActive = !this.scrollingActive;
  523. if (this.activePage == 'TextPage') {
  524. const page = this.$refs.page;
  525. if (this.scrollingActive) {
  526. page.startTextScrolling();
  527. } else {
  528. page.stopTextScrolling();
  529. }
  530. }
  531. if (!this.scrollingActive) {
  532. this.scrollingSetRecentBook.flush();
  533. }
  534. }
  535. stopSearch() {
  536. if (this.searchActive)
  537. this.searchToggle();
  538. }
  539. startTextSearch(opts) {
  540. if (this.activePage == 'TextPage')
  541. this.$refs.page.startSearch(opts.needle);
  542. }
  543. stopTextSearch() {
  544. if (this.activePage == 'TextPage')
  545. this.$refs.page.stopSearch();
  546. }
  547. searchToggle() {
  548. this.searchActive = !this.searchActive;
  549. const page = this.$refs.page;
  550. if (this.searchActive && this.activePage == 'TextPage' && page.parsed) {
  551. this.closeAllTextPages();
  552. this.searchActive = true;
  553. this.$nextTick(() => {
  554. this.$refs.searchPage.init(page.parsed);
  555. });
  556. } else {
  557. this.stopTextSearch();
  558. this.searchActive = false;
  559. }
  560. }
  561. copyTextToggle() {
  562. this.copyTextActive = !this.copyTextActive;
  563. const page = this.$refs.page;
  564. if (this.copyTextActive && this.activePage == 'TextPage' && page.parsed) {
  565. this.closeAllTextPages();
  566. this.copyTextActive = true;
  567. this.$nextTick(() => {
  568. this.$refs.copyTextPage.init(this.mostRecentBook().bookPos, page.parsed, this.copyFullText);
  569. });
  570. } else {
  571. this.copyTextActive = false;
  572. }
  573. }
  574. recentBooksToggle() {
  575. this.recentBooksActive = !this.recentBooksActive;
  576. if (this.recentBooksActive) {
  577. this.closeAllTextPages();
  578. this.$refs.recentBooksPage.init();
  579. this.recentBooksActive = true;
  580. } else {
  581. this.recentBooksActive = false;
  582. }
  583. }
  584. offlineModeToggle() {
  585. this.offlineModeActive = !this.offlineModeActive;
  586. this.$refs.serverStorage.offlineModeActive = this.offlineModeActive;
  587. }
  588. settingsToggle() {
  589. this.settingsActive = !this.settingsActive;
  590. if (this.settingsActive) {
  591. this.closeAllTextPages();
  592. this.settingsActive = true;
  593. this.$nextTick(() => {
  594. this.$refs.settingsPage.init();
  595. });
  596. } else {
  597. this.settingsActive = false;
  598. }
  599. }
  600. helpToggle() {
  601. this.helpActive = !this.helpActive;
  602. if (this.helpActive) {
  603. this.closeAllTextPages();
  604. this.helpActive = true;
  605. }
  606. }
  607. donateToggle() {
  608. this.helpToggle();
  609. if (this.helpActive) {
  610. this.$nextTick(() => {
  611. this.$refs.helpPage.activateDonateHelpPage();
  612. });
  613. }
  614. }
  615. versionHistoryToggle() {
  616. this.helpToggle();
  617. if (this.helpActive) {
  618. this.$nextTick(() => {
  619. this.$refs.helpPage.activateVersionHistoryHelpPage();
  620. });
  621. }
  622. }
  623. refreshBook() {
  624. if (this.mostRecentBook()) {
  625. this.loadBook({url: this.mostRecentBook().url, force: true});
  626. }
  627. }
  628. buttonClick(button) {
  629. const activeClass = this.buttonActiveClass(button);
  630. this.$refs[button].$el.blur();
  631. if (activeClass['tool-button-disabled'])
  632. return;
  633. switch (button) {
  634. case 'loader':
  635. this.loaderToggle();
  636. break;
  637. case 'undoAction':
  638. if (this.actionCur > 0) {
  639. this.actionCur--;
  640. this.bookPosChanged({bookPos: this.actionList[this.actionCur]});
  641. }
  642. break;
  643. case 'redoAction':
  644. if (this.actionCur < this.actionList.length - 1) {
  645. this.actionCur++;
  646. this.bookPosChanged({bookPos: this.actionList[this.actionCur]});
  647. }
  648. break;
  649. case 'fullScreen':
  650. this.fullScreenToggle();
  651. break;
  652. case 'setPosition':
  653. this.setPositionToggle();
  654. break;
  655. case 'scrolling':
  656. this.scrollingToggle();
  657. break;
  658. case 'search':
  659. this.searchToggle();
  660. break;
  661. case 'copyText':
  662. this.copyTextToggle();
  663. break;
  664. case 'refresh':
  665. this.refreshBook();
  666. break;
  667. case 'recentBooks':
  668. this.recentBooksToggle();
  669. break;
  670. case 'offlineMode':
  671. this.offlineModeToggle();
  672. break;
  673. case 'settings':
  674. this.settingsToggle();
  675. break;
  676. }
  677. }
  678. buttonActiveClass(button) {
  679. const classActive = { 'tool-button-active': true, 'tool-button-active:hover': true };
  680. const classDisabled = { 'tool-button-disabled': true, 'tool-button-disabled:hover': true };
  681. let classResult = {};
  682. switch (button) {
  683. case 'loader':
  684. case 'fullScreen':
  685. case 'setPosition':
  686. case 'scrolling':
  687. case 'search':
  688. case 'copyText':
  689. case 'refresh':
  690. case 'offlineMode':
  691. case 'recentBooks':
  692. case 'settings':
  693. if (this.progressActive) {
  694. classResult = classDisabled;
  695. } else if (this[`${button}Active`]) {
  696. classResult = classActive;
  697. }
  698. break;
  699. case 'undoAction':
  700. if (this.actionCur <= 0)
  701. classResult = classDisabled;
  702. break;
  703. case 'redoAction':
  704. if (this.actionCur == this.actionList.length - 1)
  705. classResult = classDisabled;
  706. break;
  707. }
  708. if (this.activePage == 'LoaderPage' || !this.mostRecentBookReactive) {
  709. switch (button) {
  710. case 'undoAction':
  711. case 'redoAction':
  712. case 'setPosition':
  713. case 'scrolling':
  714. case 'search':
  715. case 'copyText':
  716. classResult = classDisabled;
  717. break;
  718. case 'recentBooks':
  719. case 'refresh':
  720. if (!this.mostRecentBookReactive)
  721. classResult = classDisabled;
  722. break;
  723. }
  724. }
  725. return classResult;
  726. }
  727. async activateClickMapPage() {
  728. if (this.clickControl && this.showClickMapPage && !this.clickMapActive) {
  729. this.clickMapActive = true;
  730. await this.$refs.clickMapPage.slowDisappear();
  731. this.clickMapActive = false;
  732. }
  733. }
  734. get activePage() {
  735. let result = '';
  736. if (this.progressActive)
  737. result = 'ProgressPage';
  738. else if (this.loaderActive)
  739. result = 'LoaderPage';
  740. else if (this.mostRecentBookReactive)
  741. result = 'TextPage';
  742. if (!result && !this.loading) {
  743. this.loaderActive = true;
  744. result = 'LoaderPage';
  745. }
  746. if (result != 'TextPage') {
  747. this.$root.$emit('set-app-title');
  748. }
  749. // на LoaderPage всегда показываем toolBar
  750. if (result == 'LoaderPage' && !this.toolBarActive) {
  751. this.toolBarToggle();
  752. }
  753. if (this.lastActivePage != result && result == 'TextPage') {
  754. //акивируем страницу с текстом
  755. this.$nextTick(async() => {
  756. const last = this.mostRecentBookReactive;
  757. const isParsed = await bookManager.hasBookParsed(last);
  758. if (!isParsed) {
  759. this.$root.$emit('set-app-title');
  760. return;
  761. }
  762. this.updateRoute();
  763. const textPage = this.$refs.page;
  764. if (textPage.showBook) {
  765. this.textPage = textPage;
  766. textPage.lastBook = last;
  767. textPage.bookPos = (last.bookPos !== undefined ? last.bookPos : 0);
  768. textPage.showBook();
  769. }
  770. });
  771. }
  772. this.lastActivePage = result;
  773. return result;
  774. }
  775. async loadBook(opts) {
  776. if (!opts || !opts.url) {
  777. this.mostRecentBook();
  778. return;
  779. }
  780. let url = encodeURI(decodeURI(opts.url));
  781. if ((url.indexOf('http://') != 0) && (url.indexOf('https://') != 0) &&
  782. (url.indexOf('file://') != 0))
  783. url = 'http://' + url;
  784. // уже просматривается сейчас
  785. const lastBook = (this.textPage ? this.textPage.lastBook : null);
  786. if (!opts.force && lastBook && lastBook.url == url &&
  787. (!opts.path || opts.path == lastBook.path) &&
  788. await bookManager.hasBookParsed(lastBook)) {
  789. this.loaderActive = false;
  790. return;
  791. }
  792. this.progressActive = true;
  793. await this.$nextTick();
  794. const progress = this.$refs.page;
  795. this.actionList = [];
  796. this.actionCur = -1;
  797. try {
  798. progress.show();
  799. progress.setState({state: 'parse'});
  800. // есть ли среди недавних
  801. const key = bookManager.keyFromUrl(url);
  802. let wasOpened = await bookManager.getRecentBook({key});
  803. wasOpened = (wasOpened ? wasOpened : {});
  804. const bookPos = (opts.bookPos !== undefined ? opts.bookPos : wasOpened.bookPos);
  805. const bookPosSeen = (opts.bookPos !== undefined ? opts.bookPos : wasOpened.bookPosSeen);
  806. let book = null;
  807. if (!opts.force) {
  808. // пытаемся загрузить и распарсить книгу в менеджере из локального кэша
  809. const bookParsed = await bookManager.getBook({url, path: opts.path}, (prog) => {
  810. progress.setState({progress: prog});
  811. });
  812. // если есть в локальном кэше
  813. if (bookParsed) {
  814. await bookManager.setRecentBook(Object.assign({bookPos, bookPosSeen}, bookParsed));
  815. this.mostRecentBook();
  816. this.addAction(bookPos);
  817. this.loaderActive = false;
  818. progress.hide(); this.progressActive = false;
  819. this.blinkCachedLoadMessage();
  820. this.checkBookPosPercent();
  821. await this.activateClickMapPage();
  822. return;
  823. }
  824. // иначе идем на сервер
  825. // пытаемся загрузить готовый файл с сервера
  826. if (wasOpened.path) {
  827. progress.setState({totalSteps: 5});
  828. try {
  829. const resp = await readerApi.loadCachedBook(wasOpened.path, (state) => {
  830. progress.setState(state);
  831. });
  832. book = Object.assign({}, wasOpened, {data: resp.data});
  833. } catch (e) {
  834. //молчим
  835. }
  836. }
  837. }
  838. progress.setState({totalSteps: 5});
  839. // не удалось, скачиваем книгу полностью с конвертацией
  840. let loadCached = true;
  841. if (!book) {
  842. book = await readerApi.loadBook({url, enableSitesFilter: this.enableSitesFilter}, (state) => {
  843. progress.setState(state);
  844. });
  845. loadCached = false;
  846. }
  847. // добавляем в bookManager
  848. progress.setState({state: 'parse', step: 5});
  849. const addedBook = await bookManager.addBook(book, (prog) => {
  850. progress.setState({progress: prog});
  851. });
  852. // добавляем в историю
  853. await bookManager.setRecentBook(Object.assign({bookPos, bookPosSeen}, addedBook));
  854. this.mostRecentBook();
  855. this.addAction(bookPos);
  856. this.updateRoute(true);
  857. this.loaderActive = false;
  858. progress.hide(); this.progressActive = false;
  859. if (loadCached) {
  860. this.blinkCachedLoadMessage();
  861. } else
  862. this.stopBlink = true;
  863. this.checkBookPosPercent();
  864. await this.activateClickMapPage();
  865. } catch (e) {
  866. progress.hide(); this.progressActive = false;
  867. this.loaderActive = true;
  868. this.$alert(e.message, 'Ошибка', {type: 'error'});
  869. }
  870. }
  871. async loadFile(opts) {
  872. this.progressActive = true;
  873. await this.$nextTick();
  874. const progress = this.$refs.page;
  875. try {
  876. progress.show();
  877. progress.setState({state: 'upload'});
  878. const url = await readerApi.uploadFile(opts.file, this.config.maxUploadFileSize, (state) => {
  879. progress.setState(state);
  880. });
  881. progress.hide(); this.progressActive = false;
  882. await this.loadBook({url});
  883. } catch (e) {
  884. progress.hide(); this.progressActive = false;
  885. this.loaderActive = true;
  886. this.$alert(e.message, 'Ошибка', {type: 'error'});
  887. }
  888. }
  889. blinkCachedLoadMessage() {
  890. if (!this.blinkCachedLoad)
  891. return;
  892. this.blinkCount = 30;
  893. if (!this.inBlink) {
  894. this.inBlink = true;
  895. this.stopBlink = false;
  896. this.$nextTick(async() => {
  897. let page = this.$refs.page;
  898. while (this.blinkCount) {
  899. this.showRefreshIcon = !this.showRefreshIcon;
  900. if (page && page.blinkCachedLoadMessage)
  901. page.blinkCachedLoadMessage(this.showRefreshIcon);
  902. await utils.sleep(500);
  903. if (this.stopBlink)
  904. break;
  905. this.blinkCount--;
  906. page = this.$refs.page;
  907. }
  908. this.showRefreshIcon = true;
  909. this.inBlink = false;
  910. if (page && page.blinkCachedLoadMessage)
  911. page.blinkCachedLoadMessage('finish');
  912. });
  913. }
  914. }
  915. keyHook(event) {
  916. if (this.$root.rootRoute == '/reader') {
  917. let handled = false;
  918. if (!handled && this.helpActive)
  919. handled = this.$refs.helpPage.keyHook(event);
  920. if (!handled && this.settingsActive)
  921. handled = this.$refs.settingsPage.keyHook(event);
  922. if (!handled && this.recentBooksActive)
  923. handled = this.$refs.recentBooksPage.keyHook(event);
  924. if (!handled && this.setPositionActive)
  925. handled = this.$refs.setPositionPage.keyHook(event);
  926. if (!handled && this.searchActive)
  927. handled = this.$refs.searchPage.keyHook(event);
  928. if (!handled && this.copyTextActive)
  929. handled = this.$refs.copyTextPage.keyHook(event);
  930. if (!handled && this.$refs.page && this.$refs.page.keyHook)
  931. handled = this.$refs.page.keyHook(event);
  932. if (!handled && event.type == 'keydown') {
  933. if (event.code == 'Escape')
  934. this.loaderToggle();
  935. if (this.activePage == 'TextPage') {
  936. switch (event.code) {
  937. case 'KeyH':
  938. case 'F1':
  939. this.helpToggle();
  940. event.preventDefault();
  941. event.stopPropagation();
  942. break;
  943. case 'KeyZ':
  944. this.scrollingToggle();
  945. break;
  946. case 'KeyP':
  947. this.setPositionToggle();
  948. break;
  949. case 'KeyF':
  950. if (event.ctrlKey) {
  951. this.searchToggle();
  952. event.preventDefault();
  953. event.stopPropagation();
  954. }
  955. break;
  956. case 'KeyC':
  957. if (event.ctrlKey) {
  958. this.copyTextToggle();
  959. event.preventDefault();
  960. event.stopPropagation();
  961. }
  962. break;
  963. case 'KeyR':
  964. this.refreshBook();
  965. break;
  966. case 'KeyX':
  967. this.recentBooksToggle();
  968. event.preventDefault();
  969. event.stopPropagation();
  970. break;
  971. case 'KeyO':
  972. this.offlineModeToggle();
  973. break;
  974. case 'KeyS':
  975. this.settingsToggle();
  976. break;
  977. }
  978. }
  979. }
  980. }
  981. }
  982. }
  983. //-----------------------------------------------------------------------------
  984. </script>
  985. <style scoped>
  986. .el-container {
  987. padding: 0;
  988. margin: 0;
  989. height: 100%;
  990. }
  991. .el-header {
  992. padding-left: 5px;
  993. padding-right: 5px;
  994. background-color: #1B695F;
  995. color: #000;
  996. overflow-x: auto;
  997. overflow-y: hidden;
  998. }
  999. .header {
  1000. display: flex;
  1001. justify-content: space-between;
  1002. }
  1003. .el-main {
  1004. position: relative;
  1005. display: flex;
  1006. padding: 0;
  1007. margin: 0;
  1008. background-color: #EBE2C9;
  1009. color: #000;
  1010. }
  1011. .tool-button {
  1012. margin: 0 2px 0 2px;
  1013. padding: 0;
  1014. color: #3E843E;
  1015. background-color: #E6EDF4;
  1016. margin-top: 5px;
  1017. height: 38px;
  1018. width: 38px;
  1019. border: 0;
  1020. box-shadow: 3px 3px 5px black;
  1021. }
  1022. .tool-button + .tool-button {
  1023. margin: 0 2px 0 2px;
  1024. }
  1025. .tool-button:hover {
  1026. background-color: white;
  1027. }
  1028. .tool-button-active {
  1029. box-shadow: 0 0 0;
  1030. color: white;
  1031. background-color: #8AB45F;
  1032. position: relative;
  1033. top: 1px;
  1034. left: 1px;
  1035. }
  1036. .tool-button-active:hover {
  1037. color: white;
  1038. background-color: #81C581;
  1039. }
  1040. .tool-button-disabled {
  1041. color: lightgray;
  1042. background-color: gray;
  1043. }
  1044. .tool-button-disabled:hover {
  1045. color: lightgray;
  1046. background-color: gray;
  1047. }
  1048. i {
  1049. font-size: 200%;
  1050. }
  1051. .space {
  1052. width: 10px;
  1053. display: inline-block;
  1054. }
  1055. .clear {
  1056. color: rgba(0,0,0,0);
  1057. }
  1058. .clickable {
  1059. color: blue;
  1060. text-decoration: underline;
  1061. cursor: pointer;
  1062. }
  1063. </style>