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. delete newShowToolButton['history'];
  277. const newSettings = Object.assign({}, this.settings, { showToolButton: newShowToolButton });
  278. this.commit('reader/setSettings', newSettings);
  279. }
  280. }
  281. mounted() {
  282. this.updateHeaderMinWidth();
  283. (async() => {
  284. await bookManager.init(this.settings);
  285. bookManager.addEventListener(this.bookManagerEvent);
  286. if (this.$root.rootRoute == '/reader') {
  287. if (this.routeParamUrl) {
  288. await this.loadBook({url: this.routeParamUrl, bookPos: this.routeParamPos, force: this.routeParamRefresh});
  289. } else {
  290. this.loaderActive = true;
  291. }
  292. }
  293. this.checkSetStorageAccessKey();
  294. this.checkActivateDonateHelpPage();
  295. this.loading = false;
  296. await this.$refs.serverStorage.init();
  297. await this.showWhatsNew();
  298. await this.showMigration();
  299. })();
  300. }
  301. loadSettings() {
  302. const settings = this.settings;
  303. this.allowUrlParamBookPos = settings.allowUrlParamBookPos;
  304. this.copyFullText = settings.copyFullText;
  305. this.showClickMapPage = settings.showClickMapPage;
  306. this.clickControl = settings.clickControl;
  307. this.blinkCachedLoad = settings.blinkCachedLoad;
  308. this.showWhatsNewDialog = settings.showWhatsNewDialog;
  309. this.showMigrationDialog = settings.showMigrationDialog;
  310. this.showToolButton = settings.showToolButton;
  311. this.updateHeaderMinWidth();
  312. }
  313. updateHeaderMinWidth() {
  314. const showButtonCount = Object.values(this.showToolButton).reduce((a, b) => a + (b ? 1 : 0), 0);
  315. if (this.$refs.header)
  316. this.$refs.header.style.minWidth = 65*showButtonCount + 'px';
  317. }
  318. checkSetStorageAccessKey() {
  319. const q = this.$route.query;
  320. if (q['setStorageAccessKey']) {
  321. this.$router.replace(`/reader`);
  322. this.settingsToggle();
  323. this.$nextTick(() => {
  324. this.$refs.settingsPage.enterServerStorageKey(
  325. Buffer.from(utils.fromBase58(q['setStorageAccessKey'])).toString()
  326. );
  327. });
  328. }
  329. }
  330. checkActivateDonateHelpPage() {
  331. const q = this.$route.query;
  332. if (q['donate']) {
  333. this.$router.replace(`/reader`);
  334. this.helpToggle();
  335. this.$nextTick(() => {
  336. this.$refs.helpPage.activateDonateHelpPage();
  337. });
  338. }
  339. }
  340. checkBookPosPercent() {
  341. const q = this.$route.query;
  342. if (q['__pp']) {
  343. let pp = q['__pp'];
  344. if (pp) {
  345. pp = parseFloat(pp) || 0;
  346. const recent = this.mostRecentBook();
  347. (async() => {
  348. await utils.sleep(100);
  349. this.bookPos = Math.floor(recent.textLength*pp/100);
  350. })();
  351. }
  352. }
  353. }
  354. async showWhatsNew() {
  355. await utils.sleep(2000);
  356. const whatsNew = versionHistory[0];
  357. if (this.showWhatsNewDialog &&
  358. whatsNew.showUntil >= utils.formatDate(new Date(), 'coDate') &&
  359. whatsNew.header != this.whatsNewContentHash) {
  360. this.whatsNewContent = 'Версия ' + whatsNew.header + whatsNew.content;
  361. this.whatsNewVisible = true;
  362. }
  363. }
  364. async showMigration() {
  365. await utils.sleep(3000);
  366. if (!this.settingsActive &&
  367. this.mode == 'omnireader' && this.showMigrationDialog && this.migrationRemindDate != utils.formatDate(new Date(), 'coDate')) {
  368. if (window.location.protocol == 'http:') {
  369. this.migrationVisible1 = true;
  370. } else if (window.location.protocol == 'https:') {
  371. this.migrationVisible2 = true;
  372. }
  373. }
  374. }
  375. migrationDialogDisable() {
  376. this.migrationVisible1 = false;
  377. this.migrationVisible2 = false;
  378. if (this.showMigrationDialog) {
  379. const newSettings = Object.assign({}, this.settings, { showMigrationDialog: false });
  380. this.commit('reader/setSettings', newSettings);
  381. }
  382. }
  383. migrationDialogRemind() {
  384. this.migrationVisible1 = false;
  385. this.migrationVisible2 = false;
  386. this.commit('reader/setMigrationRemindDate', utils.formatDate(new Date(), 'coDate'));
  387. }
  388. openVersionHistory() {
  389. this.whatsNewVisible = false;
  390. this.versionHistoryToggle();
  391. }
  392. whatsNewDisable() {
  393. this.whatsNewVisible = false;
  394. const whatsNew = versionHistory[0];
  395. this.commit('reader/setWhatsNewContentHash', whatsNew.header);
  396. }
  397. get routeParamPos() {
  398. let result = undefined;
  399. const q = this.$route.query;
  400. if (q['__p']) {
  401. result = q['__p'];
  402. if (Array.isArray(result))
  403. result = result[0];
  404. }
  405. return (result ? parseInt(result, 10) || 0 : result);
  406. }
  407. updateRoute(isNewRoute) {
  408. if (this.loading)
  409. return;
  410. const recent = this.mostRecentBook();
  411. const pos = (recent && recent.bookPos && this.allowUrlParamBookPos ? `__p=${recent.bookPos}&` : '');
  412. const url = (recent ? `url=${recent.url}` : '');
  413. if (isNewRoute)
  414. this.$router.push(`/reader?${pos}${url}`).catch(() => {});
  415. else
  416. this.$router.replace(`/reader?${pos}${url}`).catch(() => {});
  417. }
  418. get mode() {
  419. return this.$store.state.config.mode;
  420. }
  421. get routeParamUrl() {
  422. let result = '';
  423. const path = this.$route.fullPath;
  424. const i = path.indexOf('url=');
  425. if (i >= 0) {
  426. result = path.substr(i + 4);
  427. }
  428. return decodeURIComponent(result);
  429. }
  430. get routeParamRefresh() {
  431. const q = this.$route.query;
  432. return !!q['__refresh'];
  433. }
  434. bookPosChanged(event) {
  435. if (event.bookPosSeen !== undefined)
  436. this.bookPosSeen = event.bookPosSeen;
  437. this.bookPos = event.bookPos;
  438. this.debouncedUpdateRoute();
  439. }
  440. async bookManagerEvent(eventName) {
  441. if (eventName == 'recent-changed') {
  442. if (this.recentBooksActive) {
  443. await this.$refs.recentBooksPage.updateTableData();
  444. }
  445. const oldBook = this.mostRecentBookReactive;
  446. const newBook = bookManager.mostRecentBook();
  447. if (oldBook && newBook) {
  448. if (oldBook.key != newBook.key) {
  449. this.loadingBook = true;
  450. try {
  451. await this.loadBook(newBook);
  452. } finally {
  453. this.loadingBook = false;
  454. }
  455. } else if (oldBook.bookPos != newBook.bookPos) {
  456. while (this.loadingBook) await utils.sleep(100);
  457. this.bookPosChanged({bookPos: newBook.bookPos});
  458. }
  459. }
  460. }
  461. }
  462. get toolBarActive() {
  463. return this.reader.toolBarActive;
  464. }
  465. mostRecentBook() {
  466. const result = bookManager.mostRecentBook();
  467. this.mostRecentBookReactive = result;
  468. return result;
  469. }
  470. get settings() {
  471. return this.$store.state.reader.settings;
  472. }
  473. get whatsNewContentHash() {
  474. return this.$store.state.reader.whatsNewContentHash;
  475. }
  476. get migrationRemindDate() {
  477. return this.$store.state.reader.migrationRemindDate;
  478. }
  479. addAction(pos) {
  480. let a = this.actionList;
  481. if (!a.length || a[a.length - 1] != pos) {
  482. a.push(pos);
  483. if (a.length > 20)
  484. a.shift();
  485. this.actionCur = a.length - 1;
  486. }
  487. }
  488. toolBarToggle() {
  489. this.commit('reader/setToolBarActive', !this.toolBarActive);
  490. this.$root.$emit('resize');
  491. }
  492. fullScreenToggle() {
  493. this.fullScreenActive = !this.fullScreenActive;
  494. if (this.fullScreenActive) {
  495. const element = document.documentElement;
  496. if (element.requestFullscreen) {
  497. element.requestFullscreen();
  498. } else if (element.webkitrequestFullscreen) {
  499. element.webkitRequestFullscreen();
  500. } else if (element.mozRequestFullscreen) {
  501. element.mozRequestFullScreen();
  502. }
  503. } else {
  504. if (document.cancelFullScreen) {
  505. document.cancelFullScreen();
  506. } else if (document.mozCancelFullScreen) {
  507. document.mozCancelFullScreen();
  508. } else if (document.webkitCancelFullScreen) {
  509. document.webkitCancelFullScreen();
  510. }
  511. }
  512. }
  513. closeAllTextPages() {
  514. this.setPositionActive = false;
  515. this.copyTextActive = false;
  516. this.recentBooksActive = false;
  517. this.settingsActive = false;
  518. this.stopScrolling();
  519. this.stopSearch();
  520. this.helpActive = false;
  521. }
  522. loaderToggle() {
  523. this.loaderActive = !this.loaderActive;
  524. if (this.loaderActive) {
  525. this.closeAllTextPages();
  526. }
  527. }
  528. setPositionToggle() {
  529. this.setPositionActive = !this.setPositionActive;
  530. if (this.setPositionActive && this.activePage == 'TextPage' && this.mostRecentBook()) {
  531. this.closeAllTextPages();
  532. this.setPositionActive = true;
  533. this.$nextTick(() => {
  534. const recent = this.mostRecentBook();
  535. this.$refs.setPositionPage.init(recent.bookPos, recent.textLength - 1);
  536. });
  537. } else {
  538. this.setPositionActive = false;
  539. }
  540. }
  541. stopScrolling() {
  542. if (this.scrollingActive)
  543. this.scrollingToggle();
  544. }
  545. scrollingToggle() {
  546. this.scrollingActive = !this.scrollingActive;
  547. if (this.activePage == 'TextPage') {
  548. const page = this.$refs.page;
  549. if (this.scrollingActive) {
  550. page.startTextScrolling();
  551. } else {
  552. page.stopTextScrolling();
  553. }
  554. }
  555. }
  556. stopSearch() {
  557. if (this.searchActive)
  558. this.searchToggle();
  559. }
  560. startTextSearch(opts) {
  561. if (this.activePage == 'TextPage')
  562. this.$refs.page.startSearch(opts.needle);
  563. }
  564. stopTextSearch() {
  565. if (this.activePage == 'TextPage')
  566. this.$refs.page.stopSearch();
  567. }
  568. searchToggle() {
  569. this.searchActive = !this.searchActive;
  570. const page = this.$refs.page;
  571. if (this.searchActive && this.activePage == 'TextPage' && page.parsed) {
  572. this.closeAllTextPages();
  573. this.searchActive = true;
  574. this.$nextTick(() => {
  575. this.$refs.searchPage.init(page.parsed);
  576. });
  577. } else {
  578. this.stopTextSearch();
  579. this.searchActive = false;
  580. }
  581. }
  582. copyTextToggle() {
  583. this.copyTextActive = !this.copyTextActive;
  584. const page = this.$refs.page;
  585. if (this.copyTextActive && this.activePage == 'TextPage' && page.parsed) {
  586. this.closeAllTextPages();
  587. this.copyTextActive = true;
  588. this.$nextTick(() => {
  589. this.$refs.copyTextPage.init(this.mostRecentBook().bookPos, page.parsed, this.copyFullText);
  590. });
  591. } else {
  592. this.copyTextActive = false;
  593. }
  594. }
  595. recentBooksToggle() {
  596. this.recentBooksActive = !this.recentBooksActive;
  597. if (this.recentBooksActive) {
  598. this.closeAllTextPages();
  599. this.$refs.recentBooksPage.init();
  600. this.recentBooksActive = true;
  601. } else {
  602. this.recentBooksActive = false;
  603. }
  604. }
  605. settingsToggle() {
  606. this.settingsActive = !this.settingsActive;
  607. if (this.settingsActive) {
  608. this.closeAllTextPages();
  609. this.settingsActive = true;
  610. this.$nextTick(() => {
  611. this.$refs.settingsPage.init();
  612. });
  613. } else {
  614. this.settingsActive = false;
  615. }
  616. }
  617. helpToggle() {
  618. this.helpActive = !this.helpActive;
  619. if (this.helpActive) {
  620. this.closeAllTextPages();
  621. this.helpActive = true;
  622. }
  623. }
  624. donateToggle() {
  625. this.helpToggle();
  626. if (this.helpActive) {
  627. this.$nextTick(() => {
  628. this.$refs.helpPage.activateDonateHelpPage();
  629. });
  630. }
  631. }
  632. versionHistoryToggle() {
  633. this.helpToggle();
  634. if (this.helpActive) {
  635. this.$nextTick(() => {
  636. this.$refs.helpPage.activateVersionHistoryHelpPage();
  637. });
  638. }
  639. }
  640. refreshBook() {
  641. if (this.mostRecentBook()) {
  642. this.loadBook({url: this.mostRecentBook().url, force: true});
  643. }
  644. }
  645. buttonClick(button) {
  646. const activeClass = this.buttonActiveClass(button);
  647. this.$refs[button].$el.blur();
  648. if (activeClass['tool-button-disabled'])
  649. return;
  650. switch (button) {
  651. case 'loader':
  652. this.loaderToggle();
  653. break;
  654. case 'undoAction':
  655. if (this.actionCur > 0) {
  656. this.actionCur--;
  657. this.bookPosChanged({bookPos: this.actionList[this.actionCur]});
  658. }
  659. break;
  660. case 'redoAction':
  661. if (this.actionCur < this.actionList.length - 1) {
  662. this.actionCur++;
  663. this.bookPosChanged({bookPos: this.actionList[this.actionCur]});
  664. }
  665. break;
  666. case 'fullScreen':
  667. this.fullScreenToggle();
  668. break;
  669. case 'setPosition':
  670. this.setPositionToggle();
  671. break;
  672. case 'scrolling':
  673. this.scrollingToggle();
  674. break;
  675. case 'search':
  676. this.searchToggle();
  677. break;
  678. case 'copyText':
  679. this.copyTextToggle();
  680. break;
  681. case 'recentBooks':
  682. this.recentBooksToggle();
  683. break;
  684. case 'refresh':
  685. this.refreshBook();
  686. break;
  687. case 'settings':
  688. this.settingsToggle();
  689. break;
  690. }
  691. }
  692. buttonActiveClass(button) {
  693. const classActive = { 'tool-button-active': true, 'tool-button-active:hover': true };
  694. const classDisabled = { 'tool-button-disabled': true, 'tool-button-disabled:hover': true };
  695. let classResult = {};
  696. switch (button) {
  697. case 'loader':
  698. case 'fullScreen':
  699. case 'setPosition':
  700. case 'scrolling':
  701. case 'search':
  702. case 'copyText':
  703. case 'recentBooks':
  704. case 'settings':
  705. if (this[`${button}Active`])
  706. classResult = classActive;
  707. break;
  708. }
  709. switch (button) {
  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.mostRecentBook()) {
  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.mostRecentBook())
  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. 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 = 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.$refs.page ? this.$refs.page.lastBook : null);
  796. if (!opts.force && lastBook && lastBook.url == url && await bookManager.hasBookParsed(lastBook)) {
  797. this.loaderActive = false;
  798. return;
  799. }
  800. this.progressActive = true;
  801. await this.$nextTick();
  802. const progress = this.$refs.page;
  803. this.actionList = [];
  804. this.actionCur = -1;
  805. try {
  806. progress.show();
  807. progress.setState({state: 'parse'});
  808. // есть ли среди недавних
  809. const key = bookManager.keyFromUrl(url);
  810. let wasOpened = await bookManager.getRecentBook({key});
  811. wasOpened = (wasOpened ? wasOpened : {});
  812. const bookPos = (opts.bookPos !== undefined ? opts.bookPos : wasOpened.bookPos);
  813. const bookPosSeen = (opts.bookPos !== undefined ? opts.bookPos : wasOpened.bookPosSeen);
  814. let book = null;
  815. if (!opts.force) {
  816. // пытаемся загрузить и распарсить книгу в менеджере из локального кэша
  817. const bookParsed = await bookManager.getBook({url}, (prog) => {
  818. progress.setState({progress: prog});
  819. });
  820. // если есть в локальном кэше
  821. if (bookParsed) {
  822. await bookManager.setRecentBook(Object.assign({bookPos, bookPosSeen}, bookParsed));
  823. this.mostRecentBook();
  824. this.addAction(bookPos);
  825. this.loaderActive = false;
  826. progress.hide(); this.progressActive = false;
  827. this.blinkCachedLoadMessage();
  828. this.checkBookPosPercent();
  829. await this.activateClickMapPage();
  830. return;
  831. }
  832. // иначе идем на сервер
  833. // пытаемся загрузить готовый файл с сервера
  834. if (wasOpened.path) {
  835. try {
  836. const resp = await readerApi.loadCachedBook(wasOpened.path, (state) => {
  837. progress.setState(state);
  838. });
  839. book = Object.assign({}, wasOpened, {data: resp.data});
  840. } catch (e) {
  841. //молчим
  842. }
  843. }
  844. }
  845. progress.setState({totalSteps: 5});
  846. // не удалось, скачиваем книгу полностью с конвертацией
  847. let loadCached = true;
  848. if (!book) {
  849. book = await readerApi.loadBook(url, (state) => {
  850. progress.setState(state);
  851. });
  852. loadCached = false;
  853. }
  854. // добавляем в bookManager
  855. progress.setState({state: 'parse', step: 5});
  856. const addedBook = await bookManager.addBook(book, (prog) => {
  857. progress.setState({progress: prog});
  858. });
  859. // добавляем в историю
  860. await bookManager.setRecentBook(Object.assign({bookPos, bookPosSeen}, addedBook));
  861. this.mostRecentBook();
  862. this.addAction(bookPos);
  863. this.updateRoute(true);
  864. this.loaderActive = false;
  865. progress.hide(); this.progressActive = false;
  866. if (loadCached) {
  867. this.blinkCachedLoadMessage();
  868. } else
  869. this.stopBlink = true;
  870. this.checkBookPosPercent();
  871. await this.activateClickMapPage();
  872. } catch (e) {
  873. progress.hide(); this.progressActive = false;
  874. this.loaderActive = true;
  875. this.$alert(e.message, 'Ошибка', {type: 'error'});
  876. }
  877. }
  878. async loadFile(opts) {
  879. this.progressActive = true;
  880. await this.$nextTick();
  881. const progress = this.$refs.page;
  882. try {
  883. progress.show();
  884. progress.setState({state: 'upload'});
  885. const url = await readerApi.uploadFile(opts.file, this.config.maxUploadFileSize, (state) => {
  886. progress.setState(state);
  887. });
  888. progress.hide(); this.progressActive = false;
  889. await this.loadBook({url});
  890. } catch (e) {
  891. progress.hide(); this.progressActive = false;
  892. this.loaderActive = true;
  893. this.$alert(e.message, 'Ошибка', {type: 'error'});
  894. }
  895. }
  896. blinkCachedLoadMessage() {
  897. if (!this.blinkCachedLoad)
  898. return;
  899. this.blinkCount = 30;
  900. if (!this.inBlink) {
  901. this.inBlink = true;
  902. this.stopBlink = false;
  903. this.$nextTick(async() => {
  904. let page = this.$refs.page;
  905. while (this.blinkCount) {
  906. this.showRefreshIcon = !this.showRefreshIcon;
  907. if (page.blinkCachedLoadMessage)
  908. page.blinkCachedLoadMessage(this.showRefreshIcon);
  909. await utils.sleep(500);
  910. if (this.stopBlink)
  911. break;
  912. this.blinkCount--;
  913. page = this.$refs.page;
  914. }
  915. this.showRefreshIcon = true;
  916. this.inBlink = false;
  917. if (page.blinkCachedLoadMessage)
  918. page.blinkCachedLoadMessage('finish');
  919. });
  920. }
  921. }
  922. keyHook(event) {
  923. if (this.$root.rootRoute == '/reader') {
  924. let handled = false;
  925. if (!handled && this.helpActive)
  926. handled = this.$refs.helpPage.keyHook(event);
  927. if (!handled && this.settingsActive)
  928. handled = this.$refs.settingsPage.keyHook(event);
  929. if (!handled && this.recentBooksActive)
  930. handled = this.$refs.recentBooksPage.keyHook(event);
  931. if (!handled && this.setPositionActive)
  932. handled = this.$refs.setPositionPage.keyHook(event);
  933. if (!handled && this.searchActive)
  934. handled = this.$refs.searchPage.keyHook(event);
  935. if (!handled && this.copyTextActive)
  936. handled = this.$refs.copyTextPage.keyHook(event);
  937. if (!handled && this.$refs.page && this.$refs.page.keyHook)
  938. handled = this.$refs.page.keyHook(event);
  939. if (!handled && event.type == 'keydown') {
  940. if (event.code == 'Escape')
  941. this.loaderToggle();
  942. if (this.activePage == 'TextPage') {
  943. switch (event.code) {
  944. case 'KeyH':
  945. case 'F1':
  946. this.helpToggle();
  947. event.preventDefault();
  948. event.stopPropagation();
  949. break;
  950. case 'KeyZ':
  951. this.scrollingToggle();
  952. break;
  953. case 'KeyP':
  954. this.setPositionToggle();
  955. break;
  956. case 'KeyF':
  957. if (event.ctrlKey) {
  958. this.searchToggle();
  959. event.preventDefault();
  960. event.stopPropagation();
  961. }
  962. break;
  963. case 'KeyC':
  964. if (event.ctrlKey) {
  965. this.copyTextToggle();
  966. event.preventDefault();
  967. event.stopPropagation();
  968. }
  969. break;
  970. case 'KeyR':
  971. this.refreshBook();
  972. break;
  973. case 'KeyX':
  974. this.recentBooksToggle();
  975. event.preventDefault();
  976. event.stopPropagation();
  977. break;
  978. case 'KeyS':
  979. this.settingsToggle();
  980. break;
  981. }
  982. }
  983. }
  984. }
  985. }
  986. }
  987. //-----------------------------------------------------------------------------
  988. </script>
  989. <style scoped>
  990. .el-container {
  991. padding: 0;
  992. margin: 0;
  993. height: 100%;
  994. }
  995. .el-header {
  996. padding-left: 5px;
  997. padding-right: 5px;
  998. background-color: #1B695F;
  999. color: #000;
  1000. overflow-x: auto;
  1001. overflow-y: hidden;
  1002. }
  1003. .header {
  1004. display: flex;
  1005. justify-content: space-between;
  1006. }
  1007. .el-main {
  1008. position: relative;
  1009. display: flex;
  1010. padding: 0;
  1011. margin: 0;
  1012. background-color: #EBE2C9;
  1013. color: #000;
  1014. }
  1015. .tool-button {
  1016. margin: 0 2px 0 2px;
  1017. padding: 0;
  1018. color: #3E843E;
  1019. background-color: #E6EDF4;
  1020. margin-top: 5px;
  1021. height: 38px;
  1022. width: 38px;
  1023. border: 0;
  1024. box-shadow: 3px 3px 5px black;
  1025. }
  1026. .tool-button + .tool-button {
  1027. margin: 0 2px 0 2px;
  1028. }
  1029. .tool-button:hover {
  1030. background-color: white;
  1031. }
  1032. .tool-button-active {
  1033. box-shadow: 0 0 0;
  1034. color: white;
  1035. background-color: #8AB45F;
  1036. position: relative;
  1037. top: 1px;
  1038. left: 1px;
  1039. }
  1040. .tool-button-active:hover {
  1041. color: white;
  1042. background-color: #81C581;
  1043. }
  1044. .tool-button-disabled {
  1045. color: lightgray;
  1046. background-color: gray;
  1047. }
  1048. .tool-button-disabled:hover {
  1049. color: lightgray;
  1050. background-color: gray;
  1051. }
  1052. i {
  1053. font-size: 200%;
  1054. }
  1055. .space {
  1056. width: 10px;
  1057. display: inline-block;
  1058. }
  1059. .clear {
  1060. color: rgba(0,0,0,0);
  1061. }
  1062. .clickable {
  1063. color: blue;
  1064. text-decoration: underline;
  1065. cursor: pointer;
  1066. }
  1067. </style>