Reader.vue 44 KB

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