Search.vue 48 KB

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