Search.vue 38 KB

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