Search.vue 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047
  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: 'за 2 месяца', value: '2months'},
  407. {label: 'за 3 месяца', value: '3months'},
  408. {label: 'выбрать даты', value: 'manual'},
  409. ];
  410. created() {
  411. this.commit = this.$store.commit;
  412. this.api = this.$root.api;
  413. this.search = this.search.setDefaults(this.search);
  414. this.search.lang = this.langDefault;
  415. this.loadSettings();
  416. }
  417. mounted() {
  418. (async() => {
  419. //для встраивания в liberama
  420. window.addEventListener('message', (event) => {
  421. if (!_.isObject(event.data) || event.data.from != 'ExternalLibs')
  422. return;
  423. //console.log(event);
  424. this.recvMessage(event.data);
  425. });
  426. //локальный кеш
  427. await authorBooksStorage.init();
  428. if (!this.$root.isMobileDevice)
  429. this.$refs.authorInput.focus();
  430. this.updateListFromRoute(this.$route);
  431. this.updateSearchFromRouteQuery(this.$route);
  432. this.sendMessage({type: 'mes', data: 'hello-from-inpx-web'});
  433. this.ready = true;
  434. })();
  435. }
  436. loadSettings() {
  437. const settings = this.settings;
  438. this.search.limit = settings.limit;
  439. this.extendedParams = settings.extendedParams;
  440. this.expanded = _.cloneDeep(settings.expanded);
  441. this.expandedSeries = _.cloneDeep(settings.expandedSeries);
  442. this.showCounts = settings.showCounts;
  443. this.showRates = settings.showRates;
  444. this.showGenres = settings.showGenres;
  445. this.showDates = settings.showDates;
  446. this.showDeleted = settings.showDeleted;
  447. this.abCacheEnabled = settings.abCacheEnabled;
  448. this.langDefault = settings.langDefault;
  449. }
  450. recvMessage(d) {
  451. if (d.type == 'mes') {
  452. switch(d.data) {
  453. case 'ready':
  454. this.list.liberamaReady = true;
  455. this.sendMessage({type: 'mes', data: 'ready'});
  456. this.sendCurrentUrl();
  457. break;
  458. }
  459. }
  460. }
  461. sendMessage(d) {
  462. window.parent.postMessage(Object.assign({}, {from: 'inpx-web'}, d), '*');
  463. }
  464. sendCurrentUrl() {
  465. this.sendMessage({type: 'urlChange', data: window.location.href});
  466. }
  467. get config() {
  468. return this.$store.state.config;
  469. }
  470. get settings() {
  471. return this.$store.state.settings;
  472. }
  473. get genreNames() {
  474. let result = [];
  475. const genre = this.search.genre.split(',');
  476. for (const g of genre) {
  477. const name = this.genreMap.get(g);
  478. if (name)
  479. result.push(name);
  480. }
  481. return result.join(', ');
  482. }
  483. get librateNames() {
  484. let result = [];
  485. const rates = this.search.librate.split(',');
  486. for (const r of rates) {
  487. result.push(r == '0' ? 'Без оценки' : r);
  488. }
  489. return result.join(', ');
  490. }
  491. get listOptions() {
  492. const result = [];
  493. for (const [route, rec] of Object.entries(route2component))
  494. result.push({label: rec.label, value: route});
  495. return result;
  496. }
  497. get extendedParamsMessage() {
  498. const s = this.search;
  499. const result = [];
  500. result.push(s.genre ? 'Жанр' : '');
  501. result.push(s.date ? 'Дата поступления' : '');
  502. result.push(s.librate ? 'Оценка' : '');
  503. return result.filter(s => s).join(', ');
  504. }
  505. inputBgColor(inp) {
  506. if (inp === this.selectedList)
  507. return 'white';
  508. else
  509. return 'yellow-1';
  510. }
  511. async updateListFromRoute(to) {
  512. const newPath = to.path;
  513. let newList = this.getListRoute(newPath);
  514. newList = (newList ? newList : 'author');
  515. if (this.selectedList != newList)
  516. this.selectedList = newList;
  517. }
  518. getListRoute(newPath) {
  519. newPath = (newPath ? newPath : this.$route.path);
  520. const m = newPath.match(/^\/([^/]*).*$/i);
  521. return (m ? m[1] : newPath);
  522. }
  523. openReleasePage() {
  524. window.open('https://github.com/bookpauk/inpx-web/releases', '_blank');
  525. }
  526. makeProjectName() {
  527. const collection = this.config.dbConfig.inpxInfo.collection.split('\n');
  528. this.collection = collection[0].trim();
  529. this.projectName = `${this.config.name} v${this.config.webAppVersion}`;
  530. this.makeTitle();
  531. }
  532. makeTitle() {
  533. if (!this.collection)
  534. return;
  535. let result = `Коллекция ${this.collection}`;
  536. const search = this.search;
  537. const specSym = new Set(['*', '#']);
  538. const correctValue = (v) => {
  539. if (v) {
  540. if (v[0] === '=')
  541. v = v.substring(1);
  542. else if (!specSym.has(v[0]))
  543. v = '^' + v;
  544. }
  545. return v || '';
  546. };
  547. if (search.author || search.series || search.title) {
  548. const as = (search.author ? search.author.split(',') : []);
  549. const author = (as.length ? as[0] : '') + (as.length > 1 ? ' и др.' : '');
  550. const a = correctValue(author);
  551. let s = correctValue(search.series);
  552. s = (s ? `(Серия: ${s})` : '');
  553. let t = correctValue(search.title);
  554. t = (t ? `"${t}"` : '');
  555. result = [s, t].filter(v => v).join(' ');
  556. result = [a, result].filter(v => v).join(' ');
  557. }
  558. this.$root.setAppTitle(result);
  559. if (this.list.liberamaReady)
  560. this.sendMessage({type: 'titleChange', data: result});
  561. }
  562. showSearchHelp() {
  563. let info = '';
  564. info += `<div style="min-width: 250px" />`;
  565. info += `
  566. <p>
  567. Для раздела <b>Авторы</b>, работу поискового движка можно описать простой фразой: найти авторов по указанным критериям.
  568. По тем же критериям среди найденных авторов фильтруются книги, сортируются и группируются по сериям.
  569. <br><br>
  570. По умолчанию поисковое значение трактуется как "начинается с". Например значение автора "Пушкин"
  571. трактуется как: найти авторов, имя которых начинается с "Пушкин". Поиск всегда ведется без
  572. учета регистра - значения "Ельцин" и "ельцин" равнозначны.
  573. <br><br>
  574. В поисковых полях "Автор", "Серия", "Название" также доступны следующие префиксы:
  575. <ul>
  576. <li>
  577. "=" поиск по точному совпадению. Например, если задать "=Пушкин Александр Сергеевич" в поле автора,
  578. то будет найден в точности этот автор
  579. </li>
  580. <br>
  581. <li>
  582. "*" поиск подстроки в строке. Например, для "*Александр" в поле автора, будут найдены
  583. все авторы, имя которых содержит "Александр"
  584. </li>
  585. <br>
  586. <li>
  587. "#" поиск подстроки в строке, но только для тех значений, которые не начинаются ни с одной буквы русского или латинского алфавита.
  588. Например, значение "#поворот" в поле автора означает: найти всех авторов, имя которых начинается не с русской или латинской буквы и содержит слово "поворот".
  589. Указание простого "#" в поиске по названию означает: найти всех авторов, названия книг которых начинаются не с русской или латинской буквы
  590. </li>
  591. <br>
  592. <li>
  593. "?" поиск пустых значений или тех, что начинаются с этого символа. Например, "?" в поле серии означает: найти всех авторов, у которых есть книги без серий
  594. или название серии начинается с "?".
  595. Значение "?" в поле названия означает: найти всех авторов, книги которых без названия или начинаются с "?"
  596. </li>
  597. </ul>
  598. <br>
  599. Специльное имя автора "?" служит для поиска и группировки книг без автора.
  600. <br><br>
  601. Для разделов <b>Серии</b>, <b>Книги</b> все аналогично разделу <b>Авторы</b>.
  602. </p>
  603. `;
  604. this.$root.stdDialog.alert(info, 'Памятка', {iconName: 'la la-info-circle'});
  605. }
  606. showCollectionInfo() {
  607. /*
  608. "dbConfig": {
  609. "inpxInfo": {
  610. "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/",
  611. },
  612. "stats": {
  613. "recsLoaded": 687063,
  614. "authorCount": 153364,
  615. "authorCountAll": 177034,
  616. "bookCount": 576018,
  617. "bookCountAll": 687063,
  618. "bookDelCount": 111045,
  619. "noAuthorBookCount": 4347,
  620. "titleCount": 512671,
  621. "seriesCount": 54472,
  622. "genreCount": 238,
  623. "langCount": 102
  624. },
  625. */
  626. let info = '';
  627. const inpxInfo = this.config.dbConfig.inpxInfo;
  628. const stat = this.config.dbConfig.stats;
  629. const keyStyle = 'style="display: inline-block; text-align: right; margin-right: 5px; min-width: 200px"';
  630. info += `<div style="min-width: 250px" />`;
  631. info += `
  632. <div><div ${keyStyle}>Всего файлов книг:</div><span>${stat.filesCountAll}</span></div>
  633. <div><div ${keyStyle}>Из них актуальных:</div><span>${stat.filesCount}</span></div>
  634. <div><div ${keyStyle}>Помеченных как удаленные:</div><span>${stat.filesDelCount}</span></div>
  635. <br>
  636. <div><div ${keyStyle}>Обработано ссылок на файлы:</div><span>${stat.bookCountAll}</span></div>
  637. <div><div ${keyStyle}>Из них актуальных:</div><span>${stat.bookCount}</span></div>
  638. <div><div ${keyStyle}>Помеченных как удаленные:</div><span>${stat.bookDelCount}</span></div>
  639. <div><div ${keyStyle}>Актуальных без автора:</div><span>${stat.noAuthorBookCount}</span></div>
  640. <br>
  641. <div><div ${keyStyle}>Всего имен авторов:</div><span>${stat.authorCountAll}</span></div>
  642. <div><div ${keyStyle}>Уникальных имен без соавторов:</div><span>${stat.authorCount}</span></div>
  643. <div><div ${keyStyle}>С соавторами:</div><span>${stat.authorCountAll- stat.authorCount}</span></div>
  644. <br>
  645. <div><div ${keyStyle}>Уникальных названий книг:</div><span>${stat.titleCount}</span></div>
  646. <div><div ${keyStyle}>Уникальных названий серий:</div><span>${stat.seriesCount}</span></div>
  647. <div><div ${keyStyle}>Найдено жанров:</div><span>${stat.genreCount}</span></div>
  648. <div><div ${keyStyle}>Найдено языков:</div><span>${stat.langCount}</span></div>
  649. <br>
  650. <div><div ${keyStyle}>Версия поисковой БД:</div><span>${this.config.dbVersion}</span></div>
  651. `;
  652. info += `
  653. <div><hr/>
  654. <b>collection.info:</b>
  655. <pre>${inpxInfo.collection}</pre>
  656. </div>
  657. `;
  658. this.$root.stdDialog.alert(info, 'Статистика по коллекции', {iconName: 'la la-info-circle'});
  659. }
  660. get newSearchLink() {
  661. return window.location.origin;
  662. }
  663. async hideTooltip() {
  664. //Firefox bugfix: при всплывающем диалоге скрываем подсказку
  665. this.showTooltips = false;
  666. await utils.sleep(1000);
  667. this.showTooltips = true;
  668. }
  669. selectGenre() {
  670. this.hideTooltip();
  671. this.selectGenreDialogVisible = true;
  672. }
  673. selectLang() {
  674. this.hideTooltip();
  675. this.selectLangDialogVisible = true;
  676. }
  677. selectLibRate() {
  678. this.hideTooltip();
  679. this.selectLibRateDialogVisible = true;
  680. }
  681. onScroll() {
  682. const curScrollTop = this.$refs.scroller.scrollTop;
  683. if (this.ignoreScrolling) {
  684. this.lastScrollTop = curScrollTop;
  685. return;
  686. }
  687. if (!this.lastScrollTop)
  688. this.lastScrollTop = 0;
  689. if (!this.lastScrollTop2)
  690. this.lastScrollTop2 = 0;
  691. if (curScrollTop - this.lastScrollTop > 0) {
  692. this.$refs.toolPanel.style.position = 'relative';
  693. if (this.lastScrollTop2 <= curScrollTop - this.$refs.toolPanel.clientHeight)
  694. this.lastScrollTop2 = 0;
  695. this.$refs.toolPanel.style.top = `${this.lastScrollTop2}px`;
  696. } else {
  697. this.$refs.toolPanel.style.position = 'sticky';
  698. this.$refs.toolPanel.style.top = 0;
  699. this.lastScrollTop2 = curScrollTop;
  700. }
  701. this.lastScrollTop = curScrollTop;
  702. }
  703. async ignoreScroll(ms = 300) {
  704. this.ignoreScrolling = true;
  705. await utils.sleep(ms);
  706. await this.$nextTick();
  707. await this.$nextTick();
  708. await this.$nextTick();
  709. this.ignoreScrolling = false;
  710. }
  711. scrollToTop() {
  712. this.$refs.scroller.scrollTop = 0;
  713. this.lastScrollTop = 0;
  714. }
  715. updatePageCount() {
  716. if (this.list.totalFound < 0)
  717. return;
  718. const prevPageCount = this.pageCount;
  719. this.pageCount = Math.ceil(this.list.totalFound/this.limit);
  720. this.pageCount = (this.pageCount < 1 ? 1 : this.pageCount);
  721. if (this.prevPage && prevPageCount == 1 && this.pageCount > 1 && this.prevPage <= this.pageCount) {
  722. this.search.page = this.prevPage;
  723. }
  724. if (this.search.page > this.pageCount)
  725. this.search.page = 1;
  726. }
  727. listEvent(event) {
  728. switch (event.action) {
  729. case 'ignoreScroll':
  730. this.ignoreScroll();
  731. break;
  732. case 'highlightPageScroller':
  733. this.highlightPageScroller(event.query);
  734. break;
  735. case 'scrollToTop':
  736. this.scrollToTop();
  737. break;
  738. }
  739. }
  740. setSetting(name, newValue) {
  741. this.commit('setSettings', {[name]: _.cloneDeep(newValue)});
  742. }
  743. highlightPageScroller(query) {
  744. const q = _.cloneDeep(query);
  745. delete q.limit;
  746. delete q.offset;
  747. delete q.page;
  748. try {
  749. if (this.search.page < 2 || !this._prevQuery || _.isEqual(this._prevQuery, q))
  750. return;
  751. this.$refs.pageScroller1.highlightScroller();
  752. } finally {
  753. this._prevQuery = q;
  754. }
  755. }
  756. updateSearchFromRouteQuery(to) {
  757. if (this.list.liberamaReady)
  758. this.sendCurrentUrl();
  759. if (this.routeUpdating)
  760. return;
  761. const query = to.query;
  762. this.search = this.search.setDefaults(
  763. Object.assign({}, this.search, {
  764. author: query.author,
  765. series: query.series,
  766. title: query.title,
  767. genre: query.genre,
  768. lang: (typeof(query.lang) == 'string' ? query.lang : this.langDefault),
  769. date: query.date,
  770. librate: query.librate,
  771. page: parseInt(query.page, 10),
  772. limit: parseInt(query.limit, 10) || this.search.limit,
  773. })
  774. );
  775. if (this.search.limit > 1000)
  776. this.search.limit = 1000;
  777. }
  778. updateRouteQueryFromSearch() {
  779. if (!this.ready)
  780. return;
  781. this.routeUpdating = true;
  782. try {
  783. const oldQuery = this.$route.query;
  784. const cloned = _.cloneDeep(this.search);
  785. delete cloned.setDefaults;
  786. const query = _.pickBy(cloned);
  787. if (this.search.lang == this.langDefault) {
  788. delete query.lang;
  789. } else {
  790. query.lang = this.search.lang;
  791. }
  792. const diff = diffUtils.getObjDiff(oldQuery, query);
  793. if (!diffUtils.isEmptyObjDiff(diff)) {
  794. this.$router.replace({path: this.selectedList, query});
  795. }
  796. } finally {
  797. (async() => {
  798. await utils.sleep(100);
  799. this.routeUpdating = false;
  800. })();
  801. }
  802. }
  803. async updateGenreTreeIfNeeded() {
  804. if (this.genreTreeUpdating)
  805. return;
  806. this.genreTreeUpdating = true;
  807. try {
  808. if (this.genreTreeInpxHash !== this.list.inpxHash) {
  809. let result;
  810. if (this.abCacheEnabled) {
  811. const key = `genre-tree-${this.list.inpxHash}`;
  812. const data = await authorBooksStorage.getData(key);
  813. if (data) {
  814. result = JSON.parse(data);
  815. } else {
  816. result = await this.api.getGenreTree();
  817. await authorBooksStorage.setData(key, JSON.stringify(result));
  818. }
  819. } else {
  820. result = await this.api.getGenreTree();
  821. }
  822. this.genreTree = result.genreTree;
  823. this.genreMap = new Map();
  824. for (const section of this.genreTree) {
  825. for (const g of section.value)
  826. this.genreMap.set(g.value, g.name);
  827. }
  828. this.langList = result.langList;
  829. this.genreTreeInpxHash = result.inpxHash;
  830. }
  831. } catch (e) {
  832. this.$root.stdDialog.alert(e.message, 'Ошибка');
  833. } finally {
  834. this.genreTreeUpdating = false;
  835. }
  836. }
  837. updateSearchDate(toLocal) {
  838. if (toLocal) {
  839. let local = this.search.date || '';
  840. if (utils.isManualDate(local) || !local)
  841. this.prevManualDate = local;
  842. if (utils.isManualDate(local))
  843. local = 'manual';
  844. this.searchDate = local;
  845. } else {
  846. if (this.searchDate != 'manual')
  847. this.search.date = this.searchDate || '';
  848. }
  849. }
  850. get formatSearchDate() {
  851. const result = [];
  852. const date = this.search.date;
  853. if (utils.isManualDate(date)) {
  854. const [from, to] = date.split(',')
  855. if (from)
  856. result.push(`<div style="display: inline-block; width: 15px; text-align: right;">с</div> ${utils.sqlDateFormat(from)}`);
  857. if (to)
  858. result.push(`<div style="display: inline-block; width: 15px; text-align: right;">по</div> ${utils.sqlDateFormat(to)}`);
  859. }
  860. return result.join('<br>');
  861. }
  862. dateSelectItemClick(itemValue) {
  863. if (itemValue == 'manual') {
  864. if (!utils.isManualDate(this.search.date)) {
  865. this.search.date = this.prevManualDate;
  866. if (!this.search.date)
  867. this.searchDate = '';
  868. }
  869. this.selectDateDialogVisible = true
  870. }
  871. }
  872. }
  873. export default vueComponent(Search);
  874. //-----------------------------------------------------------------------------
  875. </script>
  876. <style scoped>
  877. .root {
  878. }
  879. .tool-panel {
  880. border-bottom: 1px solid #bbb;
  881. }
  882. .header {
  883. min-height: 30px;
  884. }
  885. .clickable {
  886. color: blue;
  887. cursor: pointer;
  888. }
  889. .clickable2 {
  890. cursor: pointer;
  891. }
  892. .separator {
  893. border-bottom: 2px solid #ddd;
  894. margin: 5px 0 5px 0;
  895. }
  896. </style>