Reader.vue 44 KB

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