Search.vue 58 KB

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