Reader.vue 44 KB

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