Search.vue 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  1. <template>
  2. <div class="root column fit" style="position: relative">
  3. <div ref="scroller" class="col fit column no-wrap" style="overflow: auto; position: relative" @scroll="onScroll">
  4. <div ref="toolPanel" class="tool-panel column bg-cyan-2" style="position: sticky; top: 0; z-index: 10;">
  5. <div class="header q-mx-md q-mb-xs q-mt-sm row items-center">
  6. <a :href="newSearchLink" style="height: 33px">
  7. <img src="./assets/logo.png" />
  8. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
  9. Новый поиск
  10. </q-tooltip>
  11. </a>
  12. <div class="row items-center q-ml-sm" style="font-size: 150%;">
  13. <div class="q-mr-xs">
  14. Коллекция
  15. </div>
  16. <div class="clickable" @click="showCollectionInfo">
  17. {{ collection }}
  18. </div>
  19. </div>
  20. <q-btn-toggle
  21. v-if="extendedSearch"
  22. v-model="selectedList"
  23. class="q-ml-md"
  24. toggle-color="primary"
  25. :options="listOptions"
  26. push
  27. no-caps
  28. rounded
  29. />
  30. <DivBtn class="q-ml-md text-white bg-secondary" :size="30" :icon-size="24" :imt="1" icon="la la-cog" round @click="settingsDialogVisible = true">
  31. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
  32. Настройки
  33. </q-tooltip>
  34. </DivBtn>
  35. <DivBtn class="q-ml-sm text-white bg-secondary" :size="30" :icon-size="24" icon="la la-question" round @click="showSearchHelp">
  36. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
  37. Памятка
  38. </q-tooltip>
  39. </DivBtn>
  40. <div class="col"></div>
  41. <div class="q-px-sm q-py-xs bg-green-12 clickable2" style="border: 1px solid #aaaaaa; border-radius: 6px" @click="openReleasePage">
  42. {{ projectName }}
  43. </div>
  44. </div>
  45. <div class="row q-mx-md q-mb-sm items-center">
  46. <q-input
  47. ref="authorInput" v-model="search.author" :maxlength="5000" :debounce="inputDebounce"
  48. class="bg-white q-mt-xs" style="width: 300px;" label="Автор" stack-label outlined dense clearable
  49. >
  50. <q-tooltip v-if="search.author" :delay="500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
  51. {{ search.author }}
  52. </q-tooltip>
  53. </q-input>
  54. <div class="q-mx-xs" />
  55. <q-input
  56. v-model="search.series" :maxlength="inputMaxLength" :debounce="inputDebounce"
  57. class="bg-white q-mt-xs" style="width: 200px;" label="Серия" stack-label outlined dense clearable
  58. >
  59. <q-tooltip v-if="search.series" :delay="500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
  60. {{ search.series }}
  61. </q-tooltip>
  62. </q-input>
  63. <div class="q-mx-xs" />
  64. <q-input
  65. v-model="search.title" :maxlength="inputMaxLength" :debounce="inputDebounce"
  66. class="bg-white q-mt-xs" style="width: 200px;" label="Название" stack-label outlined dense clearable
  67. >
  68. <q-tooltip v-if="search.title" :delay="500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
  69. {{ search.title }}
  70. </q-tooltip>
  71. </q-input>
  72. <div class="q-mx-xs" />
  73. <q-input
  74. v-model="genreNames" :maxlength="inputMaxLength" :debounce="inputDebounce"
  75. class="bg-white q-mt-xs" input-style="cursor: pointer" style="width: 200px;" label="Жанр" stack-label outlined dense clearable readonly
  76. @click="selectGenre"
  77. >
  78. <template v-if="genreNames" #append>
  79. <q-icon name="la la-times-circle" class="q-field__focusable-action" @click.stop.prevent="search.genre = ''" />
  80. </template>
  81. <q-tooltip v-if="genreNames && showTooltips" :delay="500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
  82. {{ genreNames }}
  83. </q-tooltip>
  84. </q-input>
  85. <div class="q-mx-xs" />
  86. <q-input
  87. v-model="search.lang" :maxlength="inputMaxLength" :debounce="inputDebounce"
  88. class="bg-white q-mt-xs" input-style="cursor: pointer" style="width: 80px;" label="Язык" stack-label outlined dense clearable readonly
  89. @click="selectLang"
  90. >
  91. <q-tooltip v-if="search.lang && showTooltips" :delay="500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
  92. {{ search.lang }}
  93. </q-tooltip>
  94. </q-input>
  95. <div class="q-mx-xs" />
  96. <div class="row items-center q-mt-xs">
  97. <div v-show="list.queryFound > 0">
  98. {{ foundCountMessage }}
  99. </div>
  100. <div v-show="list.queryFound == 0">
  101. Ничего не найдено
  102. </div>
  103. </div>
  104. </div>
  105. </div>
  106. <div class="row justify-center" style="min-height: 48px">
  107. <PageScroller v-show="pageCount > 1" ref="pageScroller1" v-model="search.page" :page-count="pageCount" />
  108. </div>
  109. <!-- Формирование списка ------------------------------------------------------------------------>
  110. <component :is="selectedListComponent" v-if="selectedListComponent" ref="list" :list="list" :search="search" :genre-map="genreMap" @list-event="listEvent" />
  111. <!-- Формирование списка конец ------------------------------------------------------------------>
  112. <div class="row justify-center">
  113. <PageScroller v-show="pageCount > 1" v-model="search.page" :page-count="pageCount" />
  114. </div>
  115. <div v-show="pageCount <= 1" class="q-mt-lg" />
  116. </div>
  117. <Dialog v-model="settingsDialogVisible">
  118. <template #header>
  119. <div class="row items-center" style="font-size: 130%">
  120. <q-icon class="q-mr-sm" name="la la-cog" size="28px"></q-icon>
  121. Настройки
  122. </div>
  123. </template>
  124. <div class="q-mx-md column" style="min-width: 300px; font-size: 120%;">
  125. <div class="row items-center q-ml-sm">
  126. <div class="q-mr-sm">
  127. Результатов на странице
  128. </div>
  129. <q-select
  130. v-model="limit" :options="limitOptions" class="bg-white"
  131. dropdown-icon="la la-angle-down la-sm"
  132. outlined dense emit-value map-options
  133. />
  134. </div>
  135. <q-checkbox v-model="showCounts" size="36px" label="Показывать количество" />
  136. <q-checkbox v-model="showRate" size="36px" label="Показывать оценки" />
  137. <q-checkbox v-model="showGenres" size="36px" label="Показывать жанры" />
  138. <q-checkbox v-model="showDeleted" size="36px" label="Показывать удаленные" />
  139. <q-checkbox v-model="abCacheEnabled" size="36px" label="Кешировать запросы" />
  140. </div>
  141. <template #footer>
  142. <q-btn class="q-px-md q-ml-sm" color="primary" dense no-caps @click="settingsDialogVisible = false">
  143. OK
  144. </q-btn>
  145. </template>
  146. </Dialog>
  147. <SelectGenreDialog v-model="selectGenreDialogVisible" v-model:genre="search.genre" :genre-tree="genreTree" />
  148. <SelectLangDialog v-model="selectLangDialogVisible" v-model:lang="search.lang" :lang-list="langList" :lang-default="langDefault" />
  149. </div>
  150. </template>
  151. <script>
  152. //-----------------------------------------------------------------------------
  153. import vueComponent from '../vueComponent.js';
  154. import AuthorList from './AuthorList/AuthorList.vue';
  155. import SeriesList from './SeriesList/SeriesList.vue';
  156. import PageScroller from './PageScroller/PageScroller.vue';
  157. import SelectGenreDialog from './SelectGenreDialog/SelectGenreDialog.vue';
  158. import SelectLangDialog from './SelectLangDialog/SelectLangDialog.vue';
  159. import authorBooksStorage from './authorBooksStorage';
  160. import DivBtn from '../share/DivBtn.vue';
  161. import Dialog from '../share/Dialog.vue';
  162. import * as utils from '../../share/utils';
  163. import diffUtils from '../../share/diffUtils';
  164. import _ from 'lodash';
  165. const route2component = {
  166. 'author': {component: 'AuthorList', label: 'Авторы'},
  167. 'series': {component: 'SeriesList', label: 'Серии'},
  168. 'book': {component: 'AuthorList', label: 'Книги'},
  169. };
  170. const componentOptions = {
  171. components: {
  172. AuthorList,
  173. SeriesList,
  174. PageScroller,
  175. SelectGenreDialog,
  176. SelectLangDialog,
  177. Dialog,
  178. DivBtn
  179. },
  180. watch: {
  181. config(newValue) {
  182. this.makeProjectName();
  183. if (newValue.dbConfig)
  184. this.list.inpxHash = newValue.dbConfig.inpxHash;
  185. },
  186. settings() {
  187. this.loadSettings();
  188. },
  189. search: {
  190. handler(newValue) {
  191. this.limit = newValue.limit;
  192. if (this.pageCount > 1)
  193. this.prevPage = this.search.page;
  194. this.makeTitle();
  195. this.updateRouteQueryFromSearch();
  196. },
  197. deep: true,
  198. },
  199. limit(newValue) {
  200. this.setSetting('limit', newValue);
  201. this.updatePageCount();
  202. },
  203. showCounts(newValue) {
  204. this.setSetting('showCounts', newValue);
  205. },
  206. showRate(newValue) {
  207. this.setSetting('showRate', newValue);
  208. },
  209. showGenres(newValue) {
  210. this.setSetting('showGenres', newValue);
  211. },
  212. showDeleted(newValue) {
  213. this.setSetting('showDeleted', newValue);
  214. },
  215. abCacheEnabled(newValue) {
  216. this.setSetting('abCacheEnabled', newValue);
  217. },
  218. $route(to) {
  219. this.updateListFromRoute(to);
  220. this.updateSearchFromRouteQuery(to);
  221. },
  222. langDefault() {
  223. this.updateSearchFromRouteQuery(this.$route);
  224. },
  225. list: {
  226. handler(newValue) {
  227. this.updateGenreTreeIfNeeded();
  228. if (this.prevList.totalFound != newValue.totalFound) {
  229. this.updatePageCount();
  230. this.foundCountMessage = this.$refs.list.foundCountMessage;
  231. }
  232. this.prevList = _.cloneDeep(newValue);
  233. },
  234. deep: true,
  235. },
  236. selectedList(newValue) {
  237. this.selectedListComponent = (route2component[newValue] ? route2component[newValue].component : null);
  238. this.pageCount = 1;
  239. if (this.getListRoute() != newValue) {
  240. this.updateRouteQueryFromSearch();
  241. }
  242. }
  243. },
  244. };
  245. class Search {
  246. _options = componentOptions;
  247. ready = false;
  248. selectedList = '';
  249. selectedListComponent = '';
  250. collection = '';
  251. projectName = '';
  252. foundCountMessage = '';
  253. settingsDialogVisible = false;
  254. selectGenreDialogVisible = false;
  255. selectLangDialogVisible = false;
  256. pageCount = 1;
  257. //input field consts
  258. inputMaxLength = 1000;
  259. inputDebounce = 200;
  260. //search fields
  261. search = {
  262. setDefaults(search) {
  263. return Object.assign({}, search, {
  264. author: search.author || '',
  265. series: search.series || '',
  266. title: search.title || '',
  267. genre: search.genre || '',
  268. lang: search.lang || '',
  269. page: search.page || 1,
  270. limit: search.limit || 50,
  271. });
  272. },
  273. };
  274. //settings
  275. showCounts = true;
  276. showRate = true;
  277. showGenres = true;
  278. showDeleted = false;
  279. abCacheEnabled = true;
  280. langDefault = '';
  281. limit = 20;
  282. //stuff
  283. prevList = {};
  284. list = {
  285. queryFound: -1,
  286. totalFound: -1,
  287. inpxHash: '',
  288. liberamaReady: false,
  289. };
  290. genreTree = [];
  291. genreMap = new Map();
  292. langList = [];
  293. genreTreeInpxHash = '';
  294. showTooltips = true;
  295. limitOptions = [
  296. {label: '10', value: 10},
  297. {label: '20', value: 20},
  298. {label: '50', value: 50},
  299. {label: '100', value: 100},
  300. {label: '200', value: 200},
  301. {label: '500', value: 500},
  302. {label: '1000', value: 1000},
  303. ];
  304. searchResult = {};
  305. tableData = [];
  306. created() {
  307. this.commit = this.$store.commit;
  308. this.api = this.$root.api;
  309. this.search = this.search.setDefaults(this.search);
  310. this.search.lang = this.langDefault;
  311. this.loadSettings();
  312. }
  313. mounted() {
  314. (async() => {
  315. //для встраивания в liberama
  316. window.addEventListener('message', (event) => {
  317. if (!_.isObject(event.data) || event.data.from != 'ExternalLibs')
  318. return;
  319. //console.log(event);
  320. this.recvMessage(event.data);
  321. });
  322. //локальный кеш
  323. await authorBooksStorage.init();
  324. if (!this.$root.isMobileDevice)
  325. this.$refs.authorInput.focus();
  326. this.updateListFromRoute(this.$route);
  327. this.updateSearchFromRouteQuery(this.$route);
  328. this.sendMessage({type: 'mes', data: 'hello-from-inpx-web'});
  329. this.ready = true;
  330. })();
  331. }
  332. loadSettings() {
  333. const settings = this.settings;
  334. this.search.limit = settings.limit;
  335. this.expanded = _.cloneDeep(settings.expanded);
  336. this.expandedSeries = _.cloneDeep(settings.expandedSeries);
  337. this.showCounts = settings.showCounts;
  338. this.showRate = settings.showRate;
  339. this.showGenres = settings.showGenres;
  340. this.showDeleted = settings.showDeleted;
  341. this.abCacheEnabled = settings.abCacheEnabled;
  342. this.langDefault = settings.langDefault;
  343. }
  344. recvMessage(d) {
  345. if (d.type == 'mes') {
  346. switch(d.data) {
  347. case 'ready':
  348. this.list.liberamaReady = true;
  349. this.sendMessage({type: 'mes', data: 'ready'});
  350. this.sendCurrentUrl();
  351. break;
  352. }
  353. }
  354. }
  355. sendMessage(d) {
  356. window.parent.postMessage(Object.assign({}, {from: 'inpx-web'}, d), '*');
  357. }
  358. sendCurrentUrl() {
  359. this.sendMessage({type: 'urlChange', data: window.location.href});
  360. }
  361. get config() {
  362. return this.$store.state.config;
  363. }
  364. get extendedSearch() {
  365. return this.config.extendedSearch;
  366. }
  367. get settings() {
  368. return this.$store.state.settings;
  369. }
  370. get genreNames() {
  371. let result = [];
  372. const genre = this.search.genre.split(',');
  373. for (const g of genre) {
  374. const name = this.genreMap.get(g);
  375. if (name)
  376. result.push(name);
  377. }
  378. return result.join(', ');
  379. }
  380. get listOptions() {
  381. const result = [];
  382. for (const [route, rec] of Object.entries(route2component))
  383. result.push({label: rec.label, value: route});
  384. return result;
  385. }
  386. async updateListFromRoute(to) {
  387. const newPath = to.path;
  388. let newList = this.getListRoute(newPath);
  389. newList = (newList && this.extendedSearch ? newList : 'author');
  390. if (this.selectedList != newList)
  391. this.selectedList = newList;
  392. }
  393. getListRoute(newPath) {
  394. newPath = (newPath ? newPath : this.$route.path);
  395. const m = newPath.match(/^\/([^/]*).*$/i);
  396. return (m ? m[1] : newPath);
  397. }
  398. openReleasePage() {
  399. window.open('https://github.com/bookpauk/inpx-web/releases', '_blank');
  400. }
  401. makeProjectName() {
  402. const collection = this.config.dbConfig.inpxInfo.collection.split('\n');
  403. this.collection = collection[0].trim();
  404. this.projectName = `${this.config.name} v${this.config.webAppVersion}`;
  405. this.makeTitle();
  406. }
  407. makeTitle() {
  408. if (!this.collection)
  409. return;
  410. let result = `Коллекция ${this.collection}`;
  411. const search = this.search;
  412. const specSym = new Set(['*', '#']);
  413. const correctValue = (v) => {
  414. if (v) {
  415. if (v[0] === '=')
  416. v = v.substring(1);
  417. else if (!specSym.has(v[0]))
  418. v = '^' + v;
  419. }
  420. return v || '';
  421. };
  422. if (search.author || search.series || search.title) {
  423. const as = (search.author ? search.author.split(',') : []);
  424. const author = (as.length ? as[0] : '') + (as.length > 1 ? ' и др.' : '');
  425. const a = correctValue(author);
  426. let s = correctValue(search.series);
  427. s = (s ? `(${s})` : '');
  428. let t = correctValue(search.title);
  429. t = (t ? `"${t}"` : '');
  430. result = [s, t].filter(v => v).join(' ');
  431. result = [a, result].filter(v => v).join(' ');
  432. }
  433. this.$root.setAppTitle(result);
  434. if (this.list.liberamaReady)
  435. this.sendMessage({type: 'titleChange', data: result});
  436. }
  437. showSearchHelp() {
  438. let info = '';
  439. info += `<div style="min-width: 250px" />`;
  440. info += `
  441. <p>
  442. Для раздела <b>Авторы</b>, работу поискового движка можно описать простой фразой: найти авторов по указанным критериям.
  443. По тем же критериям среди найденных авторов фильтруются книги, сортируются и группируются по сериям.
  444. <br><br>
  445. По умолчанию поисковое значение трактуется как "начинается с". Например значение автора "Пушкин"
  446. трактуется как: найти авторов, имя которых начинается с "Пушкин". Поиск всегда ведется без
  447. учета регистра - значения "Ельцин" и "ельцин" равнозначны.
  448. <br><br>
  449. В поисковых полях "Автор", "Серия", "Название" также доступны следующие префиксы:
  450. <ul>
  451. <li>
  452. "=" поиск по точному совпадению. Например, если задать "=Пушкин Александр Сергеевич" в поле автора,
  453. то будет найден в точности этот автор
  454. </li>
  455. <br>
  456. <li>
  457. "*" поиск подстроки в строке. Например, для "*Александр" в поле автора, будут найдены
  458. все авторы, имя которых содержит "Александр"
  459. </li>
  460. <br>
  461. <li>
  462. "#" поиск подстроки в строке, но только для тех значений, которые не начинаются ни с одной буквы русского или латинского алфавита.
  463. Например, значение "#поворот" в поле автора означает: найти всех авторов, имя которых начинается не с русской или латинской буквы и содержит слово "поворот".
  464. Указание простого "#" в поиске по названию означает: найти всех авторов, названия книг которых начинаются не с русской или латинской буквы
  465. </li>
  466. <br>
  467. <li>
  468. "?" поиск пустых значений или тех, что начинаются с этого символа. Например, "?" в поле серии означает: найти всех авторов, у которых есть книги без серий
  469. или название серии начинается с "?".
  470. Значение "?" в поле названия означает: найти всех авторов, книги которых без названия или начинаются с "?"
  471. </li>
  472. </ul>
  473. <br>
  474. Специльное имя автора "?" служит для поиска и группировки книг без автора.
  475. <br><br>
  476. Для разделов <b>Серии</b>, <b>Книги</b> все по аналогии с авторами.
  477. </p>
  478. `;
  479. this.$root.stdDialog.alert(info, 'Памятка', {iconName: 'la la-info-circle'});
  480. }
  481. showCollectionInfo() {
  482. /*
  483. "dbConfig": {
  484. "inpxInfo": {
  485. "collection": "Flibusta Offline 2 August 2022\r\nflibusta_all_local_2022-08-02\r\n65537\r\nFlibusta. A local collection. Total: 636591 books\r\nhttp://flibusta.is/",
  486. },
  487. "stats": {
  488. "recsLoaded": 687063,
  489. "authorCount": 153364,
  490. "authorCountAll": 177034,
  491. "bookCount": 576018,
  492. "bookCountAll": 687063,
  493. "bookDelCount": 111045,
  494. "noAuthorBookCount": 4347,
  495. "titleCount": 512671,
  496. "seriesCount": 54472,
  497. "genreCount": 238,
  498. "langCount": 102
  499. },
  500. */
  501. let info = '';
  502. const inpxInfo = this.config.dbConfig.inpxInfo;
  503. const stat = this.config.dbConfig.stats;
  504. const keyStyle = 'style="display: inline-block; text-align: right; margin-right: 5px; min-width: 200px"';
  505. info += `<div style="min-width: 250px" />`;
  506. info += `
  507. <div><div ${keyStyle}>Всего файлов книг:</div><span>${stat.filesCountAll}</span></div>
  508. <div><div ${keyStyle}>Из них актуальных:</div><span>${stat.filesCount}</span></div>
  509. <div><div ${keyStyle}>Помеченных как удаленные:</div><span>${stat.filesDelCount}</span></div>
  510. <br>
  511. <div><div ${keyStyle}>Обработано ссылок на файлы:</div><span>${stat.bookCountAll}</span></div>
  512. <div><div ${keyStyle}>Из них актуальных:</div><span>${stat.bookCount}</span></div>
  513. <div><div ${keyStyle}>Помеченных как удаленные:</div><span>${stat.bookDelCount}</span></div>
  514. <div><div ${keyStyle}>Актуальных без автора:</div><span>${stat.noAuthorBookCount}</span></div>
  515. <br>
  516. <div><div ${keyStyle}>Всего имен авторов:</div><span>${stat.authorCountAll}</span></div>
  517. <div><div ${keyStyle}>Уникальных имен без соавторов:</div><span>${stat.authorCount}</span></div>
  518. <div><div ${keyStyle}>С соавторами:</div><span>${stat.authorCountAll- stat.authorCount}</span></div>
  519. <br>
  520. <div><div ${keyStyle}>Уникальных названий книг:</div><span>${stat.titleCount}</span></div>
  521. <div><div ${keyStyle}>Уникальных названий серий:</div><span>${stat.seriesCount}</span></div>
  522. <div><div ${keyStyle}>Найдено жанров:</div><span>${stat.genreCount}</span></div>
  523. <div><div ${keyStyle}>Найдено языков:</div><span>${stat.langCount}</span></div>
  524. <br>
  525. <div><div ${keyStyle}>Версия поисковой БД:</div><span>${this.config.dbVersion}</span></div>
  526. `;
  527. info += `
  528. <div><hr/>
  529. <b>collection.info:</b>
  530. <pre>${inpxInfo.collection}</pre>
  531. </div>
  532. `;
  533. this.$root.stdDialog.alert(info, 'Статистика по коллекции', {iconName: 'la la-info-circle'});
  534. }
  535. get newSearchLink() {
  536. return window.location.origin;
  537. }
  538. async hideTooltip() {
  539. //Firefox bugfix: при всплывающем диалоге скрываем подсказку
  540. this.showTooltips = false;
  541. await utils.sleep(1000);
  542. this.showTooltips = true;
  543. }
  544. selectGenre() {
  545. this.hideTooltip();
  546. this.selectGenreDialogVisible = true;
  547. }
  548. selectLang() {
  549. this.hideTooltip();
  550. this.selectLangDialogVisible = true;
  551. }
  552. onScroll() {
  553. if (this.ignoreScrolling)
  554. return;
  555. const curScrollTop = this.$refs.scroller.scrollTop;
  556. if (!this.lastScrollTop)
  557. this.lastScrollTop = 0;
  558. if (!this.lastScrollTop2)
  559. this.lastScrollTop2 = 0;
  560. if (curScrollTop - this.lastScrollTop > 0) {
  561. this.$refs.toolPanel.style.position = 'relative';
  562. this.$refs.toolPanel.style.top = `${this.lastScrollTop2}px`;
  563. } else {
  564. this.$refs.toolPanel.style.position = 'sticky';
  565. this.$refs.toolPanel.style.top = 0;
  566. this.lastScrollTop2 = curScrollTop;
  567. }
  568. this.lastScrollTop = curScrollTop;
  569. }
  570. async ignoreScroll(ms = 50) {
  571. this.ignoreScrolling = true;
  572. await utils.sleep(ms);
  573. this.ignoreScrolling = false;
  574. }
  575. scrollToTop() {
  576. this.$refs.scroller.scrollTop = 0;
  577. this.lastScrollTop = 0;
  578. }
  579. updatePageCount() {
  580. if (this.list.totalFound < 0)
  581. return;
  582. const prevPageCount = this.pageCount;
  583. this.pageCount = Math.ceil(this.list.totalFound/this.limit);
  584. this.pageCount = (this.pageCount < 1 ? 1 : this.pageCount);
  585. if (this.prevPage && prevPageCount == 1 && this.pageCount > 1 && this.prevPage <= this.pageCount) {
  586. this.search.page = this.prevPage;
  587. }
  588. if (this.search.page > this.pageCount)
  589. this.search.page = 1;
  590. }
  591. listEvent(event) {
  592. switch (event.action) {
  593. case 'ignoreScroll':
  594. this.ignoreScroll();
  595. break;
  596. case 'highlightPageScroller':
  597. this.highlightPageScroller(event.query);
  598. break;
  599. case 'scrollToTop':
  600. this.scrollToTop();
  601. break;
  602. }
  603. }
  604. setSetting(name, newValue) {
  605. this.commit('setSettings', {[name]: _.cloneDeep(newValue)});
  606. }
  607. highlightPageScroller(query) {
  608. const q = _.cloneDeep(query);
  609. delete q.limit;
  610. delete q.offset;
  611. delete q.page;
  612. try {
  613. if (this.search.page < 2 || !this._prevQuery || _.isEqual(this._prevQuery, q))
  614. return;
  615. this.$refs.pageScroller1.highlightScroller();
  616. } finally {
  617. this._prevQuery = q;
  618. }
  619. }
  620. updateSearchFromRouteQuery(to) {
  621. if (this.list.liberamaReady)
  622. this.sendCurrentUrl();
  623. if (this.routeUpdating)
  624. return;
  625. const query = to.query;
  626. this.search = this.search.setDefaults(
  627. Object.assign({}, this.search, {
  628. author: query.author,
  629. series: query.series,
  630. title: query.title,
  631. genre: query.genre,
  632. lang: (typeof(query.lang) == 'string' ? query.lang : this.langDefault),
  633. page: parseInt(query.page, 10),
  634. limit: parseInt(query.limit, 10) || this.search.limit,
  635. })
  636. );
  637. if (this.search.limit > 1000)
  638. this.search.limit = 1000;
  639. }
  640. updateRouteQueryFromSearch() {
  641. if (!this.ready)
  642. return;
  643. this.routeUpdating = true;
  644. try {
  645. const oldQuery = this.$route.query;
  646. const cloned = _.cloneDeep(this.search);
  647. delete cloned.setDefaults;
  648. const query = _.pickBy(cloned);
  649. if (this.search.lang == this.langDefault) {
  650. delete query.lang;
  651. } else {
  652. query.lang = this.search.lang;
  653. }
  654. const diff = diffUtils.getObjDiff(oldQuery, query);
  655. if (!diffUtils.isEmptyObjDiff(diff)) {
  656. this.$router.replace({path: this.selectedList, query});
  657. }
  658. } finally {
  659. (async() => {
  660. await utils.sleep(100);
  661. this.routeUpdating = false;
  662. })();
  663. }
  664. }
  665. async updateGenreTreeIfNeeded() {
  666. if (this.genreTreeUpdating)
  667. return;
  668. this.genreTreeUpdating = true;
  669. try {
  670. if (this.genreTreeInpxHash !== this.list.inpxHash) {
  671. let result;
  672. if (this.abCacheEnabled) {
  673. const key = `genre-tree-${this.list.inpxHash}`;
  674. const data = await authorBooksStorage.getData(key);
  675. if (data) {
  676. result = JSON.parse(data);
  677. } else {
  678. result = await this.api.getGenreTree();
  679. await authorBooksStorage.setData(key, JSON.stringify(result));
  680. }
  681. } else {
  682. result = await this.api.getGenreTree();
  683. }
  684. this.genreTree = result.genreTree;
  685. this.genreMap = new Map();
  686. for (const section of this.genreTree) {
  687. for (const g of section.value)
  688. this.genreMap.set(g.value, g.name);
  689. }
  690. this.langList = result.langList;
  691. this.genreTreeInpxHash = result.inpxHash;
  692. }
  693. } catch (e) {
  694. this.$root.stdDialog.alert(e.message, 'Ошибка');
  695. } finally {
  696. this.genreTreeUpdating = false;
  697. }
  698. }
  699. }
  700. export default vueComponent(Search);
  701. //-----------------------------------------------------------------------------
  702. </script>
  703. <style scoped>
  704. .root {
  705. }
  706. .tool-panel {
  707. border-bottom: 1px solid black;
  708. }
  709. .header {
  710. min-height: 30px;
  711. }
  712. .clickable {
  713. color: blue;
  714. cursor: pointer;
  715. }
  716. .clickable2 {
  717. cursor: pointer;
  718. }
  719. </style>