Search.vue 47 KB

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