Search.vue 39 KB

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