Search.vue 31 KB

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