Search.vue 46 KB

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