Search.vue 45 KB

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