Search.vue 39 KB

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