Search.vue 29 KB

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