Search.vue 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215
  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. "~" поиск по регулярному выражению. Например, для "~^\\s" в поле названия, будут найдены
  686. все книги, названия которых начинаются с пробельного символа
  687. </li>
  688. <br>
  689. <li>
  690. "?" поиск пустых значений или тех, что начинаются с этого символа. Например, "?" в поле серии означает: найти всех авторов, у которых есть книги без серий
  691. или название серии начинается с "?".
  692. Значение "?" в поле названия означает: найти всех авторов, книги которых без названия или начинаются с "?"
  693. </li>
  694. </ul>
  695. <br>
  696. Специльное имя автора "?" служит для поиска и группировки книг без автора.
  697. <br><br>
  698. Для разделов <b>Серии</b>, <b>Книги</b> все аналогично разделу <b>Авторы</b>.
  699. </p>
  700. `;
  701. this.$root.stdDialog.alert(info, 'Памятка', {iconName: 'la la-info-circle'});
  702. }
  703. showCollectionInfo() {
  704. /*
  705. "dbConfig": {
  706. "inpxInfo": {
  707. "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/",
  708. },
  709. "stats": {
  710. "recsLoaded": 687063,
  711. "authorCount": 153364,
  712. "authorCountAll": 177034,
  713. "bookCount": 576018,
  714. "bookCountAll": 687063,
  715. "bookDelCount": 111045,
  716. "noAuthorBookCount": 4347,
  717. "titleCount": 512671,
  718. "seriesCount": 54472,
  719. "genreCount": 238,
  720. "langCount": 102
  721. },
  722. */
  723. let info = '';
  724. const inpxInfo = this.config.dbConfig.inpxInfo;
  725. const stat = this.config.dbConfig.stats;
  726. const keyStyle = 'style="display: inline-block; text-align: right; margin-right: 5px; min-width: 200px"';
  727. info += `<div style="min-width: 250px" />`;
  728. info += `
  729. <div><div ${keyStyle}>Всего файлов книг:</div><span>${stat.filesCountAll}</span></div>
  730. <div><div ${keyStyle}>Из них актуальных:</div><span>${stat.filesCount}</span></div>
  731. <div><div ${keyStyle}>Помеченных как удаленные:</div><span>${stat.filesDelCount}</span></div>
  732. <br>
  733. <div><div ${keyStyle}>Обработано ссылок на файлы:</div><span>${stat.bookCountAll}</span></div>
  734. <div><div ${keyStyle}>Из них актуальных:</div><span>${stat.bookCount}</span></div>
  735. <div><div ${keyStyle}>Помеченных как удаленные:</div><span>${stat.bookDelCount}</span></div>
  736. <div><div ${keyStyle}>Актуальных без автора:</div><span>${stat.noAuthorBookCount}</span></div>
  737. <br>
  738. <div><div ${keyStyle}>Всего имен авторов:</div><span>${stat.authorCountAll}</span></div>
  739. <div><div ${keyStyle}>Уникальных имен без соавторов:</div><span>${stat.authorCount}</span></div>
  740. <div><div ${keyStyle}>С соавторами:</div><span>${stat.authorCountAll- stat.authorCount}</span></div>
  741. <br>
  742. <div><div ${keyStyle}>Уникальных названий книг:</div><span>${stat.titleCount}</span></div>
  743. <div><div ${keyStyle}>Уникальных названий серий:</div><span>${stat.seriesCount}</span></div>
  744. <div><div ${keyStyle}>Найдено жанров:</div><span>${stat.genreCount}</span></div>
  745. <div><div ${keyStyle}>Найдено языков:</div><span>${stat.langCount}</span></div>
  746. <br>
  747. <div><div ${keyStyle}>Версия поисковой БД:</div><span>${this.config.dbVersion}</span></div>
  748. `;
  749. info += `
  750. <div><hr/>
  751. <b>collection.info:</b>
  752. <pre>${inpxInfo.collection}</pre>
  753. </div>
  754. `;
  755. this.$root.stdDialog.alert(info, 'Статистика по коллекции', {iconName: 'la la-info-circle'});
  756. }
  757. get newSearchLink() {
  758. return window.location.origin;
  759. }
  760. async hideTooltip() {
  761. //Firefox bugfix: при всплывающем диалоге скрываем подсказку
  762. this.showTooltips = false;
  763. await utils.sleep(1000);
  764. this.showTooltips = true;
  765. }
  766. selectGenre() {
  767. this.hideTooltip();
  768. this.selectGenreDialogVisible = true;
  769. }
  770. selectLang() {
  771. this.hideTooltip();
  772. this.selectLangDialogVisible = true;
  773. }
  774. selectLibRate() {
  775. this.hideTooltip();
  776. this.selectLibRateDialogVisible = true;
  777. }
  778. selectExtSearch() {
  779. this.hideTooltip();
  780. this.selectExtSearchDialogVisible = true;
  781. }
  782. clearExtSearch() {
  783. const self = this.extSearch;
  784. self.setDefaults(self, {page: self.page, limit: self.limit});
  785. }
  786. onScroll() {
  787. const curScrollTop = this.$refs.scroller.scrollTop;
  788. if (this.ignoreScrolling) {
  789. this.lastScrollTop = curScrollTop;
  790. if (this.$refs.toolPanel.offsetTop > curScrollTop)
  791. this.$refs.toolPanel.style.top = `${curScrollTop}px`;
  792. return;
  793. }
  794. if (!this.lastScrollTop)
  795. this.lastScrollTop = 0;
  796. if (!this.lastScrollTop2)
  797. this.lastScrollTop2 = 0;
  798. if (curScrollTop - this.lastScrollTop > 0) {
  799. this.$refs.toolPanel.style.position = 'relative';
  800. if (this.lastScrollTop2 <= curScrollTop - this.$refs.toolPanel.clientHeight)
  801. this.lastScrollTop2 = 0;
  802. this.$refs.toolPanel.style.top = `${this.lastScrollTop2}px`;
  803. } else {
  804. this.$refs.toolPanel.style.position = 'sticky';
  805. this.$refs.toolPanel.style.top = 0;
  806. this.lastScrollTop2 = curScrollTop;
  807. }
  808. this.lastScrollTop = curScrollTop;
  809. }
  810. async ignoreScroll(ms = 300) {
  811. this.ignoreScrolling = true;
  812. await utils.sleep(ms);
  813. await this.$nextTick();
  814. await this.$nextTick();
  815. await this.$nextTick();
  816. this.ignoreScrolling = false;
  817. }
  818. scrollToTop() {
  819. this.$refs.scroller.scrollTop = 0;
  820. this.lastScrollTop = 0;
  821. }
  822. updatePageCount() {
  823. if (this.list.totalFound < 0)
  824. return;
  825. const prevPageCount = this.pageCount;
  826. this.pageCount = Math.ceil(this.list.totalFound/this.limit);
  827. this.pageCount = (this.pageCount < 1 ? 1 : this.pageCount);
  828. if (this.prevPage && prevPageCount == 1 && this.pageCount > 1 && this.prevPage <= this.pageCount) {
  829. this.search.page = this.prevPage;
  830. }
  831. if (this.search.page > this.pageCount)
  832. this.search.page = 1;
  833. }
  834. listEvent(event) {
  835. switch (event.action) {
  836. case 'ignoreScroll':
  837. this.ignoreScroll();
  838. break;
  839. case 'highlightPageScroller':
  840. this.highlightPageScroller(event.query);
  841. break;
  842. case 'scrollToTop':
  843. this.scrollToTop();
  844. break;
  845. case 'submitUrl':
  846. this.sendMessage({type: 'submitUrl', data: event.data});
  847. break;
  848. case 'bookInfo':
  849. this.bookInfo = event.data;
  850. this.bookInfoDialogVisible = true;
  851. break;
  852. }
  853. }
  854. setSetting(name, newValue) {
  855. this.commit('setSettings', {[name]: _.cloneDeep(newValue)});
  856. }
  857. highlightPageScroller(query) {
  858. const q = _.cloneDeep(query);
  859. delete q.limit;
  860. delete q.offset;
  861. delete q.page;
  862. try {
  863. if (this.search.page < 2 || !this._prevQuery || _.isEqual(this._prevQuery, q))
  864. return;
  865. this.$refs.pageScroller1.highlightScroller();
  866. } finally {
  867. this._prevQuery = q;
  868. }
  869. }
  870. updateSearchFromRouteQuery(to) {
  871. if (!this.ready)
  872. return;
  873. if (this.list.liberamaReady)
  874. this.sendCurrentUrl();
  875. if (this.routeUpdating)
  876. return;
  877. const query = to.query;
  878. this.search.setDefaults(this.search, {
  879. author: query.author,
  880. series: query.series,
  881. title: query.title,
  882. genre: query.genre,
  883. lang: (typeof(query.lang) == 'string' ? query.lang : this.langDefault),
  884. date: query.date,
  885. librate: query.librate,
  886. page: parseInt(query.page, 10),
  887. limit: parseInt(query.limit, 10) || this.search.limit,
  888. });
  889. if (this.search.limit > maxLimit)
  890. this.search.limit = maxLimit;
  891. const queryExtSearch = {
  892. page: this.search.page,
  893. limit: this.search.limit,
  894. };
  895. for (const f of this.recStruct) {
  896. const field = `ex_${f.field}`;
  897. if (query[field])
  898. queryExtSearch[f.field] = query[field];
  899. }
  900. this.extSearch.setDefaults(this.extSearch, queryExtSearch);
  901. }
  902. updateRouteQueryFromSearch() {
  903. if (!this.ready)
  904. return;
  905. this.routeUpdating = true;
  906. try {
  907. const oldQuery = this.$route.query;
  908. let query = {};
  909. const cloned = {};
  910. this.search.setDefaults(cloned, this.search);
  911. query = _.pickBy(cloned);
  912. if (this.search.lang == this.langDefault) {
  913. delete query.lang;
  914. } else {
  915. query.lang = this.search.lang;
  916. }
  917. for (const f of this.recStruct) {
  918. const field = `ex_${f.field}`;
  919. if (this.extSearch[f.field])
  920. query[field] = this.extSearch[f.field];
  921. }
  922. const diff = diffUtils.getObjDiff(oldQuery, query);
  923. if (!diffUtils.isEmptyObjDiff(diff)) {
  924. this.$router.replace({path: this.selectedList, query});
  925. }
  926. } finally {
  927. (async() => {
  928. await utils.sleep(100);
  929. this.routeUpdating = false;
  930. })();
  931. }
  932. }
  933. async updateGenreTreeIfNeeded() {
  934. if (this.genreTreeUpdating)
  935. return;
  936. this.genreTreeUpdating = true;
  937. try {
  938. if (this.genreTreeInpxHash !== this.list.inpxHash) {
  939. let result;
  940. if (this.abCacheEnabled) {
  941. const key = `genre-tree-${this.list.inpxHash}`;
  942. const data = await authorBooksStorage.getData(key);
  943. if (data) {
  944. result = JSON.parse(data);
  945. } else {
  946. result = await this.api.getGenreTree();
  947. await authorBooksStorage.setData(key, JSON.stringify(result));
  948. }
  949. } else {
  950. result = await this.api.getGenreTree();
  951. }
  952. this.genreTree = result.genreTree;
  953. this.genreMap = new Map();
  954. for (const section of this.genreTree) {
  955. for (const g of section.value)
  956. this.genreMap.set(g.value, g.name);
  957. }
  958. this.langList = result.langList;
  959. this.genreTreeInpxHash = result.inpxHash;
  960. }
  961. } catch (e) {
  962. this.$root.stdDialog.alert(e.message, 'Ошибка');
  963. } finally {
  964. this.genreTreeUpdating = false;
  965. }
  966. }
  967. updateSearchDate(toLocal) {
  968. if (toLocal) {
  969. let local = this.search.date || '';
  970. if (utils.isManualDate(local) || !local)
  971. this.prevManualDate = local;
  972. if (utils.isManualDate(local))
  973. local = 'manual';
  974. this.searchDate = local;
  975. } else {
  976. if (this.searchDate != 'manual')
  977. this.search.date = this.searchDate || '';
  978. }
  979. }
  980. get formatSearchDate() {
  981. const result = [];
  982. const date = this.search.date;
  983. if (utils.isManualDate(date)) {
  984. const [from, to] = date.split(',')
  985. if (from)
  986. result.push(`<div style="display: inline-block; width: 15px; text-align: right;">с</div> ${utils.sqlDateFormat(from)}`);
  987. if (to)
  988. result.push(`<div style="display: inline-block; width: 15px; text-align: right;">по</div> ${utils.sqlDateFormat(to)}`);
  989. }
  990. return result.join('<br>');
  991. }
  992. dateSelectItemClick(itemValue) {
  993. if (itemValue == 'manual') {
  994. if (!utils.isManualDate(this.search.date)) {
  995. this.search.date = this.prevManualDate;
  996. if (!this.search.date)
  997. this.searchDate = '';
  998. }
  999. this.selectDateDialogVisible = true
  1000. }
  1001. }
  1002. cloneSearch() {
  1003. window.open(window.location.href, '_blank');
  1004. }
  1005. extToList(list) {
  1006. if (this.extSearch[list])
  1007. this.search[list] = this.extSearch[list];
  1008. this.selectedList = list;
  1009. }
  1010. async logout() {
  1011. await this.api.logout();
  1012. }
  1013. }
  1014. export default vueComponent(Search);
  1015. //-----------------------------------------------------------------------------
  1016. </script>
  1017. <style scoped>
  1018. .root {
  1019. }
  1020. .tool-panel {
  1021. border-bottom: 1px solid #bbb;
  1022. }
  1023. .header {
  1024. min-height: 30px;
  1025. }
  1026. .clickable {
  1027. color: blue;
  1028. cursor: pointer;
  1029. }
  1030. .clickable2 {
  1031. cursor: pointer;
  1032. }
  1033. .separator {
  1034. border-bottom: 2px solid #ddd;
  1035. margin: 5px 0 5px 0;
  1036. }
  1037. </style>