Reader.vue 44 KB

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