Search.vue 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545
  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" 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. `;
  613. info += `
  614. <div><hr/>
  615. <b>collection.info:</b>
  616. <pre>${inpxInfo.collection}</pre>
  617. </div>
  618. `;
  619. this.$root.stdDialog.alert(info, 'Статистика по коллекции', {iconName: 'la la-info-circle'});
  620. }
  621. newSearch() {
  622. window.location = window.location.origin;
  623. }
  624. async hideTooltip() {
  625. //Firefox bugfix: при всплывающем диалоге скрываем подсказку
  626. this.showTooltips = false;
  627. await utils.sleep(1000);
  628. this.showTooltips = true;
  629. }
  630. selectGenre() {
  631. this.hideTooltip();
  632. this.selectGenreDialogVisible = true;
  633. }
  634. selectLang() {
  635. this.hideTooltip();
  636. this.selectLangDialogVisible = true;
  637. }
  638. onScroll() {
  639. if (this.ignoreScrolling)
  640. return;
  641. const curScrollTop = this.$refs.scroller.scrollTop;
  642. if (!this.lastScrollTop)
  643. this.lastScrollTop = 0;
  644. if (!this.lastScrollTop2)
  645. this.lastScrollTop2 = 0;
  646. if (curScrollTop - this.lastScrollTop > 0) {
  647. this.$refs.toolPanel.style.position = 'relative';
  648. this.$refs.toolPanel.style.top = `${this.lastScrollTop2}px`;
  649. } else {
  650. this.$refs.toolPanel.style.position = 'sticky';
  651. this.$refs.toolPanel.style.top = 0;
  652. this.lastScrollTop2 = curScrollTop;
  653. }
  654. this.lastScrollTop = curScrollTop;
  655. }
  656. async ignoreScroll(ms = 50) {
  657. this.ignoreScrolling = true;
  658. await utils.sleep(ms);
  659. this.ignoreScrolling = false;
  660. }
  661. scrollToTop() {
  662. this.$refs.scroller.scrollTop = 0;
  663. this.lastScrollTop = 0;
  664. }
  665. get foundAuthorsMessage() {
  666. return `Найден${utils.wordEnding(this.totalFound, 2)} ${this.totalFound} автор${utils.wordEnding(this.totalFound)}`;
  667. }
  668. get hiddenResultsMessage() {
  669. return `+${this.hiddenCount} результат${utils.wordEnding(this.hiddenCount)} скрыт${utils.wordEnding(this.hiddenCount, 2)}`;
  670. }
  671. updatePageCount() {
  672. const prevPageCount = this.pageCount;
  673. this.pageCount = Math.ceil(this.totalFound/this.limit);
  674. this.pageCount = (this.pageCount < 1 ? 1 : this.pageCount);
  675. if (this.prevPage && prevPageCount == 1 && this.pageCount > 1 && this.prevPage <= this.pageCount) {
  676. this.search.page = this.prevPage;
  677. }
  678. if (this.search.page > this.pageCount)
  679. this.search.page = 1;
  680. }
  681. getBookCount(item) {
  682. let result = '';
  683. if (!this.showCounts || item.count === undefined)
  684. return result;
  685. if (item.booksLoaded) {
  686. let count = 0;
  687. for (const book of item.booksLoaded) {
  688. if (book.type == 'series')
  689. count += book.seriesBooks.length;
  690. else
  691. count++;
  692. }
  693. result = `${count}/${item.count}`;
  694. } else
  695. result = `#/${item.count}`;
  696. return `(${result})`;
  697. }
  698. selectAuthor(author) {
  699. this.search.author = `=${author}`;
  700. this.scrollToTop();
  701. }
  702. selectSeries(series) {
  703. this.search.series = `=${series}`;
  704. }
  705. selectTitle(title) {
  706. this.search.title = `=${title}`;
  707. }
  708. async download(book, action) {
  709. if (this.downloadFlag)
  710. return;
  711. this.downloadFlag = true;
  712. (async() => {
  713. await utils.sleep(200);
  714. if (this.downloadFlag)
  715. this.loadingMessage2 = 'Подготовка файла...';
  716. })();
  717. try {
  718. const makeValidFilenameOrEmpty = (s) => {
  719. try {
  720. return utils.makeValidFilename(s);
  721. } catch(e) {
  722. return '';
  723. }
  724. };
  725. //имя файла
  726. let downFileName = 'default-name';
  727. const author = book.author.split(',');
  728. const at = [author[0], book.title];
  729. downFileName = makeValidFilenameOrEmpty(at.filter(r => r).join(' - '))
  730. || makeValidFilenameOrEmpty(at[0])
  731. || makeValidFilenameOrEmpty(at[1])
  732. || downFileName;
  733. downFileName = downFileName.substring(0, 100);
  734. const ext = `.${book.ext}`;
  735. if (downFileName.substring(downFileName.length - ext.length) != ext)
  736. downFileName += ext;
  737. const bookPath = `${book.folder}/${book.file}${ext}`;
  738. //подготовка
  739. const response = await this.api.getBookLink({bookPath, downFileName});
  740. const link = response.link;
  741. const href = `${window.location.origin}${link}`;
  742. if (action == 'download') {
  743. //скачивание
  744. const d = this.$refs.download;
  745. d.href = href;
  746. d.download = downFileName;
  747. d.click();
  748. } else if (action == 'copyLink') {
  749. //копирование ссылки
  750. if (await utils.copyTextToClipboard(href))
  751. this.$root.notify.success('Ссылка успешно скопирована');
  752. else
  753. this.$root.stdDialog.alert(
  754. `Копирование ссылки не удалось. Пожалуйста, попробуйте еще раз.
  755. <br><br>
  756. <b>Пояснение</b>: вероятно, браузер запретил копирование, т.к. прошло<br>
  757. слишком много времени с момента нажатия на кнопку (инициация<br>
  758. пользовательского события). Сейчас ссылка уже закеширована,<br>
  759. поэтому повторная попытка должна быть успешной.`, 'Ошибка');
  760. } else if (action == 'readBook') {
  761. //читать
  762. if (this.liberamaReady) {
  763. this.sendMessage({type: 'submitUrl', data: href});
  764. } else {
  765. const url = this.config.bookReadLink.replace('${DOWNLOAD_LINK}', href);
  766. window.open(url, '_blank');
  767. }
  768. }
  769. } catch(e) {
  770. this.$root.stdDialog.alert(e.message, 'Ошибка');
  771. } finally {
  772. this.downloadFlag = false;
  773. this.loadingMessage2 = '';
  774. }
  775. }
  776. bookEvent(event) {
  777. switch (event.action) {
  778. case 'authorClick':
  779. this.selectAuthor(event.book.author);
  780. break;
  781. case 'titleClick':
  782. this.selectTitle(event.book.title);
  783. break;
  784. case 'download':
  785. case 'copyLink':
  786. case 'readBook':
  787. this.download(event.book, event.action);//no await
  788. break;
  789. }
  790. }
  791. isExpanded(item) {
  792. return this.expanded.indexOf(item.author) >= 0;
  793. }
  794. isExpandedSeries(seriesItem) {
  795. return this.expandedSeries.indexOf(seriesItem.key) >= 0;
  796. }
  797. isFoundSeriesBook(seriesItem, seriesBook) {
  798. if (!seriesItem.booksSet) {
  799. seriesItem.booksSet = new Set(seriesItem.seriesBooks.map(b => b.id));
  800. }
  801. return seriesItem.booksSet.has(seriesBook.id);
  802. }
  803. setSetting(name, newValue) {
  804. this.commit('setSettings', {[name]: _.cloneDeep(newValue)});
  805. }
  806. setDefaults() {
  807. this.search = Object.assign({}, this.search, {
  808. author: '',
  809. series: '',
  810. title: '',
  811. genre: '',
  812. lang: this.langDefault,
  813. });
  814. }
  815. highlightPageScroller(query) {
  816. const q = _.cloneDeep(query);
  817. delete q.limit;
  818. delete q.offset;
  819. delete q.page;
  820. try {
  821. if (this.search.page < 2 || !this._prevQuery || _.isEqual(this._prevQuery, q))
  822. return;
  823. this.$refs.pageScroller1.highlightScroller();
  824. } finally {
  825. this._prevQuery = q;
  826. }
  827. }
  828. async updateSearchFromRouteQuery(to) {
  829. if (this.liberamaReady)
  830. this.sendCurrentUrl();
  831. if (this.routeUpdating)
  832. return;
  833. const query = to.query;
  834. this.search = Object.assign({}, this.search, {
  835. author: query.author || '',
  836. series: query.series || '',
  837. title: query.title || '',
  838. genre: query.genre || '',
  839. lang: (typeof(query.lang) == 'string' ? query.lang : this.langDefault),
  840. page: parseInt(query.page, 10) || 1,
  841. limit: parseInt(query.limit, 10) || this.search.limit,
  842. });
  843. if (this.search.limit > 1000)
  844. this.search.limit = 1000;
  845. }
  846. updateRouteQueryFromSearch() {
  847. this.routeUpdating = true;
  848. try {
  849. const oldQuery = this.$route.query;
  850. const query = _.pickBy(this.search);
  851. if (this.search.lang == this.langDefault) {
  852. delete query.lang;
  853. } else {
  854. query.lang = this.search.lang;
  855. }
  856. const diff = diffUtils.getObjDiff(oldQuery, query);
  857. if (!diffUtils.isEmptyObjDiff(diff)) {
  858. this.$router.replace({query});
  859. }
  860. } finally {
  861. (async() => {
  862. await utils.sleep(100);
  863. this.routeUpdating = false;
  864. })();
  865. }
  866. }
  867. async expandAuthor(item) {
  868. const expanded = _.cloneDeep(this.expanded);
  869. const key = item.author;
  870. if (!this.isExpanded(item)) {
  871. expanded.push(key);
  872. await this.getBooks(item);
  873. if (expanded.length > 10) {
  874. expanded.shift();
  875. }
  876. this.setSetting('expanded', expanded);
  877. this.ignoreScroll();
  878. } else {
  879. const i = expanded.indexOf(key);
  880. if (i >= 0) {
  881. expanded.splice(i, 1);
  882. this.setSetting('expanded', expanded);
  883. }
  884. }
  885. }
  886. expandSeries(seriesItem) {
  887. const expandedSeries = _.cloneDeep(this.expandedSeries);
  888. const key = seriesItem.key;
  889. if (!this.isExpandedSeries(seriesItem)) {
  890. expandedSeries.push(key);
  891. if (expandedSeries.length > 100) {
  892. expandedSeries.shift();
  893. }
  894. this.getSeriesBooks(seriesItem); //no await
  895. this.setSetting('expandedSeries', expandedSeries);
  896. this.ignoreScroll();
  897. } else {
  898. const i = expandedSeries.indexOf(key);
  899. if (i >= 0) {
  900. expandedSeries.splice(i, 1);
  901. this.setSetting('expandedSeries', expandedSeries);
  902. }
  903. }
  904. }
  905. async loadBooks(authorId) {
  906. try {
  907. let result;
  908. if (this.abCacheEnabled) {
  909. const key = `${authorId}-${this.inpxHash}`;
  910. const data = await authorBooksStorage.getData(key);
  911. if (data) {
  912. result = JSON.parse(data);
  913. } else {
  914. result = await this.api.getBookList(authorId);
  915. await authorBooksStorage.setData(key, JSON.stringify(result));
  916. }
  917. } else {
  918. result = await this.api.getBookList(authorId);
  919. }
  920. return (result.books ? JSON.parse(result.books) : []);
  921. } catch (e) {
  922. this.$root.stdDialog.alert(e.message, 'Ошибка');
  923. }
  924. }
  925. async loadSeriesBooks(series) {
  926. try {
  927. let result;
  928. if (this.abCacheEnabled) {
  929. const key = `series-${series}-${this.inpxHash}`;
  930. const data = await authorBooksStorage.getData(key);
  931. if (data) {
  932. result = JSON.parse(data);
  933. } else {
  934. result = await this.api.getSeriesBookList(series);
  935. await authorBooksStorage.setData(key, JSON.stringify(result));
  936. }
  937. } else {
  938. result = await this.api.getSeriesBookList(series);
  939. }
  940. return (result.books ? JSON.parse(result.books) : []);
  941. } catch (e) {
  942. this.$root.stdDialog.alert(e.message, 'Ошибка');
  943. }
  944. }
  945. async getSeriesBooks(seriesItem) {
  946. //асинхронно подгружаем все книги серии, блокируем повторный вызов
  947. if (seriesItem.allBooksLoaded === null) {
  948. seriesItem.allBooksLoaded = undefined;
  949. (async() => {
  950. seriesItem.allBooksLoaded = await this.loadSeriesBooks(seriesItem.series);
  951. if (seriesItem.allBooksLoaded) {
  952. seriesItem.allBooksLoaded = seriesItem.allBooksLoaded.filter(book => (this.showDeleted || !book.del));
  953. this.sortSeriesBooks(seriesItem.allBooksLoaded);
  954. this.showMoreSeries(seriesItem);
  955. } else {
  956. seriesItem.allBooksLoaded = null;
  957. }
  958. })();
  959. }
  960. }
  961. filterBooks(books) {
  962. const s = this.search;
  963. const emptyFieldValue = '?';
  964. const ruAlphabet = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя';
  965. const enAlphabet = 'abcdefghijklmnopqrstuvwxyz';
  966. const enru = new Set((ruAlphabet + enAlphabet).split(''));
  967. const splitAuthor = (author) => {
  968. if (!author) {
  969. author = emptyFieldValue;
  970. }
  971. const result = author.split(',');
  972. if (result.length > 1)
  973. result.push(author);
  974. return result;
  975. };
  976. const filterBySearch = (bookValue, searchValue) => {
  977. if (!searchValue)
  978. return true;
  979. bookValue = bookValue.toLowerCase();
  980. searchValue = searchValue.toLowerCase();
  981. //особая обработка префиксов
  982. if (searchValue[0] == '=') {
  983. searchValue = searchValue.substring(1);
  984. return bookValue == searchValue;
  985. } else if (searchValue[0] == '*') {
  986. searchValue = searchValue.substring(1);
  987. return bookValue.indexOf(searchValue) >= 0;
  988. } else if (searchValue[0] == '#') {
  989. searchValue = searchValue.substring(1);
  990. return !bookValue || (!enru.has(bookValue[0]) && bookValue.indexOf(searchValue) >= 0);
  991. } else if (searchValue[0] == '?') {
  992. return bookValue == '' || bookValue.indexOf(searchValue) == 0;
  993. } else {
  994. return bookValue.indexOf(searchValue) == 0;
  995. }
  996. };
  997. return books.filter((book) => {
  998. //author
  999. let authorFound = false;
  1000. const authors = splitAuthor(book.author);
  1001. for (const a of authors) {
  1002. if (filterBySearch(a, s.author)) {
  1003. authorFound = true;
  1004. break;
  1005. }
  1006. }
  1007. //genre
  1008. let genreFound = !s.genre;
  1009. if (!genreFound) {
  1010. const searchGenres = new Set(s.genre.split(','));
  1011. const bookGenres = book.genre.split(',');
  1012. for (let g of bookGenres) {
  1013. if (!g)
  1014. g = emptyFieldValue;
  1015. if (searchGenres.has(g)) {
  1016. genreFound = true;
  1017. break;
  1018. }
  1019. }
  1020. }
  1021. //lang
  1022. let langFound = !s.lang;
  1023. if (!langFound) {
  1024. const searchLang = new Set(s.lang.split(','));
  1025. langFound = searchLang.has(book.lang || emptyFieldValue);
  1026. }
  1027. return (this.showDeleted || !book.del)
  1028. && authorFound
  1029. && filterBySearch(book.series, s.series)
  1030. && filterBySearch(book.title, s.title)
  1031. && genreFound
  1032. && langFound
  1033. ;
  1034. });
  1035. }
  1036. showMore(item, all = false) {
  1037. if (item.booksLoaded) {
  1038. const currentLen = (item.books ? item.books.length : 0);
  1039. let books;
  1040. if (all || currentLen + showMoreCount*1.5 > item.booksLoaded.length) {
  1041. books = item.booksLoaded;
  1042. } else {
  1043. books = item.booksLoaded.slice(0, currentLen + showMoreCount);
  1044. }
  1045. item.showMore = (books.length < item.booksLoaded.length);
  1046. item.books = books;
  1047. }
  1048. }
  1049. showMoreSeries(seriesItem, all = false) {
  1050. if (seriesItem.allBooksLoaded) {
  1051. const currentLen = (seriesItem.allBooks ? seriesItem.allBooks.length : 0);
  1052. let books;
  1053. if (all || currentLen + showMoreCount*1.5 > seriesItem.allBooksLoaded.length) {
  1054. books = seriesItem.allBooksLoaded;
  1055. } else {
  1056. books = seriesItem.allBooksLoaded.slice(0, currentLen + showMoreCount);
  1057. }
  1058. seriesItem.showMore = (books.length < seriesItem.allBooksLoaded.length);
  1059. seriesItem.allBooks = books;
  1060. }
  1061. }
  1062. sortSeriesBooks(seriesBooks) {
  1063. seriesBooks.sort((a, b) => {
  1064. const dserno = (a.serno || Number.MAX_VALUE) - (b.serno || Number.MAX_VALUE);
  1065. const dtitle = a.title.localeCompare(b.title);
  1066. const dext = a.ext.localeCompare(b.ext);
  1067. return (dserno ? dserno : (dtitle ? dtitle : dext));
  1068. });
  1069. }
  1070. async getBooks(item) {
  1071. if (item.books) {
  1072. if (item.count > maxItemCount) {
  1073. item.bookLoading = true;
  1074. await utils.sleep(1);//для перерисовки списка
  1075. item.bookLoading = false;
  1076. }
  1077. return;
  1078. }
  1079. if (!this.getBooksFlag)
  1080. this.getBooksFlag = 0;
  1081. this.getBooksFlag++;
  1082. if (item.count > maxItemCount)
  1083. item.bookLoading = true;
  1084. try {
  1085. if (this.getBooksFlag == 1) {
  1086. (async() => {
  1087. await utils.sleep(500);
  1088. if (this.getBooksFlag > 0)
  1089. this.loadingMessage2 = 'Загрузка списка книг...';
  1090. })();
  1091. }
  1092. const booksToFilter = await this.loadBooks(item.key);
  1093. const filtered = this.filterBooks(booksToFilter);
  1094. const prepareBook = (book) => {
  1095. return Object.assign(
  1096. {
  1097. key: book.id,
  1098. type: 'book',
  1099. },
  1100. book
  1101. );
  1102. };
  1103. //объединение по сериям
  1104. const books = [];
  1105. const seriesIndex = {};
  1106. for (const book of filtered) {
  1107. if (book.series) {
  1108. let index = seriesIndex[book.series];
  1109. if (index === undefined) {
  1110. index = books.length;
  1111. books.push(reactive({
  1112. key: `${item.author}-${book.series}`,
  1113. type: 'series',
  1114. series: book.series,
  1115. allBooksLoaded: null,
  1116. allBooks: null,
  1117. showAllBooks: false,
  1118. showMore: false,
  1119. seriesBooks: [],
  1120. }));
  1121. seriesIndex[book.series] = index;
  1122. }
  1123. books[index].seriesBooks.push(prepareBook(book));
  1124. } else {
  1125. books.push(prepareBook(book));
  1126. }
  1127. }
  1128. //сортировка
  1129. books.sort((a, b) => {
  1130. if (a.type == 'series') {
  1131. return (b.type == 'series' ? a.key.localeCompare(b.key) : -1);
  1132. } else {
  1133. return (b.type == 'book' ? a.title.localeCompare(b.title) : 1);
  1134. }
  1135. });
  1136. //сортировка внутри серий
  1137. for (const book of books) {
  1138. if (book.type == 'series') {
  1139. this.sortSeriesBooks(book.seriesBooks);
  1140. //асинхронно подгрузим все книги серии, если она раскрыта
  1141. if (this.isExpandedSeries(book)) {
  1142. this.getSeriesBooks(book);//no await
  1143. }
  1144. }
  1145. }
  1146. if (books.length == 1 && books[0].type == 'series' && !this.isExpandedSeries(books[0])) {
  1147. this.expandSeries(books[0]);
  1148. }
  1149. item.booksLoaded = books;
  1150. this.showMore(item);
  1151. await this.$nextTick();
  1152. } finally {
  1153. item.bookLoading = false;
  1154. this.getBooksFlag--;
  1155. if (this.getBooksFlag == 0)
  1156. this.loadingMessage2 = '';
  1157. }
  1158. }
  1159. async updateGenreTreeIfNeeded() {
  1160. try {
  1161. if (this.genreTreeInpxHash !== this.inpxHash) {
  1162. let result;
  1163. if (this.abCacheEnabled) {
  1164. const key = `genre-tree-${this.inpxHash}`;
  1165. const data = await authorBooksStorage.getData(key);
  1166. if (data) {
  1167. result = JSON.parse(data);
  1168. } else {
  1169. result = await this.api.getGenreTree();
  1170. await authorBooksStorage.setData(key, JSON.stringify(result));
  1171. }
  1172. } else {
  1173. result = await this.api.getGenreTree();
  1174. }
  1175. this.genreTree = result.genreTree;
  1176. this.langList = result.langList;
  1177. this.genreTreeInpxHash = result.inpxHash;
  1178. }
  1179. } catch (e) {
  1180. this.$root.stdDialog.alert(e.message, 'Ошибка');
  1181. }
  1182. }
  1183. async updateTableData() {
  1184. let result = [];
  1185. const expandedSet = new Set(this.expanded);
  1186. const authors = this.searchResult.author;
  1187. if (!authors)
  1188. return;
  1189. let num = 0;
  1190. this.hiddenCount = 0;
  1191. for (const rec of authors) {
  1192. this.cachedAuthors[rec.author] = rec;
  1193. const count = (this.showDeleted ? rec.bookCount + rec.bookDelCount : rec.bookCount);
  1194. if (!count) {
  1195. this.hiddenCount++;
  1196. continue;
  1197. }
  1198. const item = reactive({
  1199. key: rec.id,
  1200. num,
  1201. author: rec.author,
  1202. name: rec.author.replace(/,/g, ', '),
  1203. count,
  1204. booksLoaded: false,
  1205. books: false,
  1206. bookLoading: false,
  1207. showMore: false,
  1208. });
  1209. num++;
  1210. if (expandedSet.has(item.author)) {
  1211. if (authors.length > 1 || item.count > maxItemCount)
  1212. this.getBooks(item);//no await
  1213. else
  1214. await this.getBooks(item);
  1215. }
  1216. result.push(item);
  1217. }
  1218. if (result.length == 1 && !this.isExpanded(result[0])) {
  1219. this.expandAuthor(result[0]);
  1220. }
  1221. this.tableData = result;
  1222. }
  1223. async refresh() {
  1224. if (!this.ready)
  1225. return;
  1226. this.updateRouteQueryFromSearch();
  1227. //оптимизация
  1228. if (this.abCacheEnabled && this.search.author && this.search.author[0] == '=') {
  1229. const authorSearch = this.search.author.substring(1);
  1230. const author = this.cachedAuthors[authorSearch];
  1231. if (author) {
  1232. const key = `${author.id}-${this.inpxHash}`;
  1233. let data = await authorBooksStorage.getData(key);
  1234. if (data) {
  1235. this.queryFound = 1;
  1236. this.totalFound = 1;
  1237. this.searchResult = {author: [author]};
  1238. await this.updateTableData();
  1239. return;
  1240. }
  1241. }
  1242. }
  1243. //параметры запроса
  1244. const offset = (this.search.page - 1)*this.search.limit;
  1245. const newQuery = _.cloneDeep(this.search);
  1246. newQuery.offset = offset;
  1247. this.queryExecute = newQuery;
  1248. if (this.refreshing)
  1249. return;
  1250. this.refreshing = true;
  1251. try {
  1252. while (this.queryExecute) {
  1253. const query = this.queryExecute;
  1254. this.queryExecute = null;
  1255. let inSearch = true;
  1256. (async() => {
  1257. await utils.sleep(500);
  1258. if (inSearch)
  1259. this.loadingMessage = 'Поиск авторов...';
  1260. })();
  1261. try {
  1262. const result = await this.api.search(query);
  1263. this.queryFound = result.author.length;
  1264. this.totalFound = result.totalFound;
  1265. this.inpxHash = result.inpxHash;
  1266. this.searchResult = result;
  1267. await utils.sleep(1);
  1268. if (!this.queryExecute) {
  1269. await this.updateGenreTreeIfNeeded();
  1270. await this.updateTableData();
  1271. this.scrollToTop();
  1272. this.highlightPageScroller(query);
  1273. }
  1274. } catch (e) {
  1275. this.$root.stdDialog.alert(e.message, 'Ошибка');
  1276. } finally {
  1277. inSearch = false;
  1278. this.loadingMessage = '';
  1279. }
  1280. }
  1281. } finally {
  1282. this.refreshing = false;
  1283. }
  1284. }
  1285. }
  1286. export default vueComponent(Search);
  1287. //-----------------------------------------------------------------------------
  1288. </script>
  1289. <style scoped>
  1290. .root {
  1291. }
  1292. .tool-panel {
  1293. border-bottom: 1px solid black;
  1294. }
  1295. .header {
  1296. min-height: 30px;
  1297. }
  1298. .clickable {
  1299. color: blue;
  1300. cursor: pointer;
  1301. }
  1302. .clickable2 {
  1303. cursor: pointer;
  1304. }
  1305. .odd-author {
  1306. background-color: #e8e8e8;
  1307. }
  1308. .book-row {
  1309. margin-left: 50px;
  1310. }
  1311. </style>