Search.vue 55 KB

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