Reader.vue 45 KB

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