ExternalLibs.vue 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857
  1. <template>
  2. <Window ref="window" @close="close" margin="2px">
  3. <template slot="header">
  4. {{ header }}
  5. </template>
  6. <template slot="buttons">
  7. <span class="full-screen-button row justify-center items-center" @mousedown.stop @click="fullScreenToggle">
  8. <q-icon :name="(fullScreenActive ? 'la la-compress-arrows-alt': 'la la-expand-arrows-alt')" size="16px"/>
  9. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">На весь экран</q-tooltip>
  10. </span>
  11. <span class="full-screen-button row justify-center items-center" @mousedown.stop @click="changeScale(0.1)">
  12. <q-icon name="la la-plus" size="16px"/>
  13. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">Увеличить масштаб</q-tooltip>
  14. </span>
  15. <span class="full-screen-button row justify-center items-center" @mousedown.stop @click="changeScale(-0.1)">
  16. <q-icon name="la la-minus" size="16px"/>
  17. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">Уменьшить масштаб</q-tooltip>
  18. </span>
  19. <span class="full-screen-button row justify-center items-center" @mousedown.stop @click="showHelp">
  20. <q-icon name="la la-question-circle" size="16px"/>
  21. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">Справка</q-tooltip>
  22. </span>
  23. </template>
  24. <div v-show="ready" class="col column" style="min-width: 600px">
  25. <div class="row items-center q-px-sm" style="height: 50px">
  26. <q-select class="q-mr-sm" ref="rootLink" v-model="rootLink" :options="rootLinkOptions" @input="rootLinkInput"
  27. @popup-show="onSelectPopupShow" @popup-hide="onSelectPopupHide"
  28. style="width: 230px"
  29. dropdown-icon="la la-angle-down la-sm"
  30. rounded outlined dense emit-value map-options display-value-sanitize options-sanitize
  31. >
  32. <template v-slot:prepend>
  33. <q-btn class="q-mr-xs" round dense color="blue" icon="la la-plus" @click.stop="addBookmark" size="12px">
  34. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">Добавить закладку</q-tooltip>
  35. </q-btn>
  36. <q-btn round dense color="blue" icon="la la-bars" @click.stop="bookmarkSettings" size="12px">
  37. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">Настроить закладки</q-tooltip>
  38. </q-btn>
  39. </template>
  40. <template v-slot:selected>
  41. <div style="overflow: hidden; white-space: nowrap;">{{ rootLinkWithoutProtocol }}</div>
  42. </template>
  43. </q-select>
  44. <q-select class="q-mr-sm" ref="selectedLink" v-model="selectedLink" :options="selectedLinkOptions" @input="selectedLinkInput" style="width: 50px"
  45. @popup-show="onSelectPopupShow" @popup-hide="onSelectPopupHide"
  46. dropdown-icon="la la-angle-down la-sm"
  47. rounded outlined dense emit-value map-options hide-selected display-value-sanitize options-sanitize
  48. >
  49. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">Закладки</q-tooltip>
  50. </q-select>
  51. <q-input class="col q-mr-sm" ref="input" rounded outlined dense bg-color="white" v-model="bookUrl" placeholder="Скопируйте сюда URL книги"
  52. @focus="selectAllOnFocus" @keydown="bookUrlKeyDown"
  53. >
  54. <template v-slot:prepend>
  55. <q-btn class="q-mr-xs" round dense color="blue" icon="la la-home" @click="goToLink(selectedLink)" size="12px">
  56. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">Вернуться на стартовую страницу</q-tooltip>
  57. </q-btn>
  58. <q-btn round dense color="blue" icon="la la-angle-double-down" @click="openBookUrlInFrame" size="12px" :disabled="!bookUrl">
  59. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">Загрузить URL во фрейм</q-tooltip>
  60. </q-btn>
  61. </template>
  62. <template v-slot:append>
  63. <q-btn round dense color="blue" icon="la la-cog" @click.stop="optionsVisible = true" size="12px">
  64. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">Опции</q-tooltip>
  65. </q-btn>
  66. </template>
  67. </q-input>
  68. <q-btn rounded color="green-7" no-caps size="14px" @click="submitUrl" :disabled="!bookUrl">Открыть
  69. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">Открыть в читалке</q-tooltip>
  70. </q-btn>
  71. </div>
  72. <div class="separator"></div>
  73. <div class="col fit" ref="frameBox" style="position: relative;">
  74. <div ref="frameWrap" class="overflow-hidden">
  75. <iframe v-if="frameVisible" ref="frame" :src="frameSrc" frameborder="0"></iframe>
  76. </div>
  77. <div v-show="transparentLayoutVisible" ref="transparentLayout" class="fit transparent-layout" @click="transparentLayoutClick"></div>
  78. </div>
  79. <Dialog ref="dialogAddBookmark" v-model="addBookmarkVisible">
  80. <template slot="header">
  81. <div class="row items-center">
  82. <q-icon class="q-mr-sm" name="la la-bookmark" size="28px"></q-icon>
  83. <div v-if="addBookmarkMode == 'edit'">Редактировать закладку</div>
  84. <div v-else>Добавить закладку</div>
  85. </div>
  86. </template>
  87. <div class="q-mx-md row">
  88. <q-input ref="bookmarkLink" class="col q-mr-sm" outlined dense bg-color="white" v-model="bookmarkLink" @keydown="bookmarkLinkKeyDown"
  89. placeholder="Ссылка для закладки" maxlength="2000" @focus="selectAllOnFocus">
  90. </q-input>
  91. <q-select class="q-mr-sm" ref="defaultRootLink" v-model="defaultRootLink" :options="defaultRootLinkOptions" @input="defaultRootLinkInput" style="width: 50px"
  92. dropdown-icon="la la-angle-down la-sm"
  93. outlined dense emit-value map-options hide-selected display-value-sanitize options-sanitize
  94. >
  95. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%">Предустановленные ссылки</q-tooltip>
  96. </q-select>
  97. </div>
  98. <div class="q-mx-md q-mt-md">
  99. <q-input class="col q-mr-sm" ref="bookmarkDesc" outlined dense bg-color="white" v-model="bookmarkDesc" @keydown="bookmarkDescKeyDown"
  100. placeholder="Описание" style="width: 400px" maxlength="100" @focus="selectAllOnFocus">
  101. </q-input>
  102. </div>
  103. <template slot="footer">
  104. <q-btn class="q-px-md q-ml-sm" dense no-caps v-close-popup>Отмена</q-btn>
  105. <q-btn class="q-px-md q-ml-sm" color="primary" dense no-caps @click="okAddBookmark" :disabled="!bookmarkLink">OK</q-btn>
  106. </template>
  107. </Dialog>
  108. <Dialog ref="options" v-model="optionsVisible">
  109. <template slot="header">
  110. <div class="row items-center">
  111. <q-icon class="q-mr-sm" name="la la-cog" size="28px"></q-icon>
  112. Опции
  113. </div>
  114. </template>
  115. <div class="q-mx-md column">
  116. <q-checkbox v-model="closeAfterSubmit" size="36px" label="Закрыть окно при отправке ссылки в читалку" />
  117. <q-checkbox v-model="openInFrameOnEnter" size="36px" label="Открывать ссылку во фрейме при нажатии 'Enter'" />
  118. <q-checkbox v-model="openInFrameOnAdd" size="36px" label="Активировать новую закладку после добавления" />
  119. </div>
  120. <template slot="footer">
  121. <q-btn class="q-px-md q-ml-sm" color="primary" dense no-caps @click="optionsVisible = false">OK</q-btn>
  122. </template>
  123. </Dialog>
  124. </div>
  125. <BookmarkSettings v-if="bookmarkSettingsActive" ref="bookmarkSettings" :libs="libs" :addBookmarkVisible="addBookmarkVisible"
  126. @do-action="doAction" @close="closeBookmarkSettings">
  127. </BookmarkSettings>
  128. </Window>
  129. </template>
  130. <script>
  131. //-----------------------------------------------------------------------------
  132. import Vue from 'vue';
  133. import Component from 'vue-class-component';
  134. import _ from 'lodash';
  135. import Window from '../share/Window.vue';
  136. import Dialog from '../share/Dialog.vue';
  137. import BookmarkSettings from './BookmarkSettings/BookmarkSettings.vue';
  138. import rstore from '../../store/modules/reader';
  139. import * as utils from '../../share/utils';
  140. import * as lu from './linkUtils';
  141. const proxySubst = {
  142. 'http://flibusta.is': 'http://b.liberama.top:23480',
  143. };
  144. export default @Component({
  145. components: {
  146. Window,
  147. Dialog,
  148. BookmarkSettings
  149. },
  150. watch: {
  151. libs: function() {
  152. this.loadLibs();
  153. },
  154. defaultRootLink: function() {
  155. this.updateBookmarkLink();
  156. },
  157. bookUrl: function(newValue) {
  158. const value = lu.addProtocol(newValue);
  159. const subst = this.makeProxySubst(value, true);
  160. if (value != subst) {
  161. this.$nextTick(() => {
  162. this.bookUrl = subst;
  163. });
  164. }
  165. },
  166. bookmarkLink: function(newValue) {
  167. const value = lu.addProtocol(newValue);
  168. const subst = this.makeProxySubst(value, true);
  169. if (value != subst) {
  170. this.$nextTick(() => {
  171. this.bookmarkLink = subst;
  172. });
  173. }
  174. },
  175. closeAfterSubmit: function(newValue) {
  176. this.commitProp('closeAfterSubmit', newValue);
  177. },
  178. openInFrameOnEnter: function(newValue) {
  179. this.commitProp('openInFrameOnEnter', newValue);
  180. },
  181. openInFrameOnAdd: function(newValue) {
  182. this.commitProp('openInFrameOnAdd', newValue);
  183. },
  184. }
  185. })
  186. class ExternalLibs extends Vue {
  187. ready = false;
  188. frameVisible = false;
  189. rootLink = '';
  190. selectedLink = '';
  191. frameSrc = '';
  192. bookUrl = '';
  193. libs = {};
  194. fullScreenActive = false;
  195. transparentLayoutVisible = false;
  196. addBookmarkVisible = false;
  197. optionsVisible = false;
  198. addBookmarkMode = '';
  199. bookmarkLink = '';
  200. bookmarkDesc = '';
  201. defaultRootLink = '';
  202. bookmarkSettingsActive = false;
  203. closeAfterSubmit = false;
  204. openInFrameOnEnter = false;
  205. openInFrameOnAdd = false;
  206. frameScale = 1;
  207. created() {
  208. this.oldStartLink = '';
  209. this.justOpened = true;
  210. this.$root.addKeyHook(this.keyHook);
  211. this.$root.$on('resize', async() => {
  212. await utils.sleep(200);
  213. this.frameResize();
  214. });
  215. document.addEventListener('fullscreenchange', () => {
  216. this.fullScreenActive = (document.fullscreenElement !== null);
  217. });
  218. this.debouncedGoToLink = _.debounce((link) => {
  219. this.goToLink(link);
  220. }, 100, {'maxWait':200});
  221. //this.commit = this.$store.commit;
  222. //this.commit('reader/setLibs', rstore.libsDefaults);
  223. }
  224. mounted() {
  225. //Поправка метода toggleOption компонента select фреймворка quasar, необходимо другое поведение
  226. //$emit('input'.. вызывается всегда
  227. this.toggleOption = function(opt, keepOpen) {
  228. if (this.editable !== true || opt === void 0 || this.isOptionDisabled(opt) === true) {
  229. return;
  230. }
  231. const optValue = this.getOptionValue(opt);
  232. if (this.multiple !== true) {
  233. if (keepOpen !== true) {
  234. this.updateInputValue(this.fillInput === true ? this.getOptionLabel(opt) : '', true, true);
  235. this.hidePopup();
  236. }
  237. this.$refs.target !== void 0 && this.$refs.target.focus();
  238. this.$emit('input', this.emitValue === true ? optValue : opt);
  239. }
  240. };
  241. this.$refs.rootLink.toggleOption = this.toggleOption;
  242. this.$refs.selectedLink.toggleOption = this.toggleOption;
  243. (async() => {
  244. //подождем this.mode
  245. let i = 0;
  246. while(!this.mode && i < 100) {
  247. await utils.sleep(100);
  248. i++;
  249. }
  250. if (this.mode != 'liberama.top') {
  251. this.$router.replace('/404');
  252. return;
  253. }
  254. this.$refs.window.init();
  255. this.opener = null;
  256. const host = window.location.host;
  257. const openerHost = (host.indexOf('b.') == 0 ? host.substring(2) : host);
  258. const openerOrigin1 = `http://${openerHost}`;
  259. const openerOrigin2 = `https://${openerHost}`;
  260. window.addEventListener('message', (event) => {
  261. if (event.origin !== openerOrigin1 && event.origin !== openerOrigin2)
  262. return;
  263. if (!_.isObject(event.data) || event.data.from != 'LibsPage')
  264. return;
  265. if (event.origin == openerOrigin1)
  266. this.opener = window.opener;
  267. else
  268. this.opener = event.source;
  269. this.openerOrigin = event.origin;
  270. //console.log(event);
  271. this.recvMessage(event.data);
  272. });
  273. //Ожидаем родителя
  274. i = 0;
  275. while(!this.opener) {
  276. await utils.sleep(1000);
  277. i++;
  278. if (i >= 5) {
  279. await this.$root.stdDialog.alert('Нет связи с читалкой. Окно будет закрыто', 'Ошибка');
  280. window.close();
  281. }
  282. }
  283. //Проверка закрытия родительского окна
  284. while(this.opener) {
  285. await this.checkOpener();
  286. await utils.sleep(1000);
  287. }
  288. })();
  289. }
  290. recvMessage(d) {
  291. if (d.type == 'mes') {
  292. switch(d.data) {
  293. case 'hello': this.sendMessage({type: 'mes', data: 'ready'}); break;
  294. }
  295. } else if (d.type == 'libs') {
  296. this.ready = true;
  297. this.libs = _.cloneDeep(d.data);
  298. } else if (d.type == 'notify') {
  299. this.$root.notify.success(d.data, '', {position: 'bottom-right'});
  300. }
  301. }
  302. sendMessage(d) {
  303. (async() => {
  304. await this.checkOpener();
  305. if (this.opener && this.openerOrigin)
  306. this.opener.postMessage(Object.assign({}, {from: 'ExternalLibs'}, d), this.openerOrigin);
  307. })();
  308. }
  309. async checkOpener() {
  310. if (this.opener.closed) {
  311. await this.$root.stdDialog.alert('Потеряна связь с читалкой. Окно будет закрыто', 'Ошибка');
  312. window.close();
  313. }
  314. }
  315. commitLibs(libs) {
  316. this.sendMessage({type: 'libs', data: libs});
  317. }
  318. commitProp(prop, value) {
  319. let libs = _.cloneDeep(this.libs);
  320. libs[prop] = value;
  321. this.commitLibs(libs);
  322. }
  323. loadLibs() {
  324. const libs = this.libs;
  325. if (!libs.helpShowed) {
  326. this.showHelp();
  327. (async() => {
  328. await utils.sleep(1000);
  329. this.commitProp('helpShowed', true);
  330. })();
  331. }
  332. this.selectedLink = libs.startLink;
  333. this.closeAfterSubmit = libs.closeAfterSubmit || false;
  334. this.openInFrameOnEnter = libs.openInFrameOnEnter || false;
  335. this.openInFrameOnAdd = libs.openInFrameOnAdd || false;
  336. this.frameScale = 1;
  337. const index = lu.getSafeRootIndexByUrl(this.libs.groups, this.selectedLink);
  338. if (index >= 0)
  339. this.frameScale = this.libs.groups[index].frameScale || 1;
  340. this.updateStartLink();
  341. }
  342. doAction(event) {
  343. switch (event.action) {
  344. case 'setLibs': this.commitLibs(event.data); break;
  345. case 'setRootLink': this.rootLink = event.data; this.rootLinkInput(); break;
  346. case 'setSelectedLink': this.selectedLink = event.data; this.selectedLinkInput(); break;
  347. case 'editBookmark': this.addBookmark('edit', event.data.link, event.data.desc); break;
  348. case 'addBookmark': this.addBookmark('add'); break;
  349. }
  350. }
  351. get mode() {
  352. return this.$store.state.config.mode;
  353. }
  354. get header() {
  355. let result = (this.ready ? 'Библиотека' : 'Загрузка...');
  356. if (this.ready && this.selectedLink) {
  357. result += ` | ${(this.libs.comment ? this.libs.comment + ' ': '') + lu.removeProtocol(this.libs.startLink)}`;
  358. }
  359. this.$root.$emit('set-app-title', result);
  360. return result;
  361. }
  362. get rootLinkWithoutProtocol() {
  363. return lu.removeProtocol(this.rootLink);
  364. }
  365. updateSelectedLinkByRoot() {
  366. if (!this.ready)
  367. return;
  368. const index = lu.getSafeRootIndexByUrl(this.libs.groups, this.rootLink);
  369. if (index >= 0)
  370. this.selectedLink = this.libs.groups[index].s;
  371. else
  372. this.selectedLink = '';
  373. }
  374. updateStartLink(force) {
  375. if (!this.ready)
  376. return;
  377. let index = -1;
  378. try {
  379. this.rootLink = lu.getOrigin(this.selectedLink);
  380. index = lu.getRootIndexByUrl(this.libs.groups, this.rootLink);
  381. } catch(e) {
  382. //
  383. }
  384. if (index >= 0) {
  385. let libs = _.cloneDeep(this.libs);
  386. const com = this.getCommentByLink(libs.groups[index].list, this.selectedLink);
  387. if (libs.groups[index].s != this.selectedLink ||
  388. libs.startLink != this.selectedLink ||
  389. libs.comment != com) {
  390. libs.groups[index].s = this.selectedLink;
  391. libs.startLink = this.selectedLink;
  392. libs.comment = com;
  393. this.commitLibs(libs);
  394. }
  395. if (force || this.oldStartLink != libs.startLink) {
  396. this.oldStartLink = libs.startLink;
  397. this.debouncedGoToLink(this.selectedLink);
  398. }
  399. } else {
  400. this.rootLink = '';
  401. this.selectedLink = '';
  402. this.debouncedGoToLink(this.selectedLink);
  403. }
  404. }
  405. get rootLinkOptions() {
  406. let result = [];
  407. if (!this.ready)
  408. return result;
  409. this.libs.groups.forEach(group => {
  410. result.push({label: lu.removeProtocol(group.r), value: group.r});
  411. });
  412. return result;
  413. }
  414. get defaultRootLinkOptions() {
  415. let result = [];
  416. rstore.libsDefaults.groups.forEach(group => {
  417. result.push({label: lu.removeProtocol(group.r), value: group.r});
  418. });
  419. return result;
  420. }
  421. get selectedLinkOptions() {
  422. let result = [];
  423. if (!this.ready)
  424. return result;
  425. const index = lu.getSafeRootIndexByUrl(this.libs.groups, this.rootLink);
  426. if (index >= 0) {
  427. this.libs.groups[index].list.forEach(link => {
  428. result.push({label: (link.c ? link.c + ' ': '') + lu.removeOrigin(link.l), value: link.l});
  429. });
  430. }
  431. return result;
  432. }
  433. openBookUrlInFrame() {
  434. if (this.bookUrl) {
  435. this.goToLink(lu.addProtocol(this.bookUrl));
  436. }
  437. }
  438. goToLink(link) {
  439. if (!this.ready || !link)
  440. return;
  441. if (!link) {
  442. this.frameVisible = false;
  443. return;
  444. }
  445. this.frameSrc = this.makeProxySubst(link);
  446. this.frameVisible = false;
  447. this.$nextTick(() => {
  448. this.frameVisible = true;
  449. this.$nextTick(() => {
  450. if (this.$refs.frame) {
  451. this.$refs.frame.contentWindow.focus();
  452. this.frameResize();
  453. }
  454. });
  455. });
  456. }
  457. frameResize() {
  458. this.$refs.frameWrap.style = 'width: 1px; height: 1px;';
  459. this.$nextTick(() => {
  460. if (this.$refs.frame) {
  461. const w = this.$refs.frameBox.offsetWidth;
  462. const h = this.$refs.frameBox.offsetHeight;
  463. const normalSize = `width: ${w}px; height: ${h}px;`;
  464. this.$refs.frameWrap.style = normalSize;
  465. if (this.frameScale != 1) {
  466. const s = this.frameScale;
  467. this.$refs.frame.style = `width: ${w/s}px; height: ${h/s}px; transform: scale(${s}); transform-origin: 0 0;`;
  468. } else {
  469. this.$refs.frame.style = normalSize;
  470. }
  471. }
  472. });
  473. }
  474. changeScale(delta) {
  475. if ((this.frameScale > 0.1 && delta <= 0) || (this.frameScale < 5 && delta >= 0)) {
  476. this.frameScale = _.round(this.frameScale + delta, 1);
  477. const index = lu.getSafeRootIndexByUrl(this.libs.groups, this.selectedLink);
  478. if (index >= 0) {
  479. let libs = _.cloneDeep(this.libs);
  480. libs.groups[index].frameScale = this.frameScale;
  481. this.commitLibs(libs);
  482. }
  483. this.frameResize();
  484. this.$root.notify.success(`Масштаб изменен: ${(this.frameScale*100).toFixed(0)}%`, '', {position: 'bottom-right'});
  485. }
  486. }
  487. getCommentByLink(list, link) {
  488. const item = lu.getListItemByLink(list, link);
  489. return (item ? item.c : '');
  490. }
  491. makeProxySubst(url, reverse = false) {
  492. for (const [key, value] of Object.entries(proxySubst)) {
  493. if (reverse && value == url.substring(0, value.length)) {
  494. return key + url.substring(value.length);
  495. } else if (!reverse && key == url.substring(0, key.length)) {
  496. return value + url.substring(key.length);
  497. }
  498. }
  499. return url;
  500. }
  501. selectAllOnFocus(event) {
  502. if (event.target.select)
  503. event.target.select();
  504. }
  505. rootLinkInput() {
  506. this.updateSelectedLinkByRoot();
  507. this.updateStartLink(true);
  508. }
  509. selectedLinkInput() {
  510. this.updateStartLink(true);
  511. }
  512. submitUrl() {
  513. if (this.bookUrl) {
  514. this.sendMessage({type: 'submitUrl', data: {
  515. url: this.bookUrl,
  516. force: true
  517. }});
  518. this.bookUrl = '';
  519. if (this.closeAfterSubmit)
  520. this.close();
  521. }
  522. }
  523. addBookmark(mode = 'add', link = '', desc = '') {
  524. if (mode == 'edit') {
  525. this.editBookmarkLink = this.bookmarkLink = link;
  526. this.editBookmarkDesc = this.bookmarkDesc = desc;
  527. } else {
  528. this.bookmarkLink = this.bookUrl;
  529. this.bookmarkDesc = '';
  530. }
  531. this.addBookmarkMode = mode;
  532. this.addBookmarkVisible = true;
  533. this.$nextTick(() => {
  534. this.$refs.bookmarkLink.focus();
  535. this.$refs.defaultRootLink.toggleOption = this.toggleOption;
  536. });
  537. }
  538. updateBookmarkLink() {
  539. const index = lu.getSafeRootIndexByUrl(rstore.libsDefaults.groups, this.defaultRootLink);
  540. if (index >= 0) {
  541. this.bookmarkLink = rstore.libsDefaults.groups[index].s;
  542. this.bookmarkDesc = this.getCommentByLink(rstore.libsDefaults.groups[index].list, this.bookmarkLink);
  543. } else {
  544. this.bookmarkLink = '';
  545. this.bookmarkDesc = '';
  546. }
  547. }
  548. defaultRootLinkInput() {
  549. this.updateBookmarkLink();
  550. }
  551. bookmarkLinkKeyDown(event) {
  552. if (event.key == 'Enter') {
  553. this.$refs.bookmarkDesc.focus();
  554. event.preventDefault();
  555. }
  556. }
  557. bookmarkDescKeyDown(event) {
  558. if (event.key == 'Enter') {
  559. event.stopPropagation();
  560. event.preventDefault();
  561. this.okAddBookmark();
  562. }
  563. }
  564. async okAddBookmark() {
  565. if (!this.bookmarkLink)
  566. return;
  567. const link = (this.addBookmarkMode == 'edit' ? lu.addProtocol(this.editBookmarkLink) : lu.addProtocol(this.bookmarkLink));
  568. let index = -1;
  569. try {
  570. index = lu.getRootIndexByUrl(this.libs.groups, link);
  571. } catch (e) {
  572. await this.$root.stdDialog.alert('Неверный формат ссылки', 'Ошибка');
  573. return;
  574. }
  575. let libs = _.cloneDeep(this.libs);
  576. //добавление
  577. //есть группа в закладках
  578. if (index >= 0) {
  579. const item = lu.getListItemByLink(libs.groups[index].list, link);
  580. //редактирование
  581. if (item && this.addBookmarkMode == 'edit') {
  582. if (item) {
  583. //редактируем
  584. item.l = link;
  585. item.c = this.bookmarkDesc;
  586. this.commitLibs(libs);
  587. } else {
  588. await this.$root.stdDialog.alert('Не удалось отредактировать закладку', 'Ошибка');
  589. }
  590. } else if (!item) {
  591. //добавляем
  592. if (libs.groups[index].list.length >= 100) {
  593. await this.$root.stdDialog.alert('Достигнут предел количества закладок для этого сайта', 'Ошибка');
  594. return;
  595. }
  596. libs.groups[index].list.push({l: link, c: this.bookmarkDesc});
  597. if (this.openInFrameOnAdd) {
  598. libs.startLink = link;
  599. libs.comment = this.bookmarkDesc;
  600. }
  601. this.commitLibs(libs);
  602. } else if (item.c != this.bookmarkDesc) {
  603. if (await this.$root.stdDialog.confirm(`Такая закладка уже существует с другим описанием.<br>` +
  604. `Заменить '${this.$sanitize(item.c)}' на '${this.$sanitize(this.bookmarkDesc)}'?`, ' ')) {
  605. item.c = this.bookmarkDesc;
  606. this.commitLibs(libs);
  607. } else
  608. return;
  609. } else {
  610. await this.$root.stdDialog.alert('Такая закладка уже существует', ' ');
  611. return;
  612. }
  613. } else {//нет группы в закладках
  614. if (libs.groups.length >= 100) {
  615. await this.$root.stdDialog.alert('Достигнут предел количества различных сайтов в закладках', 'Ошибка');
  616. return;
  617. }
  618. //добавляем сначала группу
  619. libs.groups.push({r: lu.getOrigin(link), s: link, list: []});
  620. index = lu.getSafeRootIndexByUrl(libs.groups, link);
  621. if (index >= 0)
  622. libs.groups[index].list.push({l: link, c: this.bookmarkDesc});
  623. if (this.openInFrameOnAdd) {
  624. libs.startLink = link;
  625. libs.comment = this.bookmarkDesc;
  626. }
  627. this.commitLibs(libs);
  628. }
  629. this.addBookmarkVisible = false;
  630. }
  631. fullScreenToggle() {
  632. this.fullScreenActive = !this.fullScreenActive;
  633. if (this.fullScreenActive) {
  634. this.$q.fullscreen.request();
  635. } else {
  636. this.$q.fullscreen.exit();
  637. }
  638. }
  639. transparentLayoutClick() {
  640. this.transparentLayoutVisible = false;
  641. }
  642. onSelectPopupShow() {
  643. this.transparentLayoutVisible = true;
  644. }
  645. onSelectPopupHide() {
  646. this.transparentLayoutVisible = false;
  647. }
  648. close() {
  649. this.sendMessage({type: 'close'});
  650. }
  651. bookUrlKeyDown(event) {
  652. if (event.key == 'Enter') {
  653. if (!this.openInFrameOnEnter) {
  654. this.submitUrl();
  655. } else {
  656. if (this.bookUrl)
  657. this.goToLink(this.bookUrl);
  658. }
  659. event.preventDefault();
  660. }
  661. }
  662. bookmarkSettings() {
  663. this.bookmarkSettingsActive = true;
  664. this.$nextTick(() => {
  665. this.$refs.bookmarkSettings.init();
  666. });
  667. }
  668. closeBookmarkSettings() {
  669. this.bookmarkSettingsActive = false;
  670. }
  671. showHelp() {
  672. this.$root.stdDialog.alert(`
  673. <p>Окно 'Библиотека' позволяет открывать ссылки в читалке без переключения между окнами,
  674. что особенно актуально для мобильных устройств.</p>
  675. <p>'Библиотека' разрешает свободный доступ к сайту flibusta.is. Имеется возможность управлять закладками
  676. на понравившиеся ресурсы, книги или страницы авторов. Открытие ссылок и навигация происходят во фрейме, но,
  677. к сожалению, в нем открываются не все страницы.
  678. </p>
  679. <p>Из-за проблем с безопасностью, навигация 'вперед-назад' во фрейме осуществляется с помощью контекстного меню правой кнопкой мыши.
  680. На мобильных устройствах для этого служит системная клавиша 'Назад (стрелка влево)' и опция 'Вперед (стрелка вправо)' в меню браузера.
  681. </p>
  682. <p>Приятного пользования ;-)
  683. </p>
  684. `, 'Справка', {iconName: 'la la-info-circle'});
  685. }
  686. keyHook(event) {
  687. if (this.$root.rootRoute() == '/external-libs') {
  688. if (this.$root.stdDialog.active)
  689. return false;
  690. if (this.bookmarkSettingsActive && this.$refs.bookmarkSettings.keyHook(event))
  691. return true;
  692. if (this.addBookmarkVisible || this.optionsVisible)
  693. return false;
  694. if (event.type == 'keydown' && event.key == 'F4') {
  695. this.addBookmark();
  696. return true;
  697. }
  698. if (event.type == 'keydown' && event.key == 'Escape' &&
  699. (document.activeElement != this.$refs.rootLink.$refs.target || !this.$refs.rootLink.menu) &&
  700. (document.activeElement != this.$refs.selectedLink.$refs.target || !this.$refs.selectedLink.menu)
  701. ) {
  702. this.close();
  703. return true;
  704. }
  705. }
  706. return false;
  707. }
  708. }
  709. //-----------------------------------------------------------------------------
  710. </script>
  711. <style scoped>
  712. .separator {
  713. height: 1px;
  714. background-color: #A0A0A0;
  715. }
  716. .full-screen-button {
  717. width: 30px;
  718. height: 30px;
  719. cursor: pointer;
  720. }
  721. .full-screen-button:hover {
  722. background-color: #69C05F;
  723. }
  724. .transparent-layout {
  725. top: 0;
  726. left: 0;
  727. position: absolute;
  728. }
  729. </style>