Search.vue 37 KB

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