Search.vue 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022
  1. <template>
  2. <div class="root column fit" style="position: relative">
  3. <div v-show="loadingMessage" class="fit row justify-center items-center" style="position: absolute; background-color: rgba(0, 0, 0, 0.2); z-index: 2">
  4. <div class="bg-white row justify-center items-center q-px-lg" style="min-width: 180px; height: 50px; border-radius: 10px; box-shadow: 2px 2px 10px #333333">
  5. <q-spinner color="primary" size="2em" />
  6. <div class="q-ml-sm">
  7. {{ loadingMessage }}
  8. </div>
  9. </div>
  10. </div>
  11. <div v-show="loadingMessage2" class="fit row justify-center items-center" style="position: absolute; background-color: rgba(0, 0, 0, 0.2); z-index: 1">
  12. <div class="bg-white row justify-center items-center q-px-lg" style="min-width: 180px; height: 50px; border-radius: 10px; box-shadow: 2px 2px 10px #333333">
  13. <q-spinner color="primary" size="2em" />
  14. <div class="q-ml-sm">
  15. {{ loadingMessage2 }}
  16. </div>
  17. </div>
  18. </div>
  19. <div ref="scroller" class="col fit column no-wrap" style="overflow: auto; position: relative" @scroll="onScroll">
  20. <div ref="toolPanel" class="tool-panel column bg-green-11" style="position: sticky; top: 0; z-index: 10;">
  21. <div class="header q-mx-md q-mb-xs q-mt-sm row items-center">
  22. <div class="row items-center" style="font-size: 150%;">
  23. <div class="q-mr-xs">
  24. Коллекция
  25. </div>
  26. <div class="clickable" @click="showCollectionInfo">
  27. {{ collection }}
  28. </div>
  29. </div>
  30. <DivBtn class="q-mx-md text-white bg-secondary" :size="30" :icon-size="24" :imt="1" icon="la la-cog" round @click="settingsDialogVisible = true">
  31. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
  32. Настройки
  33. </q-tooltip>
  34. </DivBtn>
  35. <div class="col"></div>
  36. <div class="q-px-sm q-py-xs bg-green-12 clickable2" style="border: 1px solid #aaaaaa; border-radius: 6px" @click="openReleasePage">
  37. {{ projectName }}
  38. </div>
  39. </div>
  40. <div class="row q-mx-md q-mb-sm items-center">
  41. <q-input
  42. ref="authorInput" v-model="search.author" :maxlength="5000" :debounce="inputDebounce"
  43. class="bg-white q-mt-xs" style="width: 300px;" label="Автор" stack-label outlined dense clearable
  44. >
  45. <q-tooltip v-if="search.author" :delay="500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
  46. {{ search.author }}
  47. </q-tooltip>
  48. </q-input>
  49. <div class="q-mx-xs" />
  50. <q-input
  51. v-model="search.series" :maxlength="inputMaxLength" :debounce="inputDebounce"
  52. class="bg-white q-mt-xs" style="width: 200px;" label="Серия" stack-label outlined dense clearable
  53. >
  54. <q-tooltip v-if="search.series" :delay="500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
  55. {{ search.series }}
  56. </q-tooltip>
  57. </q-input>
  58. <div class="q-mx-xs" />
  59. <q-input
  60. v-model="search.title" :maxlength="inputMaxLength" :debounce="inputDebounce"
  61. class="bg-white q-mt-xs" style="width: 200px;" label="Название" stack-label outlined dense clearable
  62. >
  63. <q-tooltip v-if="search.title" :delay="500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
  64. {{ search.title }}
  65. </q-tooltip>
  66. </q-input>
  67. <div class="q-mx-xs" />
  68. <q-input
  69. v-model="genreNames" :maxlength="inputMaxLength" :debounce="inputDebounce"
  70. class="bg-white q-mt-xs" input-style="cursor: pointer" style="width: 200px;" label="Жанр" stack-label outlined dense clearable readonly
  71. @click="selectGenre"
  72. >
  73. <q-tooltip v-if="genreNames" :delay="500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
  74. {{ genreNames }}
  75. </q-tooltip>
  76. </q-input>
  77. <div class="q-mx-xs" />
  78. <q-input
  79. v-model="search.lang" :maxlength="inputMaxLength" :debounce="inputDebounce"
  80. class="bg-white q-mt-xs" input-style="cursor: pointer" style="width: 80px;" label="Язык" stack-label outlined dense clearable readonly
  81. @click="selectLang"
  82. >
  83. <q-tooltip v-if="search.lang" :delay="500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
  84. {{ search.lang }}
  85. </q-tooltip>
  86. </q-input>
  87. <div class="q-mx-xs" />
  88. <DivBtn class="text-white q-mt-xs bg-grey-13" :size="30" :icon-size="24" icon="la la-broom" round @click="setDefaults">
  89. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
  90. Сбросить поиск
  91. </q-tooltip>
  92. </DivBtn>
  93. <div class="q-mx-xs" />
  94. <DivBtn class="text-white q-mt-xs bg-grey-13" :size="30" :icon-size="24" icon="la la-question" round @click="showSearchHelp">
  95. <q-tooltip :delay="1500" anchor="bottom middle" content-style="font-size: 80%" max-width="400px">
  96. Подсказка
  97. </q-tooltip>
  98. </DivBtn>
  99. <div class="q-mx-xs" />
  100. <div class="row items-center q-mt-xs">
  101. <div v-show="queryFound > 0">
  102. {{ foundAuthorsMessage }}
  103. </div>
  104. <div v-show="queryFound == 0">
  105. Ничего не найдено
  106. </div>
  107. </div>
  108. </div>
  109. </div>
  110. <div class="row justify-center" style="min-height: 48px">
  111. <PageScroller v-show="pageCount > 1" v-model="search.page" :page-count="pageCount" />
  112. </div>
  113. <!-- Формирование списка ------------------------------------------------------------------------>
  114. <div v-for="item in tableData" :key="item.key" class="column" :class="{'odd-author': item.num % 2}" style="font-size: 120%">
  115. <div class="row items-center q-ml-md q-mr-xs no-wrap">
  116. <div class="row items-center clickable2 q-py-xs no-wrap" @click="expandAuthor(item)">
  117. <div style="min-width: 30px">
  118. <div v-if="!isExpanded(item)">
  119. <q-icon name="la la-plus-square" size="28px" />
  120. </div>
  121. <div v-else>
  122. <q-icon name="la la-minus-square" size="28px" />
  123. </div>
  124. </div>
  125. </div>
  126. <div class="clickable q-ml-xs q-py-sm" style="font-weight: bold" @click="selectAuthor(item.author)">
  127. {{ item.name }}
  128. </div>
  129. <div class="q-ml-sm" style="font-weight: bold; color: #555">
  130. {{ getBookCount(item) }}
  131. </div>
  132. </div>
  133. <div v-if="isExpanded(item) && item.books">
  134. <div v-for="book in item.books" :key="book.key" class="book-row column">
  135. <div v-if="book.type == 'series'" class="column">
  136. <div class="row items-center q-mr-xs no-wrap">
  137. <div class="row items-center clickable2 q-py-xs no-wrap" @click="expandSeries(book)">
  138. <div style="min-width: 30px">
  139. <div v-if="!isExpandedSeries(book)">
  140. <q-icon name="la la-plus-square" size="28px" />
  141. </div>
  142. <div v-else>
  143. <q-icon name="la la-minus-square" size="28px" />
  144. </div>
  145. </div>
  146. </div>
  147. <div class="clickable2 q-ml-xs q-py-sm" style="font-weight: bold" @click="selectSeries(book.series)">
  148. Серия: {{ book.series }}
  149. </div>
  150. </div>
  151. <div v-if="isExpandedSeries(book) && book.books" class="book-row column">
  152. <BookView v-for="subbook in book.books" :key="subbook.key" :book="subbook" @book-event="bookEvent" />
  153. </div>
  154. </div>
  155. <div v-else>
  156. <BookView :book="book" @book-event="bookEvent" />
  157. </div>
  158. </div>
  159. </div>
  160. </div>
  161. <!-- Формирование списка конец ------------------------------------------------------------------>
  162. <div v-show="hiddenCount" class="q-ml-lg q-py-sm clickable2 text-red" style="font-size: 120%" @click="showHiddenHelp">
  163. {{ hiddenResultsMessage }}
  164. </div>
  165. <div class="row justify-center">
  166. <PageScroller v-show="pageCount > 1" v-model="search.page" :page-count="pageCount" />
  167. </div>
  168. </div>
  169. <Dialog v-model="settingsDialogVisible">
  170. <template #header>
  171. <div class="row items-center" style="font-size: 130%">
  172. <q-icon class="q-mr-sm" name="la la-cog" size="28px"></q-icon>
  173. Настройки
  174. </div>
  175. </template>
  176. <div class="q-mx-md column" style="min-width: 300px; font-size: 120%;">
  177. <div class="row items-center q-ml-sm">
  178. <div class="q-mr-sm">
  179. Результатов на странице
  180. </div>
  181. <q-select
  182. v-model="limit" :options="limitOptions" class="bg-white"
  183. dropdown-icon="la la-angle-down la-sm"
  184. outlined dense emit-value map-options
  185. />
  186. </div>
  187. <q-checkbox v-model="showCounts" size="36px" label="Показывать количество" />
  188. <q-checkbox v-model="showDeleted" size="36px" label="Показывать удаленные" />
  189. <q-checkbox v-model="abCacheEnabled" size="36px" label="Кешировать запросы" />
  190. </div>
  191. <template #footer>
  192. <q-btn class="q-px-md q-ml-sm" color="primary" dense no-caps @click="settingsDialogVisible = false">
  193. OK
  194. </q-btn>
  195. </template>
  196. </Dialog>
  197. <SelectGenreDialog v-model="selectGenreDialogVisible" v-model:genre="search.genre" :genre-tree="genreTree" />
  198. <SelectLangDialog v-model="selectLangDialogVisible" v-model:lang="search.lang" :lang-list="langList" :lang-default="langDefault" />
  199. </div>
  200. </template>
  201. <script>
  202. //-----------------------------------------------------------------------------
  203. import vueComponent from '../vueComponent.js';
  204. import { reactive } from 'vue';
  205. import PageScroller from './PageScroller/PageScroller.vue';
  206. import SelectGenreDialog from './SelectGenreDialog/SelectGenreDialog.vue';
  207. import SelectLangDialog from './SelectLangDialog/SelectLangDialog.vue';
  208. import BookView from './BookView/BookView.vue';
  209. import authorBooksStorage from './authorBooksStorage';
  210. import DivBtn from '../share/DivBtn.vue';
  211. import Dialog from '../share/Dialog.vue';
  212. import * as utils from '../../share/utils';
  213. import diffUtils from '../../share/diffUtils';
  214. import _ from 'lodash';
  215. const componentOptions = {
  216. components: {
  217. PageScroller,
  218. SelectGenreDialog,
  219. SelectLangDialog,
  220. BookView,
  221. Dialog,
  222. DivBtn
  223. },
  224. watch: {
  225. config() {
  226. this.makeTitle();
  227. },
  228. settings() {
  229. this.loadSettings();
  230. },
  231. search: {
  232. handler(newValue) {
  233. this.limit = newValue.limit;
  234. this.refresh();
  235. },
  236. deep: true,
  237. },
  238. limit(newValue) {
  239. this.setSetting('limit', newValue);
  240. this.updatePageCount();
  241. },
  242. showCounts(newValue) {
  243. this.setSetting('showCounts', newValue);
  244. },
  245. showDeleted(newValue) {
  246. this.setSetting('showDeleted', newValue);
  247. this.updateTableData();
  248. },
  249. abCacheEnabled(newValue) {
  250. this.setSetting('abCacheEnabled', newValue);
  251. },
  252. totalFound() {
  253. this.updatePageCount();
  254. },
  255. $route(to) {
  256. this.updateQueryFromRoute(to);
  257. },
  258. langDefault() {
  259. this.updateQueryFromRoute(this.$route);
  260. },
  261. },
  262. };
  263. class Search {
  264. _options = componentOptions;
  265. collection = '';
  266. projectName = '';
  267. loadingMessage = '';
  268. loadingMessage2 = '';
  269. settingsDialogVisible = false;
  270. selectGenreDialogVisible = false;
  271. selectLangDialogVisible = false;
  272. pageCount = 1;
  273. //input field consts
  274. inputMaxLength = 1000;
  275. inputDebounce = 200;
  276. //search fields
  277. search = {
  278. author: '',
  279. series: '',
  280. title: '',
  281. genre: '',
  282. lang: '',
  283. page: 1,
  284. limit: 50,
  285. };
  286. //settings
  287. expanded = [];
  288. expandedSeries = [];
  289. showCounts = true;
  290. showDeleted = false;
  291. abCacheEnabled = true;
  292. langDefault = '';
  293. limit = 50;
  294. //stuff
  295. refreshing = false;
  296. queryFound = -1;
  297. totalFound = 0;
  298. bookRowsOnPage = 100;
  299. inpxHash = '';
  300. genreTree = [];
  301. langList = [];
  302. genreTreeInpxHash = '';
  303. cachedAuthors = {};
  304. hiddenCount = 0;
  305. limitOptions = [
  306. {label: '10', value: 10},
  307. {label: '20', value: 20},
  308. {label: '50', value: 50},
  309. {label: '100', value: 100},
  310. {label: '200', value: 200},
  311. {label: '500', value: 500},
  312. {label: '1000', value: 1000},
  313. ];
  314. searchResult = {};
  315. tableData = [];
  316. created() {
  317. this.commit = this.$store.commit;
  318. this.loadSettings();
  319. }
  320. mounted() {
  321. (async() => {
  322. await authorBooksStorage.init();
  323. this.api = this.$root.api;
  324. if (!this.$root.isMobileDevice)
  325. this.$refs.authorInput.focus();
  326. this.setDefaults();
  327. this.updateQueryFromRoute(this.$route);
  328. //чтоб не вызывался лишний refresh
  329. await utils.sleep(100);
  330. this.ready = true;
  331. this.refresh();//no await
  332. })();
  333. }
  334. loadSettings() {
  335. const settings = this.settings;
  336. this.search.limit = settings.limit;
  337. this.expanded = _.cloneDeep(settings.expanded);
  338. this.expandedSeries = _.cloneDeep(settings.expandedSeries);
  339. this.showCounts = settings.showCounts;
  340. this.showDeleted = settings.showDeleted;
  341. this.abCacheEnabled = settings.abCacheEnabled;
  342. this.langDefault = settings.langDefault;
  343. }
  344. get config() {
  345. return this.$store.state.config;
  346. }
  347. get settings() {
  348. return this.$store.state.settings;
  349. }
  350. get genreNames() {
  351. let result = [];
  352. const genre = new Set(this.search.genre.split(','));
  353. for (const section of this.genreTree) {
  354. for (const g of section.value)
  355. if (genre.has(g.value))
  356. result.push(g.name);
  357. }
  358. return result.join(', ');
  359. }
  360. openReleasePage() {
  361. window.open('https://github.com/bookpauk/inpx-web', '_blank');
  362. }
  363. makeTitle() {
  364. const collection = this.config.dbConfig.inpxInfo.collection.split('\n');
  365. this.collection = collection[0].trim();
  366. this.projectName = `${this.config.name} v${this.config.version}`;
  367. this.$root.setAppTitle(`Коллекция ${this.collection}`);
  368. }
  369. showSearchHelp() {
  370. this.$root.stdDialog.alert(`
  371. <p>
  372. Здесь должна быть подсказка<br>
  373. </p>
  374. `, 'Подсказка', {iconName: 'la la-info-circle'});
  375. }
  376. showHiddenHelp() {
  377. this.$root.stdDialog.alert(`
  378. Книги этих авторов помечены как удаленные. Для того, чтобы их увидеть, необходимо установить опцию "Показывать удаленные" в настройках.
  379. `, 'Пояснение', {iconName: 'la la-info-circle'});
  380. }
  381. showCollectionInfo() {
  382. this.$root.stdDialog.alert(`
  383. <p>
  384. Здесь должна быть информация о коллекции<br>
  385. </p>
  386. `, 'Статистика по коллекции', {iconName: 'la la-info-circle'});
  387. }
  388. selectGenre() {
  389. this.selectGenreDialogVisible = true;
  390. }
  391. selectLang() {
  392. this.selectLangDialogVisible = true;
  393. }
  394. onScroll() {
  395. if (this.ignoreScrolling)
  396. return;
  397. const curScrollTop = this.$refs.scroller.scrollTop;
  398. if (!this.lastScrollTop)
  399. this.lastScrollTop = 0;
  400. if (!this.lastScrollTop2)
  401. this.lastScrollTop2 = 0;
  402. if (curScrollTop - this.lastScrollTop > 0) {
  403. this.$refs.toolPanel.style.position = 'relative';
  404. this.$refs.toolPanel.style.top = `${this.lastScrollTop2}px`;
  405. } else if (curScrollTop - this.lastScrollTop <= 0) {
  406. this.$refs.toolPanel.style.position = 'sticky';
  407. this.$refs.toolPanel.style.top = 0;
  408. this.lastScrollTop2 = curScrollTop;
  409. }
  410. this.lastScrollTop = curScrollTop;
  411. }
  412. async ignoreScroll(ms = 50) {
  413. this.ignoreScrolling = true;
  414. await utils.sleep(ms);
  415. this.ignoreScrolling = false;
  416. }
  417. scrollToTop() {
  418. this.$refs.scroller.scrollTop = 0;
  419. this.lastScrollTop = 0;
  420. }
  421. get foundAuthorsMessage() {
  422. return `Найден${utils.wordEnding(this.totalFound, 2)} ${this.totalFound} автор${utils.wordEnding(this.totalFound)}`;
  423. }
  424. get hiddenResultsMessage() {
  425. return `+${this.hiddenCount} результат${utils.wordEnding(this.hiddenCount)} скрыты`;
  426. }
  427. updatePageCount() {
  428. const prevPageCount = this.pageCount;
  429. this.pageCount = Math.ceil(this.totalFound/this.limit);
  430. this.pageCount = (this.pageCount < 1 ? 1 : this.pageCount);
  431. if (this.prevPage && prevPageCount == 1 && this.pageCount > 1 && this.prevPage <= this.pageCount) {
  432. this.search.page = this.prevPage;
  433. }
  434. if (this.search.page > this.pageCount) {
  435. this.prevPage = this.search.page;
  436. this.search.page = 1;
  437. }
  438. }
  439. selectAuthor(author) {
  440. this.search.author = `=${author}`;
  441. this.scrollToTop();
  442. }
  443. selectSeries(series) {
  444. this.search.series = `=${series}`;
  445. }
  446. bookEvent(event) {
  447. switch (event.action) {
  448. case 'titleClick':
  449. this.search.title = `=${event.book.title}`;
  450. break;
  451. }
  452. }
  453. isExpanded(item) {
  454. return this.expanded.indexOf(item.author) >= 0;
  455. }
  456. isExpandedSeries(seriesItem) {
  457. return this.expandedSeries.indexOf(seriesItem.key) >= 0;
  458. }
  459. setSetting(name, newValue) {
  460. this.commit('setSettings', {[name]: _.cloneDeep(newValue)});
  461. }
  462. expandAuthor(item) {
  463. const expanded = _.cloneDeep(this.expanded);
  464. const key = item.author;
  465. if (!this.isExpanded(item)) {
  466. expanded.push(key);
  467. this.getBooks(item);
  468. if (expanded.length > 100) {
  469. expanded.shift();
  470. }
  471. this.setSetting('expanded', expanded);
  472. this.ignoreScroll();
  473. } else {
  474. const i = expanded.indexOf(key);
  475. if (i >= 0) {
  476. expanded.splice(i, 1);
  477. this.setSetting('expanded', expanded);
  478. }
  479. }
  480. }
  481. expandSeries(seriesItem) {
  482. const expandedSeries = _.cloneDeep(this.expandedSeries);
  483. const key = seriesItem.key;
  484. if (!this.isExpandedSeries(seriesItem)) {
  485. expandedSeries.push(key);
  486. if (expandedSeries.length > 100) {
  487. expandedSeries.shift();
  488. }
  489. this.setSetting('expandedSeries', expandedSeries);
  490. this.ignoreScroll();
  491. } else {
  492. const i = expandedSeries.indexOf(key);
  493. if (i >= 0) {
  494. expandedSeries.splice(i, 1);
  495. this.setSetting('expandedSeries', expandedSeries);
  496. }
  497. }
  498. }
  499. getBookCount(item) {
  500. let result = '';
  501. if (!this.showCounts || item.count === undefined)
  502. return result;
  503. if (item.books)
  504. result = `${item.books.length}/${item.count}`;
  505. else
  506. result = `#/${item.count}`;
  507. return `(${result})`;
  508. }
  509. async loadBooks(authorId) {
  510. try {
  511. let result;
  512. if (this.abCacheEnabled) {
  513. const key = `${authorId}-${this.inpxHash}`;
  514. const data = await authorBooksStorage.getData(key);
  515. if (data) {
  516. result = JSON.parse(data);
  517. } else {
  518. result = await this.api.getBookList(authorId);
  519. await authorBooksStorage.setData(key, JSON.stringify(result));
  520. }
  521. } else {
  522. result = await this.api.getBookList(authorId);
  523. }
  524. return JSON.parse(result.books);
  525. } catch (e) {
  526. this.$root.stdDialog.alert(e.message, 'Ошибка');
  527. }
  528. }
  529. filterBooks(loadedBooks) {
  530. const s = this.search;
  531. const emptyFieldValue = '?';
  532. const ruAlphabet = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя';
  533. const enAlphabet = 'abcdefghijklmnopqrstuvwxyz';
  534. const enru = new Set((ruAlphabet + enAlphabet).split(''));
  535. const splitAuthor = (author) => {
  536. if (!author) {
  537. author = emptyFieldValue;
  538. }
  539. const result = author.split(',');
  540. if (result.length > 1)
  541. result.push(author);
  542. return result;
  543. };
  544. const filterBySearch = (bookValue, searchValue) => {
  545. if (!searchValue)
  546. return true;
  547. bookValue = bookValue.toLowerCase();
  548. searchValue = searchValue.toLowerCase();
  549. //особая обработка префиксов
  550. if (searchValue[0] == '=') {
  551. searchValue = searchValue.substring(1);
  552. return bookValue == searchValue;
  553. } else if (searchValue[0] == '*') {
  554. searchValue = searchValue.substring(1);
  555. return bookValue.indexOf(searchValue) >= 0;
  556. } else if (searchValue[0] == '#') {
  557. searchValue = searchValue.substring(1);
  558. return !bookValue || (!enru.has(bookValue[0]) && bookValue.indexOf(searchValue) >= 0);
  559. } else {
  560. return bookValue.indexOf(searchValue) == 0;
  561. }
  562. };
  563. return loadedBooks.filter((book) => {
  564. //author
  565. let authorFound = false;
  566. const authors = splitAuthor(book.author);
  567. for (const a of authors) {
  568. if (filterBySearch(a, s.author)) {
  569. authorFound = true;
  570. break;
  571. }
  572. }
  573. //genre
  574. let genreFound = !s.genre;
  575. if (!genreFound) {
  576. const searchGenres = new Set(s.genre.split(','));
  577. const bookGenres = book.genre.split(',');
  578. for (let g of bookGenres) {
  579. if (!g)
  580. g = emptyFieldValue;
  581. if (searchGenres.has(g)) {
  582. genreFound = true;
  583. break;
  584. }
  585. }
  586. }
  587. //lang
  588. let langFound = !s.lang;
  589. if (!langFound) {
  590. const searchLang = new Set(s.lang.split(','));
  591. langFound = searchLang.has(book.lang || emptyFieldValue);
  592. }
  593. return (this.showDeleted || !book.del)
  594. && authorFound
  595. && filterBySearch(book.series, s.series)
  596. && filterBySearch(book.title, s.title)
  597. && genreFound
  598. && langFound
  599. ;
  600. });
  601. }
  602. async getBooks(item) {
  603. if (item.books)
  604. return;
  605. if (!this.getBooksFlag)
  606. this.getBooksFlag = 0;
  607. this.getBooksFlag++;
  608. try {
  609. if (this.getBooksFlag == 1) {
  610. (async() => {
  611. await utils.sleep(500);
  612. if (this.getBooksFlag > 0)
  613. this.loadingMessage2 = 'Загрузка списка книг...';
  614. })();
  615. }
  616. const loadedBooks = await this.loadBooks(item.key);
  617. const filtered = this.filterBooks(loadedBooks);
  618. const prepareBook = (book) => {
  619. return {
  620. key: book.id,
  621. type: 'book',
  622. title: book.title,
  623. series: book.series,
  624. }
  625. };
  626. //объединение по сериям
  627. const books = [];
  628. const seriesIndex = {};
  629. for (const book of filtered) {
  630. if (book.series) {
  631. let index = seriesIndex[book.series];
  632. if (index === undefined) {
  633. index = books.length;
  634. books.push({
  635. key: `${item.author}-${book.series}`,
  636. type: 'series',
  637. series: book.series,
  638. books: [],
  639. });
  640. seriesIndex[book.series] = index;
  641. }
  642. books[index].books.push(prepareBook(book));
  643. } else {
  644. books.push(prepareBook(book));
  645. }
  646. }
  647. //сортировка
  648. books.sort((a, b) => {
  649. if (a.type == 'series') {
  650. if (b.type == 'series')
  651. return a.key.localeCompare(b.key);
  652. else
  653. return -1;
  654. } else {
  655. if (b.type == 'book')
  656. return a.title.localeCompare(b.title);
  657. else
  658. return 1;
  659. }
  660. });
  661. //сортировка внутри серий
  662. item.books = books;
  663. } finally {
  664. this.getBooksFlag--;
  665. if (this.getBooksFlag == 0)
  666. this.loadingMessage2 = '';
  667. }
  668. }
  669. async updateGenreTreeIfNeeded() {
  670. try {
  671. if (this.genreTreeInpxHash !== this.inpxHash) {
  672. let result;
  673. if (this.abCacheEnabled) {
  674. const key = `genre-tree-${this.inpxHash}`;
  675. const data = await authorBooksStorage.getData(key);
  676. if (data) {
  677. result = JSON.parse(data);
  678. } else {
  679. result = await this.api.getGenreTree();
  680. await authorBooksStorage.setData(key, JSON.stringify(result));
  681. }
  682. } else {
  683. result = await this.api.getGenreTree();
  684. }
  685. this.genreTree = result.genreTree;
  686. this.langList = result.langList;
  687. this.genreTreeInpxHash = result.inpxHash;
  688. }
  689. } catch (e) {
  690. this.$root.stdDialog.alert(e.message, 'Ошибка');
  691. }
  692. }
  693. async updateTableData() {
  694. let result = [];
  695. const expandedSet = new Set(this.expanded);
  696. const authors = this.searchResult.author;
  697. if (!authors)
  698. return;
  699. let num = 0;
  700. this.hiddenCount = 0;
  701. for (const rec of authors) {
  702. this.cachedAuthors[rec.author] = rec;
  703. const count = (this.showDeleted ? rec.bookCount + rec.bookDelCount : rec.bookCount);
  704. if (!count) {
  705. this.hiddenCount++;
  706. continue;
  707. }
  708. const item = reactive({
  709. key: rec.id,
  710. num,
  711. author: rec.author,
  712. name: rec.author.replace(/,/g, ', '),
  713. count,
  714. book: false,
  715. });
  716. num++;
  717. if (expandedSet.has(item.author)) {
  718. if (authors.length > 1)
  719. this.getBooks(item);//no await
  720. else
  721. await this.getBooks(item);
  722. }
  723. result.push(item);
  724. }
  725. if (result.length == 1 && !this.isExpanded(result[0])) {
  726. this.expandAuthor(result[0]);
  727. }
  728. this.tableData = result;
  729. }
  730. setDefaults() {
  731. this.search = Object.assign({}, this.search, {
  732. author: '',
  733. series: '',
  734. title: '',
  735. genre: '',
  736. lang: this.langDefault,
  737. });
  738. }
  739. async updateQueryFromRoute(to) {
  740. if (this.routeUpdating)
  741. return;
  742. const query = to.query;
  743. this.search = Object.assign({}, this.search, {
  744. author: query.author || '',
  745. series: query.series || '',
  746. title: query.title || '',
  747. genre: query.genre || '',
  748. lang: (query.lang == 'default' ? this.langDefault : query.lang || ''),
  749. page: parseInt(query.page, 10) || 1,
  750. });
  751. }
  752. updateRouteQuery() {
  753. this.routeUpdating = true;
  754. try {
  755. const oldQuery = this.$route.query;
  756. const query = _.pickBy(this.search);
  757. delete query.limit;
  758. if (this.search.lang == this.langDefault)
  759. query.lang = 'default'
  760. const diff = diffUtils.getObjDiff(oldQuery, query);
  761. if (!diffUtils.isEmptyObjDiff(diff)) {
  762. this.$router.replace({query});
  763. }
  764. } finally {
  765. (async() => {
  766. await utils.sleep(100);
  767. this.routeUpdating = false;
  768. })();
  769. }
  770. }
  771. async refresh() {
  772. if (!this.ready)
  773. return;
  774. this.updateRouteQuery();
  775. //оптимизация
  776. if (this.abCacheEnabled && this.search.author && this.search.author[0] == '=') {
  777. const authorSearch = this.search.author.substring(1);
  778. const author = this.cachedAuthors[authorSearch];
  779. if (author) {
  780. const key = `${author.id}-${this.inpxHash}`;
  781. let data = await authorBooksStorage.getData(key);
  782. if (data) {
  783. this.queryFound = 1;
  784. this.totalFound = 1;
  785. this.searchResult = {author: [author]};
  786. await this.updateTableData();
  787. return;
  788. }
  789. }
  790. }
  791. //параметры запроса
  792. const offset = (this.search.page - 1)*this.limit;
  793. const newQuery = _.cloneDeep(this.search);
  794. newQuery.limit = this.limit;
  795. newQuery.offset = offset;
  796. this.queryExecute = newQuery;
  797. if (this.refreshing)
  798. return;
  799. this.refreshing = true;
  800. try {
  801. while (this.queryExecute) {
  802. const query = this.queryExecute;
  803. this.queryExecute = null;
  804. let inSearch = true;
  805. (async() => {
  806. await utils.sleep(500);
  807. if (inSearch)
  808. this.loadingMessage = 'Поиск авторов...';
  809. })();
  810. try {
  811. const result = await this.api.search(query);
  812. this.queryFound = result.author.length;
  813. this.totalFound = result.totalFound;
  814. this.inpxHash = result.inpxHash;
  815. this.searchResult = result;
  816. await utils.sleep(1);
  817. if (!this.queryExecute) {
  818. await this.updateGenreTreeIfNeeded();
  819. await this.updateTableData();
  820. this.scrollToTop();
  821. }
  822. } catch (e) {
  823. this.$root.stdDialog.alert(e.message, 'Ошибка');
  824. } finally {
  825. inSearch = false;
  826. this.loadingMessage = '';
  827. }
  828. }
  829. } finally {
  830. this.refreshing = false;
  831. }
  832. }
  833. }
  834. export default vueComponent(Search);
  835. //-----------------------------------------------------------------------------
  836. </script>
  837. <style scoped>
  838. .root {
  839. }
  840. .tool-panel {
  841. border-bottom: 1px solid black;
  842. }
  843. .header {
  844. min-height: 30px;
  845. }
  846. .clickable {
  847. color: blue;
  848. cursor: pointer;
  849. }
  850. .clickable2 {
  851. cursor: pointer;
  852. }
  853. .odd-author {
  854. background-color: #e8e8e8;
  855. }
  856. .book-row {
  857. margin-left: 70px;
  858. }
  859. </style>