Reader.vue 44 KB

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