Search.vue 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137
  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. if (this.downloadFlag)
  481. return;
  482. this.downloadFlag = true;
  483. (async() => {
  484. await utils.sleep(200);
  485. if (this.downloadFlag)
  486. this.loadingMessage2 = 'Подготовка файла...';
  487. })();
  488. try {
  489. const makeValidFilenameOrEmpty = (s) => {
  490. try {
  491. return utils.makeValidFilename(s);
  492. } catch(e) {
  493. return '';
  494. }
  495. };
  496. //имя файла
  497. let downFileName = 'default-name';
  498. const author = book.author.split(',');
  499. const at = [author[0], book.title];
  500. downFileName = makeValidFilenameOrEmpty(at.filter(r => r).join(' - '))
  501. || makeValidFilenameOrEmpty(at[0])
  502. || makeValidFilenameOrEmpty(at[1])
  503. || downFileName;
  504. downFileName = `${downFileName.substring(0, 100)}.${book.ext}`;
  505. const bookPath = `${book.folder}/${book.file}.${book.ext}`;
  506. //подготовка
  507. const response = await this.api.getBookLink({bookPath, downFileName});
  508. const link = response.link;
  509. const href = `${window.location.origin}${link}`;
  510. if (!copy) {
  511. //скачивание
  512. const d = this.$refs.download;
  513. d.href = href;
  514. d.download = downFileName;
  515. d.click();
  516. } else {
  517. //копирование ссылки
  518. if (utils.copyTextToClipboard(href))
  519. this.$root.notify.success('Ссылка успешно скопирована');
  520. else
  521. this.$root.notify.error('Копирование ссылки не удалось');
  522. }
  523. } catch(e) {
  524. this.$root.stdDialog.alert(e.message, 'Ошибка');
  525. } finally {
  526. this.downloadFlag = false;
  527. this.loadingMessage2 = '';
  528. }
  529. }
  530. bookEvent(event) {
  531. switch (event.action) {
  532. case 'titleClick':
  533. this.search.title = `=${event.book.title}`;
  534. break;
  535. case 'download':
  536. this.download(event.book);//no await
  537. break;
  538. case 'copyLink':
  539. this.download(event.book, true);//no await
  540. break;
  541. }
  542. }
  543. isExpanded(item) {
  544. return this.expanded.indexOf(item.author) >= 0;
  545. }
  546. isExpandedSeries(seriesItem) {
  547. return this.expandedSeries.indexOf(seriesItem._key) >= 0;
  548. }
  549. setSetting(name, newValue) {
  550. this.commit('setSettings', {[name]: _.cloneDeep(newValue)});
  551. }
  552. setDefaults() {
  553. this.search = Object.assign({}, this.search, {
  554. author: '',
  555. series: '',
  556. title: '',
  557. genre: '',
  558. lang: this.langDefault,
  559. });
  560. }
  561. async updateQueryFromRoute(to) {
  562. if (this.routeUpdating)
  563. return;
  564. const query = to.query;
  565. this.search = Object.assign({}, this.search, {
  566. author: query.author || '',
  567. series: query.series || '',
  568. title: query.title || '',
  569. genre: query.genre || '',
  570. lang: (query.lang == 'default' ? this.langDefault : query.lang || ''),
  571. page: parseInt(query.page, 10) || 1,
  572. limit: parseInt(query.limit, 10) || 20,
  573. });
  574. if (this.search.limit > 1000)
  575. this.search.limit = 1000;
  576. }
  577. updateRouteQuery() {
  578. this.routeUpdating = true;
  579. try {
  580. const oldQuery = this.$route.query;
  581. const query = _.pickBy(this.search);
  582. if (this.search.lang == this.langDefault)
  583. query.lang = 'default'
  584. const diff = diffUtils.getObjDiff(oldQuery, query);
  585. if (!diffUtils.isEmptyObjDiff(diff)) {
  586. this.$router.replace({query});
  587. }
  588. } finally {
  589. (async() => {
  590. await utils.sleep(100);
  591. this.routeUpdating = false;
  592. })();
  593. }
  594. }
  595. async expandAuthor(item) {
  596. const expanded = _.cloneDeep(this.expanded);
  597. const key = item.author;
  598. if (!this.isExpanded(item)) {
  599. expanded.push(key);
  600. await this.getBooks(item);
  601. if (expanded.length > 100) {
  602. expanded.shift();
  603. }
  604. this.setSetting('expanded', expanded);
  605. this.ignoreScroll();
  606. } else {
  607. const i = expanded.indexOf(key);
  608. if (i >= 0) {
  609. expanded.splice(i, 1);
  610. this.setSetting('expanded', expanded);
  611. }
  612. }
  613. }
  614. expandSeries(seriesItem) {
  615. const expandedSeries = _.cloneDeep(this.expandedSeries);
  616. const key = seriesItem._key;
  617. if (!this.isExpandedSeries(seriesItem)) {
  618. expandedSeries.push(key);
  619. if (expandedSeries.length > 100) {
  620. expandedSeries.shift();
  621. }
  622. this.setSetting('expandedSeries', expandedSeries);
  623. this.ignoreScroll();
  624. } else {
  625. const i = expandedSeries.indexOf(key);
  626. if (i >= 0) {
  627. expandedSeries.splice(i, 1);
  628. this.setSetting('expandedSeries', expandedSeries);
  629. }
  630. }
  631. }
  632. async loadBooks(authorId) {
  633. try {
  634. let result;
  635. if (this.abCacheEnabled) {
  636. const key = `${authorId}-${this.inpxHash}`;
  637. const data = await authorBooksStorage.getData(key);
  638. if (data) {
  639. result = JSON.parse(data);
  640. } else {
  641. result = await this.api.getBookList(authorId);
  642. await authorBooksStorage.setData(key, JSON.stringify(result));
  643. }
  644. } else {
  645. result = await this.api.getBookList(authorId);
  646. }
  647. return JSON.parse(result.books);
  648. } catch (e) {
  649. this.$root.stdDialog.alert(e.message, 'Ошибка');
  650. }
  651. }
  652. filterBooks(loadedBooks) {
  653. const s = this.search;
  654. const emptyFieldValue = '?';
  655. const ruAlphabet = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя';
  656. const enAlphabet = 'abcdefghijklmnopqrstuvwxyz';
  657. const enru = new Set((ruAlphabet + enAlphabet).split(''));
  658. const splitAuthor = (author) => {
  659. if (!author) {
  660. author = emptyFieldValue;
  661. }
  662. const result = author.split(',');
  663. if (result.length > 1)
  664. result.push(author);
  665. return result;
  666. };
  667. const filterBySearch = (bookValue, searchValue) => {
  668. if (!searchValue)
  669. return true;
  670. bookValue = bookValue.toLowerCase();
  671. searchValue = searchValue.toLowerCase();
  672. //особая обработка префиксов
  673. if (searchValue[0] == '=') {
  674. searchValue = searchValue.substring(1);
  675. return bookValue == searchValue;
  676. } else if (searchValue[0] == '*') {
  677. searchValue = searchValue.substring(1);
  678. return bookValue.indexOf(searchValue) >= 0;
  679. } else if (searchValue[0] == '#') {
  680. searchValue = searchValue.substring(1);
  681. return !bookValue || (!enru.has(bookValue[0]) && bookValue.indexOf(searchValue) >= 0);
  682. } else {
  683. return bookValue.indexOf(searchValue) == 0;
  684. }
  685. };
  686. return loadedBooks.filter((book) => {
  687. //author
  688. let authorFound = false;
  689. const authors = splitAuthor(book.author);
  690. for (const a of authors) {
  691. if (filterBySearch(a, s.author)) {
  692. authorFound = true;
  693. break;
  694. }
  695. }
  696. //genre
  697. let genreFound = !s.genre;
  698. if (!genreFound) {
  699. const searchGenres = new Set(s.genre.split(','));
  700. const bookGenres = book.genre.split(',');
  701. for (let g of bookGenres) {
  702. if (!g)
  703. g = emptyFieldValue;
  704. if (searchGenres.has(g)) {
  705. genreFound = true;
  706. break;
  707. }
  708. }
  709. }
  710. //lang
  711. let langFound = !s.lang;
  712. if (!langFound) {
  713. const searchLang = new Set(s.lang.split(','));
  714. langFound = searchLang.has(book.lang || emptyFieldValue);
  715. }
  716. return (this.showDeleted || !book.del)
  717. && authorFound
  718. && filterBySearch(book.series, s.series)
  719. && filterBySearch(book.title, s.title)
  720. && genreFound
  721. && langFound
  722. ;
  723. });
  724. }
  725. async getBooks(item) {
  726. if (item.books) {
  727. if (item.count > maxItemCount) {
  728. item.bookLoading = true;
  729. await utils.sleep(1);//для перерисовки списка
  730. item.bookLoading = false;
  731. }
  732. return;
  733. }
  734. if (!this.getBooksFlag)
  735. this.getBooksFlag = 0;
  736. this.getBooksFlag++;
  737. if (item.count > maxItemCount)
  738. item.bookLoading = true;
  739. try {
  740. if (this.getBooksFlag == 1) {
  741. (async() => {
  742. await utils.sleep(500);
  743. if (this.getBooksFlag > 0)
  744. this.loadingMessage2 = 'Загрузка списка книг...';
  745. })();
  746. }
  747. const loadedBooks = await this.loadBooks(item.key);
  748. const filtered = this.filterBooks(loadedBooks);
  749. const prepareBook = (book) => {
  750. return Object.assign(
  751. {
  752. _key: book.id,
  753. _type: 'book',
  754. },
  755. book
  756. );
  757. };
  758. //объединение по сериям
  759. const books = [];
  760. const seriesIndex = {};
  761. for (const book of filtered) {
  762. if (book.series) {
  763. let index = seriesIndex[book.series];
  764. if (index === undefined) {
  765. index = books.length;
  766. books.push({
  767. _key: `${item.author}-${book.series}`,
  768. _type: 'series',
  769. series: book.series,
  770. books: [],
  771. });
  772. seriesIndex[book.series] = index;
  773. }
  774. books[index].books.push(prepareBook(book));
  775. } else {
  776. books.push(prepareBook(book));
  777. }
  778. }
  779. //сортировка
  780. books.sort((a, b) => {
  781. if (a._type == 'series') {
  782. return (b._type == 'series' ? a._key.localeCompare(b._key) : -1);
  783. } else {
  784. return (b._type == 'book' ? a.title.localeCompare(b.title) : 1);
  785. }
  786. });
  787. //сортировка внутри серий
  788. for (const book of books) {
  789. if (book._type == 'series') {
  790. book.books.sort((a, b) => {
  791. const dserno = (a.serno || Number.MAX_VALUE) - (b.serno || Number.MAX_VALUE);
  792. const dtitle = a.title.localeCompare(b.title);
  793. const dext = a.ext.localeCompare(b.ext);
  794. return (dserno ? dserno : (dtitle ? dtitle : dext));
  795. });
  796. }
  797. }
  798. if (books.length == 1 && books[0]._type == 'series' && !this.isExpandedSeries(books[0])) {
  799. this.expandSeries(books[0]);
  800. }
  801. item.books = books;
  802. await this.$nextTick();
  803. } finally {
  804. item.bookLoading = false;
  805. this.getBooksFlag--;
  806. if (this.getBooksFlag == 0)
  807. this.loadingMessage2 = '';
  808. }
  809. }
  810. async updateGenreTreeIfNeeded() {
  811. try {
  812. if (this.genreTreeInpxHash !== this.inpxHash) {
  813. let result;
  814. if (this.abCacheEnabled) {
  815. const key = `genre-tree-${this.inpxHash}`;
  816. const data = await authorBooksStorage.getData(key);
  817. if (data) {
  818. result = JSON.parse(data);
  819. } else {
  820. result = await this.api.getGenreTree();
  821. await authorBooksStorage.setData(key, JSON.stringify(result));
  822. }
  823. } else {
  824. result = await this.api.getGenreTree();
  825. }
  826. this.genreTree = result.genreTree;
  827. this.langList = result.langList;
  828. this.genreTreeInpxHash = result.inpxHash;
  829. }
  830. } catch (e) {
  831. this.$root.stdDialog.alert(e.message, 'Ошибка');
  832. }
  833. }
  834. async updateTableData() {
  835. let result = [];
  836. const expandedSet = new Set(this.expanded);
  837. const authors = this.searchResult.author;
  838. if (!authors)
  839. return;
  840. let num = 0;
  841. this.hiddenCount = 0;
  842. for (const rec of authors) {
  843. this.cachedAuthors[rec.author] = rec;
  844. const count = (this.showDeleted ? rec.bookCount + rec.bookDelCount : rec.bookCount);
  845. if (!count) {
  846. this.hiddenCount++;
  847. continue;
  848. }
  849. const item = reactive({
  850. key: rec.id,
  851. num,
  852. author: rec.author,
  853. name: rec.author.replace(/,/g, ', '),
  854. count,
  855. book: false,
  856. bookLoading: false,
  857. });
  858. num++;
  859. if (expandedSet.has(item.author)) {
  860. if (authors.length > 1 || item.count > maxItemCount)
  861. this.getBooks(item);//no await
  862. else
  863. await this.getBooks(item);
  864. }
  865. result.push(item);
  866. }
  867. if (result.length == 1 && !this.isExpanded(result[0])) {
  868. this.expandAuthor(result[0]);
  869. }
  870. this.tableData = result;
  871. }
  872. async refresh() {
  873. if (!this.ready)
  874. return;
  875. this.updateRouteQuery();
  876. //оптимизация
  877. if (this.abCacheEnabled && this.search.author && this.search.author[0] == '=') {
  878. const authorSearch = this.search.author.substring(1);
  879. const author = this.cachedAuthors[authorSearch];
  880. if (author) {
  881. const key = `${author.id}-${this.inpxHash}`;
  882. let data = await authorBooksStorage.getData(key);
  883. if (data) {
  884. this.queryFound = 1;
  885. this.totalFound = 1;
  886. this.searchResult = {author: [author]};
  887. await this.updateTableData();
  888. return;
  889. }
  890. }
  891. }
  892. //параметры запроса
  893. const offset = (this.search.page - 1)*this.search.limit;
  894. const newQuery = _.cloneDeep(this.search);
  895. newQuery.offset = offset;
  896. this.queryExecute = newQuery;
  897. if (this.refreshing)
  898. return;
  899. this.refreshing = true;
  900. try {
  901. while (this.queryExecute) {
  902. const query = this.queryExecute;
  903. this.queryExecute = null;
  904. let inSearch = true;
  905. (async() => {
  906. await utils.sleep(500);
  907. if (inSearch)
  908. this.loadingMessage = 'Поиск авторов...';
  909. })();
  910. try {
  911. const result = await this.api.search(query);
  912. this.queryFound = result.author.length;
  913. this.totalFound = result.totalFound;
  914. this.inpxHash = result.inpxHash;
  915. this.searchResult = result;
  916. await utils.sleep(1);
  917. if (!this.queryExecute) {
  918. await this.updateGenreTreeIfNeeded();
  919. await this.updateTableData();
  920. this.scrollToTop();
  921. }
  922. } catch (e) {
  923. this.$root.stdDialog.alert(e.message, 'Ошибка');
  924. } finally {
  925. inSearch = false;
  926. this.loadingMessage = '';
  927. }
  928. }
  929. } finally {
  930. this.refreshing = false;
  931. }
  932. }
  933. }
  934. export default vueComponent(Search);
  935. //-----------------------------------------------------------------------------
  936. </script>
  937. <style scoped>
  938. .root {
  939. }
  940. .tool-panel {
  941. border-bottom: 1px solid black;
  942. }
  943. .header {
  944. min-height: 30px;
  945. }
  946. .clickable {
  947. color: blue;
  948. cursor: pointer;
  949. }
  950. .clickable2 {
  951. cursor: pointer;
  952. }
  953. .odd-author {
  954. background-color: #e8e8e8;
  955. }
  956. .book-row {
  957. margin-left: 70px;
  958. }
  959. </style>