Reader.vue 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238
  1. <template>
  2. <div class="column no-wrap">
  3. <div ref="header" class="header" v-show="toolBarActive">
  4. <div ref="buttons" class="row justify-between no-wrap">
  5. <button ref="loader" class="tool-button" :class="buttonActiveClass('loader')" @click="buttonClick('loader')" v-ripple>
  6. <q-icon name="la la-arrow-left" size="30px"/>
  7. <q-tooltip :delay="1500" anchor="bottom right" content-style="font-size: 80%">Загрузить книгу</q-tooltip>
  8. </button>
  9. <div>
  10. <button ref="undoAction" v-show="showToolButton['undoAction']" class="tool-button" :class="buttonActiveClass('undoAction')" @click="buttonClick('undoAction')" v-ripple>
  11. <q-icon name="la la-angle-left" size="30px"/>
  12. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">Действие назад</q-tooltip>
  13. </button>
  14. <button ref="redoAction" v-show="showToolButton['redoAction']" class="tool-button" :class="buttonActiveClass('redoAction')" @click="buttonClick('redoAction')" v-ripple>
  15. <q-icon name="la la-angle-right" size="30px"/>
  16. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">Действие вперед</q-tooltip>
  17. </button>
  18. <div class="space"></div>
  19. <button ref="fullScreen" v-show="showToolButton['fullScreen']" class="tool-button" :class="buttonActiveClass('fullScreen')" @click="buttonClick('fullScreen')" v-ripple>
  20. <q-icon :name="(fullScreenActive ? 'la la-compress-arrows-alt': 'la la-expand-arrows-alt')" size="30px"/>
  21. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">На весь экран</q-tooltip>
  22. </button>
  23. <button ref="scrolling" v-show="showToolButton['scrolling']" class="tool-button" :class="buttonActiveClass('scrolling')" @click="buttonClick('scrolling')" v-ripple>
  24. <q-icon name="la la-film" size="32px"/>
  25. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">Плавный скроллинг</q-tooltip>
  26. </button>
  27. <button ref="setPosition" v-show="showToolButton['setPosition']" class="tool-button" :class="buttonActiveClass('setPosition')" @click="buttonClick('setPosition')" v-ripple>
  28. <q-icon name="la la-angle-double-right" size="30px"/>
  29. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">На страницу</q-tooltip>
  30. </button>
  31. <button ref="search" v-show="showToolButton['search']" class="tool-button" :class="buttonActiveClass('search')" @click="buttonClick('search')" v-ripple>
  32. <q-icon name="la la-search" size="30px"/>
  33. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">Найти в тексте</q-tooltip>
  34. </button>
  35. <button ref="copyText" v-show="showToolButton['copyText']" class="tool-button" :class="buttonActiveClass('copyText')" @click="buttonClick('copyText')" v-ripple>
  36. <q-icon name="la la-copy" size="32px"/>
  37. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">Скопировать текст со страницы</q-tooltip>
  38. </button>
  39. <button ref="refresh" v-show="showToolButton['refresh']" class="tool-button" :class="buttonActiveClass('refresh')" @click="buttonClick('refresh')" v-ripple>
  40. <q-icon name="la la-sync" size="30px"/>
  41. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">Принудительно обновить книгу в обход кэша</q-tooltip>
  42. </button>
  43. <div class="space"></div>
  44. <button ref="offlineMode" v-show="showToolButton['offlineMode']" class="tool-button" :class="buttonActiveClass('offlineMode')" @click="buttonClick('offlineMode')" v-ripple>
  45. <q-icon name="la la-unlink" size="30px"/>
  46. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">Автономный режим (без интернета)</q-tooltip>
  47. </button>
  48. <button ref="recentBooks" v-show="showToolButton['recentBooks']" class="tool-button" :class="buttonActiveClass('recentBooks')" @click="buttonClick('recentBooks')" v-ripple>
  49. <q-icon name="la la-book-open" size="32px"/>
  50. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">Открыть недавние</q-tooltip>
  51. </button>
  52. </div>
  53. <button ref="settings" class="tool-button" :class="buttonActiveClass('settings')" @click="buttonClick('settings')" v-ripple>
  54. <q-icon name="la la-cog" size="32px"/>
  55. <q-tooltip :delay="1500" anchor="bottom left" content-style="font-size: 80%">Настроить</q-tooltip>
  56. </button>
  57. </div>
  58. </div>
  59. <div class="main col row relative-position">
  60. <keep-alive>
  61. <component ref="page" class="col" :is="activePage"
  62. @load-book="loadBook"
  63. @load-file="loadFile"
  64. @book-pos-changed="bookPosChanged"
  65. @tool-bar-toggle="toolBarToggle"
  66. @full-screen-toogle="fullScreenToggle"
  67. @stop-scrolling="stopScrolling"
  68. @scrolling-toggle="scrollingToggle"
  69. @help-toggle="helpToggle"
  70. @donate-toggle="donateToggle"
  71. ></component>
  72. </keep-alive>
  73. <SetPositionPage v-if="setPositionActive" ref="setPositionPage" @set-position-toggle="setPositionToggle" @book-pos-changed="bookPosChanged"></SetPositionPage>
  74. <SearchPage v-show="searchActive" ref="searchPage"
  75. @search-toggle="searchToggle"
  76. @book-pos-changed="bookPosChanged"
  77. @start-text-search="startTextSearch"
  78. @stop-text-search="stopTextSearch">
  79. </SearchPage>
  80. <CopyTextPage v-if="copyTextActive" ref="copyTextPage" @copy-text-toggle="copyTextToggle"></CopyTextPage>
  81. <RecentBooksPage v-show="recentBooksActive" ref="recentBooksPage" @load-book="loadBook" @recent-books-close="recentBooksClose"></RecentBooksPage>
  82. <SettingsPage v-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. </div>
  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. const page = this.$refs.page;
  522. if (this.setPositionActive && this.activePage == 'TextPage' && page.parsed) {
  523. this.closeAllTextPages();
  524. this.setPositionActive = true;
  525. this.$nextTick(() => {
  526. const recent = this.mostRecentBook();
  527. this.$refs.setPositionPage.init(recent.bookPos, recent.textLength - 1);
  528. });
  529. } else {
  530. this.setPositionActive = false;
  531. }
  532. }
  533. stopScrolling() {
  534. if (this.scrollingActive)
  535. this.scrollingToggle();
  536. }
  537. scrollingToggle() {
  538. this.scrollingActive = !this.scrollingActive;
  539. if (this.activePage == 'TextPage') {
  540. const page = this.$refs.page;
  541. if (this.scrollingActive) {
  542. page.startTextScrolling();
  543. } else {
  544. page.stopTextScrolling();
  545. }
  546. }
  547. if (!this.scrollingActive) {
  548. this.scrollingSetRecentBook.flush();
  549. }
  550. }
  551. stopSearch() {
  552. if (this.searchActive)
  553. this.searchToggle();
  554. }
  555. startTextSearch(opts) {
  556. if (this.activePage == 'TextPage')
  557. this.$refs.page.startSearch(opts.needle);
  558. }
  559. stopTextSearch() {
  560. if (this.activePage == 'TextPage')
  561. this.$refs.page.stopSearch();
  562. }
  563. searchToggle() {
  564. this.searchActive = !this.searchActive;
  565. const page = this.$refs.page;
  566. if (this.searchActive && this.activePage == 'TextPage' && page.parsed) {
  567. this.closeAllTextPages();
  568. this.searchActive = true;
  569. this.$nextTick(() => {
  570. this.$refs.searchPage.init(page.parsed);
  571. });
  572. } else {
  573. this.stopTextSearch();
  574. this.searchActive = false;
  575. }
  576. }
  577. copyTextToggle() {
  578. this.copyTextActive = !this.copyTextActive;
  579. const page = this.$refs.page;
  580. if (this.copyTextActive && this.activePage == 'TextPage' && page.parsed) {
  581. this.closeAllTextPages();
  582. this.copyTextActive = true;
  583. this.$nextTick(() => {
  584. this.$refs.copyTextPage.init(this.mostRecentBook().bookPos, page.parsed, this.copyFullText);
  585. });
  586. } else {
  587. this.copyTextActive = false;
  588. }
  589. }
  590. recentBooksClose() {
  591. this.recentBooksActive = false;
  592. }
  593. recentBooksToggle() {
  594. this.recentBooksActive = !this.recentBooksActive;
  595. if (this.recentBooksActive) {
  596. this.closeAllTextPages();
  597. this.$refs.recentBooksPage.init();
  598. this.recentBooksActive = true;
  599. } else {
  600. this.recentBooksActive = false;
  601. }
  602. }
  603. offlineModeToggle() {
  604. this.offlineModeActive = !this.offlineModeActive;
  605. this.$refs.serverStorage.offlineModeActive = this.offlineModeActive;
  606. }
  607. settingsToggle() {
  608. this.settingsActive = !this.settingsActive;
  609. if (this.settingsActive) {
  610. this.closeAllTextPages();
  611. this.settingsActive = true;
  612. this.$nextTick(() => {
  613. this.$refs.settingsPage.init();
  614. });
  615. } else {
  616. this.settingsActive = false;
  617. }
  618. }
  619. helpToggle() {
  620. this.helpActive = !this.helpActive;
  621. if (this.helpActive) {
  622. this.closeAllTextPages();
  623. this.helpActive = true;
  624. }
  625. }
  626. donateToggle() {
  627. this.helpToggle();
  628. if (this.helpActive) {
  629. this.$nextTick(() => {
  630. this.$refs.helpPage.activateDonateHelpPage();
  631. });
  632. }
  633. }
  634. versionHistoryToggle() {
  635. this.helpToggle();
  636. if (this.helpActive) {
  637. this.$nextTick(() => {
  638. this.$refs.helpPage.activateVersionHistoryHelpPage();
  639. });
  640. }
  641. }
  642. refreshBook() {
  643. if (this.mostRecentBook()) {
  644. this.loadBook({url: this.mostRecentBook().url, force: true});
  645. }
  646. }
  647. buttonClick(button) {
  648. const activeClass = this.buttonActiveClass(button);
  649. this.$refs[button].blur();
  650. if (activeClass['tool-button-disabled'])
  651. return;
  652. switch (button) {
  653. case 'loader':
  654. this.loaderToggle();
  655. break;
  656. case 'undoAction':
  657. if (this.actionCur > 0) {
  658. this.actionCur--;
  659. this.bookPosChanged({bookPos: this.actionList[this.actionCur]});
  660. }
  661. break;
  662. case 'redoAction':
  663. if (this.actionCur < this.actionList.length - 1) {
  664. this.actionCur++;
  665. this.bookPosChanged({bookPos: this.actionList[this.actionCur]});
  666. }
  667. break;
  668. case 'fullScreen':
  669. this.fullScreenToggle();
  670. break;
  671. case 'setPosition':
  672. this.setPositionToggle();
  673. break;
  674. case 'scrolling':
  675. this.scrollingToggle();
  676. break;
  677. case 'search':
  678. this.searchToggle();
  679. break;
  680. case 'copyText':
  681. this.copyTextToggle();
  682. break;
  683. case 'refresh':
  684. this.refreshBook();
  685. break;
  686. case 'recentBooks':
  687. this.recentBooksToggle();
  688. break;
  689. case 'offlineMode':
  690. this.offlineModeToggle();
  691. break;
  692. case 'settings':
  693. this.settingsToggle();
  694. break;
  695. }
  696. }
  697. buttonActiveClass(button) {
  698. const classActive = { 'tool-button-active': true, 'tool-button-active:hover': true };
  699. const classDisabled = { 'tool-button-disabled': true, 'tool-button-disabled:hover': true };
  700. let classResult = {};
  701. switch (button) {
  702. case 'loader':
  703. case 'fullScreen':
  704. case 'setPosition':
  705. case 'scrolling':
  706. case 'search':
  707. case 'copyText':
  708. case 'refresh':
  709. case 'offlineMode':
  710. case 'recentBooks':
  711. case 'settings':
  712. if (this.progressActive) {
  713. classResult = classDisabled;
  714. } else if (this[`${button}Active`]) {
  715. classResult = classActive;
  716. }
  717. break;
  718. case 'undoAction':
  719. if (this.actionCur <= 0)
  720. classResult = classDisabled;
  721. break;
  722. case 'redoAction':
  723. if (this.actionCur == this.actionList.length - 1)
  724. classResult = classDisabled;
  725. break;
  726. }
  727. if (this.activePage == 'LoaderPage' || !this.mostRecentBookReactive) {
  728. switch (button) {
  729. case 'undoAction':
  730. case 'redoAction':
  731. case 'setPosition':
  732. case 'scrolling':
  733. case 'search':
  734. case 'copyText':
  735. classResult = classDisabled;
  736. break;
  737. case 'recentBooks':
  738. case 'refresh':
  739. if (!this.mostRecentBookReactive)
  740. classResult = classDisabled;
  741. break;
  742. }
  743. }
  744. return classResult;
  745. }
  746. async activateClickMapPage() {
  747. if (this.clickControl && this.showClickMapPage && !this.clickMapActive) {
  748. this.clickMapActive = true;
  749. await this.$refs.clickMapPage.slowDisappear();
  750. this.clickMapActive = false;
  751. }
  752. }
  753. get activePage() {
  754. let result = '';
  755. if (this.progressActive)
  756. result = 'ProgressPage';
  757. else if (this.loaderActive)
  758. result = 'LoaderPage';
  759. else if (this.mostRecentBookReactive)
  760. result = 'TextPage';
  761. if (!result && !this.loading) {
  762. this.loaderActive = true;
  763. result = 'LoaderPage';
  764. }
  765. if (result != 'TextPage') {
  766. this.$root.$emit('set-app-title');
  767. }
  768. // на LoaderPage всегда показываем toolBar
  769. if (result == 'LoaderPage' && !this.toolBarActive) {
  770. this.toolBarToggle();
  771. }
  772. if (this.lastActivePage != result && result == 'TextPage') {
  773. //акивируем страницу с текстом
  774. this.$nextTick(async() => {
  775. const last = this.mostRecentBookReactive;
  776. const isParsed = await bookManager.hasBookParsed(last);
  777. if (!isParsed) {
  778. this.$root.$emit('set-app-title');
  779. return;
  780. }
  781. this.updateRoute();
  782. const textPage = this.$refs.page;
  783. if (textPage.showBook) {
  784. this.textPage = textPage;
  785. textPage.lastBook = last;
  786. textPage.bookPos = (last.bookPos !== undefined ? last.bookPos : 0);
  787. textPage.showBook();
  788. }
  789. });
  790. }
  791. this.lastActivePage = result;
  792. return result;
  793. }
  794. async loadBook(opts) {
  795. if (!opts || !opts.url) {
  796. this.mostRecentBook();
  797. return;
  798. }
  799. this.closeAllTextPages();
  800. let url = encodeURI(decodeURI(opts.url));
  801. if ((url.indexOf('http://') != 0) && (url.indexOf('https://') != 0) &&
  802. (url.indexOf('file://') != 0))
  803. url = 'http://' + url;
  804. // уже просматривается сейчас
  805. const lastBook = (this.textPage ? this.textPage.lastBook : null);
  806. if (!opts.force && lastBook && lastBook.url == url &&
  807. (!opts.path || opts.path == lastBook.path) &&
  808. await bookManager.hasBookParsed(lastBook)) {
  809. this.loaderActive = false;
  810. return;
  811. }
  812. this.progressActive = true;
  813. await this.$nextTick();
  814. const progress = this.$refs.page;
  815. this.actionList = [];
  816. this.actionCur = -1;
  817. try {
  818. progress.show();
  819. progress.setState({state: 'parse'});
  820. // есть ли среди недавних
  821. const key = bookManager.keyFromUrl(url);
  822. let wasOpened = await bookManager.getRecentBook({key});
  823. wasOpened = (wasOpened ? wasOpened : {});
  824. const bookPos = (opts.bookPos !== undefined ? opts.bookPos : wasOpened.bookPos);
  825. const bookPosSeen = (opts.bookPos !== undefined ? opts.bookPos : wasOpened.bookPosSeen);
  826. let book = null;
  827. if (!opts.force) {
  828. // пытаемся загрузить и распарсить книгу в менеджере из локального кэша
  829. const bookParsed = await bookManager.getBook({url, path: opts.path}, (prog) => {
  830. progress.setState({progress: prog});
  831. });
  832. // если есть в локальном кэше
  833. if (bookParsed) {
  834. await bookManager.setRecentBook(Object.assign({bookPos, bookPosSeen}, bookParsed));
  835. this.mostRecentBook();
  836. this.addAction(bookPos);
  837. this.loaderActive = false;
  838. progress.hide(); this.progressActive = false;
  839. this.blinkCachedLoadMessage();
  840. this.checkBookPosPercent();
  841. await this.activateClickMapPage();
  842. return;
  843. }
  844. // иначе идем на сервер
  845. // пытаемся загрузить готовый файл с сервера
  846. if (wasOpened.path) {
  847. progress.setState({totalSteps: 5});
  848. try {
  849. const resp = await readerApi.loadCachedBook(wasOpened.path, (state) => {
  850. progress.setState(state);
  851. });
  852. book = Object.assign({}, wasOpened, {data: resp.data});
  853. } catch (e) {
  854. //молчим
  855. }
  856. }
  857. }
  858. progress.setState({totalSteps: 5});
  859. // не удалось, скачиваем книгу полностью с конвертацией
  860. let loadCached = true;
  861. if (!book) {
  862. book = await readerApi.loadBook({url, enableSitesFilter: this.enableSitesFilter}, (state) => {
  863. progress.setState(state);
  864. });
  865. loadCached = false;
  866. }
  867. // добавляем в bookManager
  868. progress.setState({state: 'parse', step: 5});
  869. const addedBook = await bookManager.addBook(book, (prog) => {
  870. progress.setState({progress: prog});
  871. });
  872. // добавляем в историю
  873. await bookManager.setRecentBook(Object.assign({bookPos, bookPosSeen}, addedBook));
  874. this.mostRecentBook();
  875. this.addAction(bookPos);
  876. this.updateRoute(true);
  877. this.loaderActive = false;
  878. progress.hide(); this.progressActive = false;
  879. if (loadCached) {
  880. this.blinkCachedLoadMessage();
  881. } else
  882. this.stopBlink = true;
  883. this.checkBookPosPercent();
  884. await this.activateClickMapPage();
  885. } catch (e) {
  886. progress.hide(); this.progressActive = false;
  887. this.loaderActive = true;
  888. this.$alert(e.message, 'Ошибка', {type: 'error'});
  889. }
  890. }
  891. async loadFile(opts) {
  892. this.progressActive = true;
  893. await this.$nextTick();
  894. const progress = this.$refs.page;
  895. try {
  896. progress.show();
  897. progress.setState({state: 'upload'});
  898. const url = await readerApi.uploadFile(opts.file, this.config.maxUploadFileSize, (state) => {
  899. progress.setState(state);
  900. });
  901. progress.hide(); this.progressActive = false;
  902. await this.loadBook({url});
  903. } catch (e) {
  904. progress.hide(); this.progressActive = false;
  905. this.loaderActive = true;
  906. this.$alert(e.message, 'Ошибка', {type: 'error'});
  907. }
  908. }
  909. blinkCachedLoadMessage() {
  910. if (!this.blinkCachedLoad)
  911. return;
  912. this.blinkCount = 30;
  913. if (!this.inBlink) {
  914. this.inBlink = true;
  915. this.stopBlink = false;
  916. this.$nextTick(async() => {
  917. let page = this.$refs.page;
  918. while (this.blinkCount) {
  919. this.showRefreshIcon = !this.showRefreshIcon;
  920. if (page && page.blinkCachedLoadMessage)
  921. page.blinkCachedLoadMessage(this.showRefreshIcon);
  922. await utils.sleep(500);
  923. if (this.stopBlink)
  924. break;
  925. this.blinkCount--;
  926. page = this.$refs.page;
  927. }
  928. this.showRefreshIcon = true;
  929. this.inBlink = false;
  930. if (page && page.blinkCachedLoadMessage)
  931. page.blinkCachedLoadMessage('finish');
  932. });
  933. }
  934. }
  935. keyHook(event) {
  936. if (this.$root.rootRoute() == '/reader') {
  937. let handled = false;
  938. if (!handled && this.helpActive)
  939. handled = this.$refs.helpPage.keyHook(event);
  940. if (!handled && this.settingsActive)
  941. handled = this.$refs.settingsPage.keyHook(event);
  942. if (!handled && this.recentBooksActive)
  943. handled = this.$refs.recentBooksPage.keyHook(event);
  944. if (!handled && this.setPositionActive)
  945. handled = this.$refs.setPositionPage.keyHook(event);
  946. if (!handled && this.searchActive)
  947. handled = this.$refs.searchPage.keyHook(event);
  948. if (!handled && this.copyTextActive)
  949. handled = this.$refs.copyTextPage.keyHook(event);
  950. if (!handled && this.$refs.page && this.$refs.page.keyHook)
  951. handled = this.$refs.page.keyHook(event);
  952. if (!handled && event.type == 'keydown') {
  953. if (event.code == 'Escape')
  954. this.loaderToggle();
  955. if (this.activePage == 'TextPage') {
  956. switch (event.code) {
  957. case 'KeyH':
  958. case 'F1':
  959. this.helpToggle();
  960. event.preventDefault();
  961. event.stopPropagation();
  962. break;
  963. case 'KeyZ':
  964. this.scrollingToggle();
  965. break;
  966. case 'KeyP':
  967. this.setPositionToggle();
  968. break;
  969. case 'KeyF':
  970. if (event.ctrlKey) {
  971. this.searchToggle();
  972. event.preventDefault();
  973. event.stopPropagation();
  974. }
  975. break;
  976. case 'KeyC':
  977. if (event.ctrlKey) {
  978. this.copyTextToggle();
  979. event.preventDefault();
  980. event.stopPropagation();
  981. }
  982. break;
  983. case 'KeyR':
  984. this.refreshBook();
  985. break;
  986. case 'KeyX':
  987. this.recentBooksToggle();
  988. event.preventDefault();
  989. event.stopPropagation();
  990. break;
  991. case 'KeyO':
  992. this.offlineModeToggle();
  993. break;
  994. case 'KeyS':
  995. this.settingsToggle();
  996. break;
  997. }
  998. }
  999. }
  1000. }
  1001. }
  1002. }
  1003. //-----------------------------------------------------------------------------
  1004. </script>
  1005. <style scoped>
  1006. .header {
  1007. padding-left: 5px;
  1008. padding-right: 5px;
  1009. background-color: #1B695F;
  1010. color: #000;
  1011. overflow: hidden;
  1012. height: 50px;
  1013. }
  1014. .main {
  1015. background-color: #EBE2C9;
  1016. color: #000;
  1017. }
  1018. .tool-button {
  1019. margin: 0px 2px 0 2px;
  1020. padding: 0;
  1021. color: #3E843E;
  1022. background-color: #E6EDF4;
  1023. margin-top: 5px;
  1024. height: 38px;
  1025. width: 38px;
  1026. border: 0;
  1027. border-radius: 6px;
  1028. box-shadow: 3px 3px 5px black;
  1029. outline: 0;
  1030. }
  1031. .tool-button:hover {
  1032. background-color: white;
  1033. }
  1034. .tool-button-active {
  1035. box-shadow: 0 0 0;
  1036. color: white;
  1037. background-color: #8AB45F;
  1038. position: relative;
  1039. top: 1px;
  1040. left: 1px;
  1041. }
  1042. .tool-button-active:hover {
  1043. color: white;
  1044. background-color: #81C581;
  1045. }
  1046. .tool-button-disabled {
  1047. color: lightgray;
  1048. background-color: gray;
  1049. }
  1050. .tool-button-disabled:hover {
  1051. color: lightgray;
  1052. background-color: gray;
  1053. }
  1054. .space {
  1055. width: 10px;
  1056. display: inline-block;
  1057. }
  1058. .clear {
  1059. color: rgba(0,0,0,0);
  1060. }
  1061. .clickable {
  1062. color: blue;
  1063. text-decoration: underline;
  1064. cursor: pointer;
  1065. }
  1066. </style>