Reader.vue 45 KB

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