Search.vue 36 KB

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