Search.vue 30 KB

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