Search.vue 41 KB

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