Search.vue 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223
  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" :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" :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. limitOptions = [
  322. {label: '10', value: 10},
  323. {label: '20', value: 20},
  324. {label: '50', value: 50},
  325. {label: '100', value: 100},
  326. {label: '200', value: 200},
  327. {label: '500', value: 500},
  328. {label: '1000', value: 1000},
  329. ];
  330. searchResult = {};
  331. tableData = [];
  332. created() {
  333. this.commit = this.$store.commit;
  334. this.loadSettings();
  335. }
  336. mounted() {
  337. (async() => {
  338. await authorBooksStorage.init();
  339. this.api = this.$root.api;
  340. if (!this.$root.isMobileDevice)
  341. this.$refs.authorInput.focus();
  342. this.setDefaults();
  343. this.updateQueryFromRoute(this.$route);
  344. //чтоб не вызывался лишний refresh
  345. await utils.sleep(100);
  346. this.ready = true;
  347. this.refresh();//no await
  348. })();
  349. }
  350. loadSettings() {
  351. const settings = this.settings;
  352. this.search.limit = settings.limit;
  353. this.expanded = _.cloneDeep(settings.expanded);
  354. this.expandedSeries = _.cloneDeep(settings.expandedSeries);
  355. this.showCounts = settings.showCounts;
  356. this.showGenres = settings.showGenres;
  357. this.showDeleted = settings.showDeleted;
  358. this.abCacheEnabled = settings.abCacheEnabled;
  359. this.langDefault = settings.langDefault;
  360. }
  361. get config() {
  362. return this.$store.state.config;
  363. }
  364. get settings() {
  365. return this.$store.state.settings;
  366. }
  367. get genreNames() {
  368. let result = [];
  369. const genre = new Set(this.search.genre.split(','));
  370. for (const section of this.genreTree) {
  371. for (const g of section.value)
  372. if (genre.has(g.value))
  373. result.push(g.name);
  374. }
  375. return result.join(', ');
  376. }
  377. openReleasePage() {
  378. window.open('https://github.com/bookpauk/inpx-web', '_blank');
  379. }
  380. makeTitle() {
  381. const collection = this.config.dbConfig.inpxInfo.collection.split('\n');
  382. this.collection = collection[0].trim();
  383. this.projectName = `${this.config.name} v${this.config.version}`;
  384. this.$root.setAppTitle(`Коллекция ${this.collection}`);
  385. }
  386. showSearchHelp() {
  387. let info = '';
  388. info += `<div style="min-width: 250px" />`;
  389. info += `
  390. <p>
  391. Работу поискового движка можно описать простой фразой: найти авторов по указанным критериям.
  392. По тем же критериям среди найденных авторов фильтруются книги, сортируются и группируются по сериям.
  393. <br><br>
  394. По умолчанию поисковое значение трактуется как "начинается с". Например значение автора "Пушкин"
  395. трактуется как: найти авторов, имя которых начинается с "Пушкин". Поиск всегда ведется без
  396. учета регистра - значения "Ельцин" и "ельцин" равнозначны.
  397. <br><br>
  398. В поисковых полях "Автор", "Серия", "Название" также доступны следующие префиксы:
  399. <ul>
  400. <li>
  401. "=" поиск по точному совпадению. Например, если задать "=Пушкин Александр Сергеевич" в поле автора,
  402. то будет найден в точности этот автор
  403. </li>
  404. <br>
  405. <li>
  406. "*" поиск подстроки в строке. Например, для "*Александр" в поле автора, будут найдены
  407. все авторы, имя которых содержит "Александр"
  408. </li>
  409. <br>
  410. <li>
  411. "#" поиск подстроки в строке, но только для тех значений, которые не начинаются ни с одной буквы русского или латинского алфавита.
  412. Например, значение "#поворот" в поле автора означает: найти всех авторов, имя которых начинается не с русской или латинской буквы и содержит слово "поворот".
  413. Указание простого "#" в поиске по названию означает: найти всех авторов, названия книг которых начинаются не с русской или латинской буквы
  414. </li>
  415. <br>
  416. <li>
  417. "?" поиск пустых значений или тех, что начинаются с этого символа. Например, "?" в поле серии означает: найти всех авторов, у которых есть книги без серий
  418. или название серии начинается с "?".
  419. Значение "?" в поле названия означает: найти всех авторов, книги которых без названия или начинаются с "?"
  420. </li>
  421. </ul>
  422. <br>
  423. Специльное имя автора "?" служит для поиска и группировки книг без автора.
  424. </p>
  425. `;
  426. this.$root.stdDialog.alert(info, 'Памятка', {iconName: 'la la-info-circle'});
  427. }
  428. showHiddenHelp() {
  429. this.$root.stdDialog.alert(`
  430. Книги этих авторов помечены как удаленные. Для того, чтобы их увидеть, необходимо установить опцию "Показывать удаленные" в настройках.
  431. `, 'Пояснение', {iconName: 'la la-info-circle'});
  432. }
  433. showCollectionInfo() {
  434. /*
  435. "dbConfig": {
  436. "inpxInfo": {
  437. "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/",
  438. },
  439. "stats": {
  440. "recsLoaded": 687063,
  441. "authorCount": 153364,
  442. "authorCountAll": 177034,
  443. "bookCount": 576018,
  444. "bookCountAll": 687063,
  445. "bookDelCount": 111045,
  446. "noAuthorBookCount": 4347,
  447. "titleCount": 512671,
  448. "seriesCount": 54472,
  449. "genreCount": 238,
  450. "langCount": 102
  451. },
  452. */
  453. let info = '';
  454. const inpxInfo = this.config.dbConfig.inpxInfo;
  455. const stat = this.config.dbConfig.stats;
  456. const keyStyle = 'style="display: inline-block; text-align: right; margin-right: 5px; min-width: 200px"';
  457. info += `<div style="min-width: 250px" />`;
  458. info += `
  459. <div><div ${keyStyle}>Обработано ссылок на файлы:</div><span>${stat.bookCountAll}</span></div>
  460. <div><div ${keyStyle}>Из них актуальных:</div><span>${stat.bookCount}</span></div>
  461. <div><div ${keyStyle}>Помеченных как удаленные:</div><span>${stat.bookDelCount}</span></div>
  462. <div><div ${keyStyle}>Актуальных без автора:</div><span>${stat.noAuthorBookCount}</span></div>
  463. <br>
  464. <div><div ${keyStyle}>Всего записей об авторах:</div><span>${stat.authorCountAll}</span></div>
  465. <div><div ${keyStyle}>Записей без соавторов:</div><span>${stat.authorCount}</span></div>
  466. <div><div ${keyStyle}>С соавторами:</div><span>${stat.authorCountAll- stat.authorCount}</span></div>
  467. <br>
  468. <div><div ${keyStyle}>Уникальных названий книг:</div><span>${stat.titleCount}</span></div>
  469. <div><div ${keyStyle}>Уникальных серий:</div><span>${stat.seriesCount}</span></div>
  470. <div><div ${keyStyle}>Найдено жанров:</div><span>${stat.genreCount}</span></div>
  471. <div><div ${keyStyle}>Найдено языков:</div><span>${stat.langCount}</span></div>
  472. `;
  473. info += `
  474. <div><hr/>
  475. <b>collection.info:</b>
  476. <pre>${inpxInfo.collection}</pre>
  477. </div>
  478. `;
  479. this.$root.stdDialog.alert(info, 'Статистика по коллекции', {iconName: 'la la-info-circle'});
  480. }
  481. selectGenre() {
  482. this.selectGenreDialogVisible = true;
  483. }
  484. selectLang() {
  485. this.selectLangDialogVisible = true;
  486. }
  487. onScroll() {
  488. if (this.ignoreScrolling)
  489. return;
  490. const curScrollTop = this.$refs.scroller.scrollTop;
  491. if (!this.lastScrollTop)
  492. this.lastScrollTop = 0;
  493. if (!this.lastScrollTop2)
  494. this.lastScrollTop2 = 0;
  495. if (curScrollTop - this.lastScrollTop > 0) {
  496. this.$refs.toolPanel.style.position = 'relative';
  497. this.$refs.toolPanel.style.top = `${this.lastScrollTop2}px`;
  498. } else if (curScrollTop - this.lastScrollTop <= 0) {
  499. this.$refs.toolPanel.style.position = 'sticky';
  500. this.$refs.toolPanel.style.top = 0;
  501. this.lastScrollTop2 = curScrollTop;
  502. }
  503. this.lastScrollTop = curScrollTop;
  504. }
  505. async ignoreScroll(ms = 50) {
  506. this.ignoreScrolling = true;
  507. await utils.sleep(ms);
  508. this.ignoreScrolling = false;
  509. }
  510. scrollToTop() {
  511. this.$refs.scroller.scrollTop = 0;
  512. this.lastScrollTop = 0;
  513. }
  514. get foundAuthorsMessage() {
  515. return `Найден${utils.wordEnding(this.totalFound, 2)} ${this.totalFound} автор${utils.wordEnding(this.totalFound)}`;
  516. }
  517. get hiddenResultsMessage() {
  518. return `+${this.hiddenCount} результат${utils.wordEnding(this.hiddenCount)} скрыт${utils.wordEnding(this.hiddenCount, 2)}`;
  519. }
  520. updatePageCount() {
  521. const prevPageCount = this.pageCount;
  522. this.pageCount = Math.ceil(this.totalFound/this.limit);
  523. this.pageCount = (this.pageCount < 1 ? 1 : this.pageCount);
  524. if (this.prevPage && prevPageCount == 1 && this.pageCount > 1 && this.prevPage <= this.pageCount) {
  525. this.search.page = this.prevPage;
  526. }
  527. if (this.search.page > this.pageCount) {
  528. this.prevPage = this.search.page;
  529. this.search.page = 1;
  530. }
  531. }
  532. getBookCount(item) {
  533. let result = '';
  534. if (!this.showCounts || item.count === undefined)
  535. return result;
  536. if (item.books) {
  537. let count = 0;
  538. for (const book of item.books) {
  539. if (book._type == 'series')
  540. count += book.books.length;
  541. else
  542. count++;
  543. }
  544. result = `${count}/${item.count}`;
  545. } else
  546. result = `#/${item.count}`;
  547. return `(${result})`;
  548. }
  549. selectAuthor(author) {
  550. this.search.author = `=${author}`;
  551. this.scrollToTop();
  552. }
  553. selectSeries(series) {
  554. this.search.series = `=${series}`;
  555. }
  556. async download(book, copy = false) {
  557. if (this.downloadFlag)
  558. return;
  559. this.downloadFlag = true;
  560. (async() => {
  561. await utils.sleep(200);
  562. if (this.downloadFlag)
  563. this.loadingMessage2 = 'Подготовка файла...';
  564. })();
  565. try {
  566. const makeValidFilenameOrEmpty = (s) => {
  567. try {
  568. return utils.makeValidFilename(s);
  569. } catch(e) {
  570. return '';
  571. }
  572. };
  573. //имя файла
  574. let downFileName = 'default-name';
  575. const author = book.author.split(',');
  576. const at = [author[0], book.title];
  577. downFileName = makeValidFilenameOrEmpty(at.filter(r => r).join(' - '))
  578. || makeValidFilenameOrEmpty(at[0])
  579. || makeValidFilenameOrEmpty(at[1])
  580. || downFileName;
  581. downFileName = `${downFileName.substring(0, 100)}.${book.ext}`;
  582. const bookPath = `${book.folder}/${book.file}.${book.ext}`;
  583. //подготовка
  584. const response = await this.api.getBookLink({bookPath, downFileName});
  585. const link = response.link;
  586. const href = `${window.location.origin}${link}`;
  587. if (!copy) {
  588. //скачивание
  589. const d = this.$refs.download;
  590. d.href = href;
  591. d.download = downFileName;
  592. d.click();
  593. } else {
  594. //копирование ссылки
  595. if (utils.copyTextToClipboard(href))
  596. this.$root.notify.success('Ссылка успешно скопирована');
  597. else
  598. this.$root.notify.error('Копирование ссылки не удалось');
  599. }
  600. } catch(e) {
  601. this.$root.stdDialog.alert(e.message, 'Ошибка');
  602. } finally {
  603. this.downloadFlag = false;
  604. this.loadingMessage2 = '';
  605. }
  606. }
  607. bookEvent(event) {
  608. switch (event.action) {
  609. case 'titleClick':
  610. this.search.title = `=${event.book.title}`;
  611. break;
  612. case 'download':
  613. this.download(event.book);//no await
  614. break;
  615. case 'copyLink':
  616. this.download(event.book, true);//no await
  617. break;
  618. }
  619. }
  620. isExpanded(item) {
  621. return this.expanded.indexOf(item.author) >= 0;
  622. }
  623. isExpandedSeries(seriesItem) {
  624. return this.expandedSeries.indexOf(seriesItem._key) >= 0;
  625. }
  626. setSetting(name, newValue) {
  627. this.commit('setSettings', {[name]: _.cloneDeep(newValue)});
  628. }
  629. setDefaults() {
  630. this.search = Object.assign({}, this.search, {
  631. author: '',
  632. series: '',
  633. title: '',
  634. genre: '',
  635. lang: this.langDefault,
  636. });
  637. }
  638. async updateQueryFromRoute(to) {
  639. if (this.routeUpdating)
  640. return;
  641. const query = to.query;
  642. this.search = Object.assign({}, this.search, {
  643. author: query.author || '',
  644. series: query.series || '',
  645. title: query.title || '',
  646. genre: query.genre || '',
  647. lang: (query.lang == 'default' ? this.langDefault : query.lang || ''),
  648. page: parseInt(query.page, 10) || 1,
  649. limit: parseInt(query.limit, 10) || 20,
  650. });
  651. if (this.search.limit > 1000)
  652. this.search.limit = 1000;
  653. }
  654. updateRouteQuery() {
  655. this.routeUpdating = true;
  656. try {
  657. const oldQuery = this.$route.query;
  658. const query = _.pickBy(this.search);
  659. if (this.search.lang == this.langDefault)
  660. query.lang = 'default'
  661. const diff = diffUtils.getObjDiff(oldQuery, query);
  662. if (!diffUtils.isEmptyObjDiff(diff)) {
  663. this.$router.replace({query});
  664. }
  665. } finally {
  666. (async() => {
  667. await utils.sleep(100);
  668. this.routeUpdating = false;
  669. })();
  670. }
  671. }
  672. async expandAuthor(item) {
  673. const expanded = _.cloneDeep(this.expanded);
  674. const key = item.author;
  675. if (!this.isExpanded(item)) {
  676. expanded.push(key);
  677. await this.getBooks(item);
  678. if (expanded.length > 10) {
  679. expanded.shift();
  680. }
  681. this.setSetting('expanded', expanded);
  682. this.ignoreScroll();
  683. } else {
  684. const i = expanded.indexOf(key);
  685. if (i >= 0) {
  686. expanded.splice(i, 1);
  687. this.setSetting('expanded', expanded);
  688. }
  689. }
  690. }
  691. expandSeries(seriesItem) {
  692. const expandedSeries = _.cloneDeep(this.expandedSeries);
  693. const key = seriesItem._key;
  694. if (!this.isExpandedSeries(seriesItem)) {
  695. expandedSeries.push(key);
  696. if (expandedSeries.length > 100) {
  697. expandedSeries.shift();
  698. }
  699. this.setSetting('expandedSeries', expandedSeries);
  700. this.ignoreScroll();
  701. } else {
  702. const i = expandedSeries.indexOf(key);
  703. if (i >= 0) {
  704. expandedSeries.splice(i, 1);
  705. this.setSetting('expandedSeries', expandedSeries);
  706. }
  707. }
  708. }
  709. async loadBooks(authorId) {
  710. try {
  711. let result;
  712. if (this.abCacheEnabled) {
  713. const key = `${authorId}-${this.inpxHash}`;
  714. const data = await authorBooksStorage.getData(key);
  715. if (data) {
  716. result = JSON.parse(data);
  717. } else {
  718. result = await this.api.getBookList(authorId);
  719. await authorBooksStorage.setData(key, JSON.stringify(result));
  720. }
  721. } else {
  722. result = await this.api.getBookList(authorId);
  723. }
  724. return JSON.parse(result.books);
  725. } catch (e) {
  726. this.$root.stdDialog.alert(e.message, 'Ошибка');
  727. }
  728. }
  729. filterBooks(loadedBooks) {
  730. const s = this.search;
  731. const emptyFieldValue = '?';
  732. const ruAlphabet = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя';
  733. const enAlphabet = 'abcdefghijklmnopqrstuvwxyz';
  734. const enru = new Set((ruAlphabet + enAlphabet).split(''));
  735. const splitAuthor = (author) => {
  736. if (!author) {
  737. author = emptyFieldValue;
  738. }
  739. const result = author.split(',');
  740. if (result.length > 1)
  741. result.push(author);
  742. return result;
  743. };
  744. const filterBySearch = (bookValue, searchValue) => {
  745. if (!searchValue)
  746. return true;
  747. bookValue = bookValue.toLowerCase();
  748. searchValue = searchValue.toLowerCase();
  749. //особая обработка префиксов
  750. if (searchValue[0] == '=') {
  751. searchValue = searchValue.substring(1);
  752. return bookValue == searchValue;
  753. } else if (searchValue[0] == '*') {
  754. searchValue = searchValue.substring(1);
  755. return bookValue.indexOf(searchValue) >= 0;
  756. } else if (searchValue[0] == '#') {
  757. searchValue = searchValue.substring(1);
  758. return !bookValue || (!enru.has(bookValue[0]) && bookValue.indexOf(searchValue) >= 0);
  759. } else if (searchValue[0] == '?') {
  760. return bookValue == '' || bookValue.indexOf(searchValue) == 0;
  761. } else {
  762. return bookValue.indexOf(searchValue) == 0;
  763. }
  764. };
  765. return loadedBooks.filter((book) => {
  766. //author
  767. let authorFound = false;
  768. const authors = splitAuthor(book.author);
  769. for (const a of authors) {
  770. if (filterBySearch(a, s.author)) {
  771. authorFound = true;
  772. break;
  773. }
  774. }
  775. //genre
  776. let genreFound = !s.genre;
  777. if (!genreFound) {
  778. const searchGenres = new Set(s.genre.split(','));
  779. const bookGenres = book.genre.split(',');
  780. for (let g of bookGenres) {
  781. if (!g)
  782. g = emptyFieldValue;
  783. if (searchGenres.has(g)) {
  784. genreFound = true;
  785. break;
  786. }
  787. }
  788. }
  789. //lang
  790. let langFound = !s.lang;
  791. if (!langFound) {
  792. const searchLang = new Set(s.lang.split(','));
  793. langFound = searchLang.has(book.lang || emptyFieldValue);
  794. }
  795. return (this.showDeleted || !book.del)
  796. && authorFound
  797. && filterBySearch(book.series, s.series)
  798. && filterBySearch(book.title, s.title)
  799. && genreFound
  800. && langFound
  801. ;
  802. });
  803. }
  804. async getBooks(item) {
  805. if (item.books) {
  806. if (item.count > maxItemCount) {
  807. item.bookLoading = true;
  808. await utils.sleep(1);//для перерисовки списка
  809. item.bookLoading = false;
  810. }
  811. return;
  812. }
  813. if (!this.getBooksFlag)
  814. this.getBooksFlag = 0;
  815. this.getBooksFlag++;
  816. if (item.count > maxItemCount)
  817. item.bookLoading = true;
  818. try {
  819. if (this.getBooksFlag == 1) {
  820. (async() => {
  821. await utils.sleep(500);
  822. if (this.getBooksFlag > 0)
  823. this.loadingMessage2 = 'Загрузка списка книг...';
  824. })();
  825. }
  826. const loadedBooks = await this.loadBooks(item.key);
  827. const filtered = this.filterBooks(loadedBooks);
  828. const prepareBook = (book) => {
  829. return Object.assign(
  830. {
  831. _key: book.id,
  832. _type: 'book',
  833. },
  834. book
  835. );
  836. };
  837. //объединение по сериям
  838. const books = [];
  839. const seriesIndex = {};
  840. for (const book of filtered) {
  841. if (book.series) {
  842. let index = seriesIndex[book.series];
  843. if (index === undefined) {
  844. index = books.length;
  845. books.push({
  846. _key: `${item.author}-${book.series}`,
  847. _type: 'series',
  848. series: book.series,
  849. books: [],
  850. });
  851. seriesIndex[book.series] = index;
  852. }
  853. books[index].books.push(prepareBook(book));
  854. } else {
  855. books.push(prepareBook(book));
  856. }
  857. }
  858. //сортировка
  859. books.sort((a, b) => {
  860. if (a._type == 'series') {
  861. return (b._type == 'series' ? a._key.localeCompare(b._key) : -1);
  862. } else {
  863. return (b._type == 'book' ? a.title.localeCompare(b.title) : 1);
  864. }
  865. });
  866. //сортировка внутри серий
  867. for (const book of books) {
  868. if (book._type == 'series') {
  869. book.books.sort((a, b) => {
  870. const dserno = (a.serno || Number.MAX_VALUE) - (b.serno || Number.MAX_VALUE);
  871. const dtitle = a.title.localeCompare(b.title);
  872. const dext = a.ext.localeCompare(b.ext);
  873. return (dserno ? dserno : (dtitle ? dtitle : dext));
  874. });
  875. }
  876. }
  877. if (books.length == 1 && books[0]._type == 'series' && !this.isExpandedSeries(books[0])) {
  878. this.expandSeries(books[0]);
  879. }
  880. item.books = books;
  881. await this.$nextTick();
  882. } finally {
  883. item.bookLoading = false;
  884. this.getBooksFlag--;
  885. if (this.getBooksFlag == 0)
  886. this.loadingMessage2 = '';
  887. }
  888. }
  889. async updateGenreTreeIfNeeded() {
  890. try {
  891. if (this.genreTreeInpxHash !== this.inpxHash) {
  892. let result;
  893. if (this.abCacheEnabled) {
  894. const key = `genre-tree-${this.inpxHash}`;
  895. const data = await authorBooksStorage.getData(key);
  896. if (data) {
  897. result = JSON.parse(data);
  898. } else {
  899. result = await this.api.getGenreTree();
  900. await authorBooksStorage.setData(key, JSON.stringify(result));
  901. }
  902. } else {
  903. result = await this.api.getGenreTree();
  904. }
  905. this.genreTree = result.genreTree;
  906. this.langList = result.langList;
  907. this.genreTreeInpxHash = result.inpxHash;
  908. }
  909. } catch (e) {
  910. this.$root.stdDialog.alert(e.message, 'Ошибка');
  911. }
  912. }
  913. async updateTableData() {
  914. let result = [];
  915. const expandedSet = new Set(this.expanded);
  916. const authors = this.searchResult.author;
  917. if (!authors)
  918. return;
  919. let num = 0;
  920. this.hiddenCount = 0;
  921. for (const rec of authors) {
  922. this.cachedAuthors[rec.author] = rec;
  923. const count = (this.showDeleted ? rec.bookCount + rec.bookDelCount : rec.bookCount);
  924. if (!count) {
  925. this.hiddenCount++;
  926. continue;
  927. }
  928. const item = reactive({
  929. key: rec.id,
  930. num,
  931. author: rec.author,
  932. name: rec.author.replace(/,/g, ', '),
  933. count,
  934. book: false,
  935. bookLoading: false,
  936. });
  937. num++;
  938. if (expandedSet.has(item.author)) {
  939. if (authors.length > 1 || item.count > maxItemCount)
  940. this.getBooks(item);//no await
  941. else
  942. await this.getBooks(item);
  943. }
  944. result.push(item);
  945. }
  946. if (result.length == 1 && !this.isExpanded(result[0])) {
  947. this.expandAuthor(result[0]);
  948. }
  949. this.tableData = result;
  950. }
  951. async refresh() {
  952. if (!this.ready)
  953. return;
  954. this.updateRouteQuery();
  955. //оптимизация
  956. if (this.abCacheEnabled && this.search.author && this.search.author[0] == '=') {
  957. const authorSearch = this.search.author.substring(1);
  958. const author = this.cachedAuthors[authorSearch];
  959. if (author) {
  960. const key = `${author.id}-${this.inpxHash}`;
  961. let data = await authorBooksStorage.getData(key);
  962. if (data) {
  963. this.queryFound = 1;
  964. this.totalFound = 1;
  965. this.searchResult = {author: [author]};
  966. await this.updateTableData();
  967. return;
  968. }
  969. }
  970. }
  971. //параметры запроса
  972. const offset = (this.search.page - 1)*this.search.limit;
  973. const newQuery = _.cloneDeep(this.search);
  974. newQuery.offset = offset;
  975. this.queryExecute = newQuery;
  976. if (this.refreshing)
  977. return;
  978. this.refreshing = true;
  979. try {
  980. while (this.queryExecute) {
  981. const query = this.queryExecute;
  982. this.queryExecute = null;
  983. let inSearch = true;
  984. (async() => {
  985. await utils.sleep(500);
  986. if (inSearch)
  987. this.loadingMessage = 'Поиск авторов...';
  988. })();
  989. try {
  990. const result = await this.api.search(query);
  991. this.queryFound = result.author.length;
  992. this.totalFound = result.totalFound;
  993. this.inpxHash = result.inpxHash;
  994. this.searchResult = result;
  995. await utils.sleep(1);
  996. if (!this.queryExecute) {
  997. await this.updateGenreTreeIfNeeded();
  998. await this.updateTableData();
  999. this.scrollToTop();
  1000. }
  1001. } catch (e) {
  1002. this.$root.stdDialog.alert(e.message, 'Ошибка');
  1003. } finally {
  1004. inSearch = false;
  1005. this.loadingMessage = '';
  1006. }
  1007. }
  1008. } finally {
  1009. this.refreshing = false;
  1010. }
  1011. }
  1012. }
  1013. export default vueComponent(Search);
  1014. //-----------------------------------------------------------------------------
  1015. </script>
  1016. <style scoped>
  1017. .root {
  1018. }
  1019. .tool-panel {
  1020. border-bottom: 1px solid black;
  1021. }
  1022. .header {
  1023. min-height: 30px;
  1024. }
  1025. .clickable {
  1026. color: blue;
  1027. cursor: pointer;
  1028. }
  1029. .clickable2 {
  1030. cursor: pointer;
  1031. }
  1032. .odd-author {
  1033. background-color: #e8e8e8;
  1034. }
  1035. .book-row {
  1036. margin-left: 70px;
  1037. }
  1038. </style>