Search.vue 45 KB

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