Reader.vue 46 KB

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