Search.vue 31 KB

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