ExternalLibs.vue 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858
  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. 'http://fantasy-worlds.org': 'http://b.liberama.top:23580',
  144. };
  145. export default @Component({
  146. components: {
  147. Window,
  148. Dialog,
  149. BookmarkSettings
  150. },
  151. watch: {
  152. libs: function() {
  153. this.loadLibs();
  154. },
  155. defaultRootLink: function() {
  156. this.updateBookmarkLink();
  157. },
  158. bookUrl: function(newValue) {
  159. const value = lu.addProtocol(newValue);
  160. const subst = this.makeProxySubst(value, true);
  161. if (value != subst) {
  162. this.$nextTick(() => {
  163. this.bookUrl = subst;
  164. });
  165. }
  166. },
  167. bookmarkLink: function(newValue) {
  168. const value = lu.addProtocol(newValue);
  169. const subst = this.makeProxySubst(value, true);
  170. if (value != subst) {
  171. this.$nextTick(() => {
  172. this.bookmarkLink = subst;
  173. });
  174. }
  175. },
  176. closeAfterSubmit: function(newValue) {
  177. this.commitProp('closeAfterSubmit', newValue);
  178. },
  179. openInFrameOnEnter: function(newValue) {
  180. this.commitProp('openInFrameOnEnter', newValue);
  181. },
  182. openInFrameOnAdd: function(newValue) {
  183. this.commitProp('openInFrameOnAdd', newValue);
  184. },
  185. }
  186. })
  187. class ExternalLibs extends Vue {
  188. ready = false;
  189. frameVisible = false;
  190. rootLink = '';
  191. selectedLink = '';
  192. frameSrc = '';
  193. bookUrl = '';
  194. libs = {};
  195. fullScreenActive = false;
  196. transparentLayoutVisible = false;
  197. addBookmarkVisible = false;
  198. optionsVisible = false;
  199. addBookmarkMode = '';
  200. bookmarkLink = '';
  201. bookmarkDesc = '';
  202. defaultRootLink = '';
  203. bookmarkSettingsActive = false;
  204. closeAfterSubmit = false;
  205. openInFrameOnEnter = false;
  206. openInFrameOnAdd = false;
  207. frameScale = 1;
  208. created() {
  209. this.oldStartLink = '';
  210. this.justOpened = true;
  211. this.$root.addKeyHook(this.keyHook);
  212. this.$root.$on('resize', async() => {
  213. await utils.sleep(200);
  214. this.frameResize();
  215. });
  216. document.addEventListener('fullscreenchange', () => {
  217. this.fullScreenActive = (document.fullscreenElement !== null);
  218. });
  219. this.debouncedGoToLink = _.debounce((link) => {
  220. this.goToLink(link);
  221. }, 100, {'maxWait':200});
  222. //this.commit = this.$store.commit;
  223. //this.commit('reader/setLibs', rstore.libsDefaults);
  224. }
  225. mounted() {
  226. //Поправка метода toggleOption компонента select фреймворка quasar, необходимо другое поведение
  227. //$emit('input'.. вызывается всегда
  228. this.toggleOption = function(opt, keepOpen) {
  229. if (this.editable !== true || opt === void 0 || this.isOptionDisabled(opt) === true) {
  230. return;
  231. }
  232. const optValue = this.getOptionValue(opt);
  233. if (this.multiple !== true) {
  234. if (keepOpen !== true) {
  235. this.updateInputValue(this.fillInput === true ? this.getOptionLabel(opt) : '', true, true);
  236. this.hidePopup();
  237. }
  238. this.$refs.target !== void 0 && this.$refs.target.focus();
  239. this.$emit('input', this.emitValue === true ? optValue : opt);
  240. }
  241. };
  242. this.$refs.rootLink.toggleOption = this.toggleOption;
  243. this.$refs.selectedLink.toggleOption = this.toggleOption;
  244. (async() => {
  245. //подождем this.mode
  246. let i = 0;
  247. while(!this.mode && i < 100) {
  248. await utils.sleep(100);
  249. i++;
  250. }
  251. if (this.mode != 'liberama.top') {
  252. this.$router.replace('/404');
  253. return;
  254. }
  255. this.$refs.window.init();
  256. this.opener = null;
  257. const host = window.location.host;
  258. const openerHost = (host.indexOf('b.') == 0 ? host.substring(2) : host);
  259. const openerOrigin1 = `http://${openerHost}`;
  260. const openerOrigin2 = `https://${openerHost}`;
  261. window.addEventListener('message', (event) => {
  262. if (event.origin !== openerOrigin1 && event.origin !== openerOrigin2)
  263. return;
  264. if (!_.isObject(event.data) || event.data.from != 'LibsPage')
  265. return;
  266. if (event.origin == openerOrigin1)
  267. this.opener = window.opener;
  268. else
  269. this.opener = event.source;
  270. this.openerOrigin = event.origin;
  271. //console.log(event);
  272. this.recvMessage(event.data);
  273. });
  274. //Ожидаем родителя
  275. i = 0;
  276. while(!this.opener) {
  277. await utils.sleep(1000);
  278. i++;
  279. if (i >= 5) {
  280. await this.$root.stdDialog.alert('Нет связи с читалкой. Окно будет закрыто', 'Ошибка');
  281. window.close();
  282. }
  283. }
  284. //Проверка закрытия родительского окна
  285. while(this.opener) {
  286. await this.checkOpener();
  287. await utils.sleep(1000);
  288. }
  289. })();
  290. }
  291. recvMessage(d) {
  292. if (d.type == 'mes') {
  293. switch(d.data) {
  294. case 'hello': this.sendMessage({type: 'mes', data: 'ready'}); break;
  295. }
  296. } else if (d.type == 'libs') {
  297. this.ready = true;
  298. this.libs = _.cloneDeep(d.data);
  299. } else if (d.type == 'notify') {
  300. this.$root.notify.success(d.data, '', {position: 'bottom-right'});
  301. }
  302. }
  303. sendMessage(d) {
  304. (async() => {
  305. await this.checkOpener();
  306. if (this.opener && this.openerOrigin)
  307. this.opener.postMessage(Object.assign({}, {from: 'ExternalLibs'}, d), this.openerOrigin);
  308. })();
  309. }
  310. async checkOpener() {
  311. if (this.opener.closed) {
  312. await this.$root.stdDialog.alert('Потеряна связь с читалкой. Окно будет закрыто', 'Ошибка');
  313. window.close();
  314. }
  315. }
  316. commitLibs(libs) {
  317. this.sendMessage({type: 'libs', data: libs});
  318. }
  319. commitProp(prop, value) {
  320. let libs = _.cloneDeep(this.libs);
  321. libs[prop] = value;
  322. this.commitLibs(libs);
  323. }
  324. loadLibs() {
  325. const libs = this.libs;
  326. if (!libs.helpShowed) {
  327. this.showHelp();
  328. (async() => {
  329. await utils.sleep(1000);
  330. this.commitProp('helpShowed', true);
  331. })();
  332. }
  333. this.selectedLink = libs.startLink;
  334. this.closeAfterSubmit = libs.closeAfterSubmit || false;
  335. this.openInFrameOnEnter = libs.openInFrameOnEnter || false;
  336. this.openInFrameOnAdd = libs.openInFrameOnAdd || false;
  337. this.frameScale = 1;
  338. const index = lu.getSafeRootIndexByUrl(this.libs.groups, this.selectedLink);
  339. if (index >= 0)
  340. this.frameScale = this.libs.groups[index].frameScale || 1;
  341. this.updateStartLink();
  342. }
  343. doAction(event) {
  344. switch (event.action) {
  345. case 'setLibs': this.commitLibs(event.data); break;
  346. case 'setRootLink': this.rootLink = event.data; this.rootLinkInput(); break;
  347. case 'setSelectedLink': this.selectedLink = event.data; this.selectedLinkInput(); break;
  348. case 'editBookmark': this.addBookmark('edit', event.data.link, event.data.desc); break;
  349. case 'addBookmark': this.addBookmark('add'); break;
  350. }
  351. }
  352. get mode() {
  353. return this.$store.state.config.mode;
  354. }
  355. get header() {
  356. let result = (this.ready ? 'Библиотека' : 'Загрузка...');
  357. if (this.ready && this.selectedLink) {
  358. result += ` | ${(this.libs.comment ? this.libs.comment + ' ': '') + lu.removeProtocol(this.libs.startLink)}`;
  359. }
  360. this.$root.$emit('set-app-title', result);
  361. return result;
  362. }
  363. get rootLinkWithoutProtocol() {
  364. return lu.removeProtocol(this.rootLink);
  365. }
  366. updateSelectedLinkByRoot() {
  367. if (!this.ready)
  368. return;
  369. const index = lu.getSafeRootIndexByUrl(this.libs.groups, this.rootLink);
  370. if (index >= 0)
  371. this.selectedLink = this.libs.groups[index].s;
  372. else
  373. this.selectedLink = '';
  374. }
  375. updateStartLink(force) {
  376. if (!this.ready)
  377. return;
  378. let index = -1;
  379. try {
  380. this.rootLink = lu.getOrigin(this.selectedLink);
  381. index = lu.getRootIndexByUrl(this.libs.groups, this.rootLink);
  382. } catch(e) {
  383. //
  384. }
  385. if (index >= 0) {
  386. let libs = _.cloneDeep(this.libs);
  387. const com = this.getCommentByLink(libs.groups[index].list, this.selectedLink);
  388. if (libs.groups[index].s != this.selectedLink ||
  389. libs.startLink != this.selectedLink ||
  390. libs.comment != com) {
  391. libs.groups[index].s = this.selectedLink;
  392. libs.startLink = this.selectedLink;
  393. libs.comment = com;
  394. this.commitLibs(libs);
  395. }
  396. if (force || this.oldStartLink != libs.startLink) {
  397. this.oldStartLink = libs.startLink;
  398. this.debouncedGoToLink(this.selectedLink);
  399. }
  400. } else {
  401. this.rootLink = '';
  402. this.selectedLink = '';
  403. this.debouncedGoToLink(this.selectedLink);
  404. }
  405. }
  406. get rootLinkOptions() {
  407. let result = [];
  408. if (!this.ready)
  409. return result;
  410. this.libs.groups.forEach(group => {
  411. result.push({label: lu.removeProtocol(group.r), value: group.r});
  412. });
  413. return result;
  414. }
  415. get defaultRootLinkOptions() {
  416. let result = [];
  417. rstore.libsDefaults.groups.forEach(group => {
  418. result.push({label: lu.removeProtocol(group.r), value: group.r});
  419. });
  420. return result;
  421. }
  422. get selectedLinkOptions() {
  423. let result = [];
  424. if (!this.ready)
  425. return result;
  426. const index = lu.getSafeRootIndexByUrl(this.libs.groups, this.rootLink);
  427. if (index >= 0) {
  428. this.libs.groups[index].list.forEach(link => {
  429. result.push({label: (link.c ? link.c + ' ': '') + lu.removeOrigin(link.l), value: link.l});
  430. });
  431. }
  432. return result;
  433. }
  434. openBookUrlInFrame() {
  435. if (this.bookUrl) {
  436. this.goToLink(lu.addProtocol(this.bookUrl));
  437. }
  438. }
  439. goToLink(link) {
  440. if (!this.ready || !link)
  441. return;
  442. if (!link) {
  443. this.frameVisible = false;
  444. return;
  445. }
  446. this.frameSrc = this.makeProxySubst(link);
  447. this.frameVisible = false;
  448. this.$nextTick(() => {
  449. this.frameVisible = true;
  450. this.$nextTick(() => {
  451. if (this.$refs.frame) {
  452. this.$refs.frame.contentWindow.focus();
  453. this.frameResize();
  454. }
  455. });
  456. });
  457. }
  458. frameResize() {
  459. this.$refs.frameWrap.style = 'width: 1px; height: 1px;';
  460. this.$nextTick(() => {
  461. if (this.$refs.frame) {
  462. const w = this.$refs.frameBox.offsetWidth;
  463. const h = this.$refs.frameBox.offsetHeight;
  464. const normalSize = `width: ${w}px; height: ${h}px;`;
  465. this.$refs.frameWrap.style = normalSize;
  466. if (this.frameScale != 1) {
  467. const s = this.frameScale;
  468. this.$refs.frame.style = `width: ${w/s}px; height: ${h/s}px; transform: scale(${s}); transform-origin: 0 0;`;
  469. } else {
  470. this.$refs.frame.style = normalSize;
  471. }
  472. }
  473. });
  474. }
  475. changeScale(delta) {
  476. if ((this.frameScale > 0.1 && delta <= 0) || (this.frameScale < 5 && delta >= 0)) {
  477. this.frameScale = _.round(this.frameScale + delta, 1);
  478. const index = lu.getSafeRootIndexByUrl(this.libs.groups, this.selectedLink);
  479. if (index >= 0) {
  480. let libs = _.cloneDeep(this.libs);
  481. libs.groups[index].frameScale = this.frameScale;
  482. this.commitLibs(libs);
  483. }
  484. this.frameResize();
  485. this.$root.notify.success(`Масштаб изменен: ${(this.frameScale*100).toFixed(0)}%`, '', {position: 'bottom-right'});
  486. }
  487. }
  488. getCommentByLink(list, link) {
  489. const item = lu.getListItemByLink(list, link);
  490. return (item ? item.c : '');
  491. }
  492. makeProxySubst(url, reverse = false) {
  493. for (const [key, value] of Object.entries(proxySubst)) {
  494. if (reverse && value == url.substring(0, value.length)) {
  495. return key + url.substring(value.length);
  496. } else if (!reverse && key == url.substring(0, key.length)) {
  497. return value + url.substring(key.length);
  498. }
  499. }
  500. return url;
  501. }
  502. selectAllOnFocus(event) {
  503. if (event.target.select)
  504. event.target.select();
  505. }
  506. rootLinkInput() {
  507. this.updateSelectedLinkByRoot();
  508. this.updateStartLink(true);
  509. }
  510. selectedLinkInput() {
  511. this.updateStartLink(true);
  512. }
  513. submitUrl() {
  514. if (this.bookUrl) {
  515. this.sendMessage({type: 'submitUrl', data: {
  516. url: this.bookUrl,
  517. force: true
  518. }});
  519. this.bookUrl = '';
  520. if (this.closeAfterSubmit)
  521. this.close();
  522. }
  523. }
  524. addBookmark(mode = 'add', link = '', desc = '') {
  525. if (mode == 'edit') {
  526. this.editBookmarkLink = this.bookmarkLink = link;
  527. this.editBookmarkDesc = this.bookmarkDesc = desc;
  528. } else {
  529. this.bookmarkLink = this.bookUrl;
  530. this.bookmarkDesc = '';
  531. }
  532. this.addBookmarkMode = mode;
  533. this.addBookmarkVisible = true;
  534. this.$nextTick(() => {
  535. this.$refs.bookmarkLink.focus();
  536. this.$refs.defaultRootLink.toggleOption = this.toggleOption;
  537. });
  538. }
  539. updateBookmarkLink() {
  540. const index = lu.getSafeRootIndexByUrl(rstore.libsDefaults.groups, this.defaultRootLink);
  541. if (index >= 0) {
  542. this.bookmarkLink = rstore.libsDefaults.groups[index].s;
  543. this.bookmarkDesc = this.getCommentByLink(rstore.libsDefaults.groups[index].list, this.bookmarkLink);
  544. } else {
  545. this.bookmarkLink = '';
  546. this.bookmarkDesc = '';
  547. }
  548. }
  549. defaultRootLinkInput() {
  550. this.updateBookmarkLink();
  551. }
  552. bookmarkLinkKeyDown(event) {
  553. if (event.key == 'Enter') {
  554. this.$refs.bookmarkDesc.focus();
  555. event.preventDefault();
  556. }
  557. }
  558. bookmarkDescKeyDown(event) {
  559. if (event.key == 'Enter') {
  560. event.stopPropagation();
  561. event.preventDefault();
  562. this.okAddBookmark();
  563. }
  564. }
  565. async okAddBookmark() {
  566. if (!this.bookmarkLink)
  567. return;
  568. const link = (this.addBookmarkMode == 'edit' ? lu.addProtocol(this.editBookmarkLink) : lu.addProtocol(this.bookmarkLink));
  569. let index = -1;
  570. try {
  571. index = lu.getRootIndexByUrl(this.libs.groups, link);
  572. } catch (e) {
  573. await this.$root.stdDialog.alert('Неверный формат ссылки', 'Ошибка');
  574. return;
  575. }
  576. let libs = _.cloneDeep(this.libs);
  577. //добавление
  578. //есть группа в закладках
  579. if (index >= 0) {
  580. const item = lu.getListItemByLink(libs.groups[index].list, link);
  581. //редактирование
  582. if (item && this.addBookmarkMode == 'edit') {
  583. if (item) {
  584. //редактируем
  585. item.l = link;
  586. item.c = this.bookmarkDesc;
  587. this.commitLibs(libs);
  588. } else {
  589. await this.$root.stdDialog.alert('Не удалось отредактировать закладку', 'Ошибка');
  590. }
  591. } else if (!item) {
  592. //добавляем
  593. if (libs.groups[index].list.length >= 100) {
  594. await this.$root.stdDialog.alert('Достигнут предел количества закладок для этого сайта', 'Ошибка');
  595. return;
  596. }
  597. libs.groups[index].list.push({l: link, c: this.bookmarkDesc});
  598. if (this.openInFrameOnAdd) {
  599. libs.startLink = link;
  600. libs.comment = this.bookmarkDesc;
  601. }
  602. this.commitLibs(libs);
  603. } else if (item.c != this.bookmarkDesc) {
  604. if (await this.$root.stdDialog.confirm(`Такая закладка уже существует с другим описанием.<br>` +
  605. `Заменить '${this.$sanitize(item.c)}' на '${this.$sanitize(this.bookmarkDesc)}'?`, ' ')) {
  606. item.c = this.bookmarkDesc;
  607. this.commitLibs(libs);
  608. } else
  609. return;
  610. } else {
  611. await this.$root.stdDialog.alert('Такая закладка уже существует', ' ');
  612. return;
  613. }
  614. } else {//нет группы в закладках
  615. if (libs.groups.length >= 100) {
  616. await this.$root.stdDialog.alert('Достигнут предел количества различных сайтов в закладках', 'Ошибка');
  617. return;
  618. }
  619. //добавляем сначала группу
  620. libs.groups.push({r: lu.getOrigin(link), s: link, list: []});
  621. index = lu.getSafeRootIndexByUrl(libs.groups, link);
  622. if (index >= 0)
  623. libs.groups[index].list.push({l: link, c: this.bookmarkDesc});
  624. if (this.openInFrameOnAdd) {
  625. libs.startLink = link;
  626. libs.comment = this.bookmarkDesc;
  627. }
  628. this.commitLibs(libs);
  629. }
  630. this.addBookmarkVisible = false;
  631. }
  632. fullScreenToggle() {
  633. this.fullScreenActive = !this.fullScreenActive;
  634. if (this.fullScreenActive) {
  635. this.$q.fullscreen.request();
  636. } else {
  637. this.$q.fullscreen.exit();
  638. }
  639. }
  640. transparentLayoutClick() {
  641. this.transparentLayoutVisible = false;
  642. }
  643. onSelectPopupShow() {
  644. this.transparentLayoutVisible = true;
  645. }
  646. onSelectPopupHide() {
  647. this.transparentLayoutVisible = false;
  648. }
  649. close() {
  650. this.sendMessage({type: 'close'});
  651. }
  652. bookUrlKeyDown(event) {
  653. if (event.key == 'Enter') {
  654. if (!this.openInFrameOnEnter) {
  655. this.submitUrl();
  656. } else {
  657. if (this.bookUrl)
  658. this.goToLink(this.bookUrl);
  659. }
  660. event.preventDefault();
  661. }
  662. }
  663. bookmarkSettings() {
  664. this.bookmarkSettingsActive = true;
  665. this.$nextTick(() => {
  666. this.$refs.bookmarkSettings.init();
  667. });
  668. }
  669. closeBookmarkSettings() {
  670. this.bookmarkSettingsActive = false;
  671. }
  672. showHelp() {
  673. this.$root.stdDialog.alert(`
  674. <p>Окно 'Библиотека' позволяет открывать ссылки в читалке без переключения между окнами,
  675. что особенно актуально для мобильных устройств.</p>
  676. <p>'Библиотека' разрешает свободный доступ к сайту flibusta.is. Имеется возможность управлять закладками
  677. на понравившиеся ресурсы, книги или страницы авторов. Открытие ссылок и навигация происходят во фрейме, но,
  678. к сожалению, в нем открываются не все страницы.
  679. </p>
  680. <p>Из-за проблем с безопасностью, навигация 'вперед-назад' во фрейме осуществляется с помощью контекстного меню правой кнопкой мыши.
  681. На мобильных устройствах для этого служит системная клавиша 'Назад (стрелка влево)' и опция 'Вперед (стрелка вправо)' в меню браузера.
  682. </p>
  683. <p>Приятного пользования ;-)
  684. </p>
  685. `, 'Справка', {iconName: 'la la-info-circle'});
  686. }
  687. keyHook(event) {
  688. if (this.$root.rootRoute() == '/external-libs') {
  689. if (this.$root.stdDialog.active)
  690. return false;
  691. if (this.bookmarkSettingsActive && this.$refs.bookmarkSettings.keyHook(event))
  692. return true;
  693. if (this.addBookmarkVisible || this.optionsVisible)
  694. return false;
  695. if (event.type == 'keydown' && event.key == 'F4') {
  696. this.addBookmark();
  697. return true;
  698. }
  699. if (event.type == 'keydown' && event.key == 'Escape' &&
  700. (document.activeElement != this.$refs.rootLink.$refs.target || !this.$refs.rootLink.menu) &&
  701. (document.activeElement != this.$refs.selectedLink.$refs.target || !this.$refs.selectedLink.menu)
  702. ) {
  703. this.close();
  704. return true;
  705. }
  706. }
  707. return false;
  708. }
  709. }
  710. //-----------------------------------------------------------------------------
  711. </script>
  712. <style scoped>
  713. .separator {
  714. height: 1px;
  715. background-color: #A0A0A0;
  716. }
  717. .full-screen-button {
  718. width: 30px;
  719. height: 30px;
  720. cursor: pointer;
  721. }
  722. .full-screen-button:hover {
  723. background-color: #69C05F;
  724. }
  725. .transparent-layout {
  726. top: 0;
  727. left: 0;
  728. position: absolute;
  729. }
  730. </style>