@internetarchive/collection-browser 1.13.0-alpha2 → 1.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (287) hide show
  1. package/.editorconfig +29 -29
  2. package/.github/workflows/ci.yml +26 -26
  3. package/.github/workflows/gh-pages-main.yml +39 -39
  4. package/.github/workflows/npm-publish.yml +39 -39
  5. package/.github/workflows/pr-preview.yml +38 -38
  6. package/.husky/pre-commit +4 -4
  7. package/LICENSE +661 -661
  8. package/README.md +83 -83
  9. package/dist/index.d.ts +9 -9
  10. package/dist/index.js +9 -9
  11. package/dist/src/app-root.d.ts +64 -54
  12. package/dist/src/app-root.js +320 -293
  13. package/dist/src/app-root.js.map +1 -1
  14. package/dist/src/assets/img/icons/arrow-left.d.ts +2 -2
  15. package/dist/src/assets/img/icons/arrow-left.js +2 -2
  16. package/dist/src/assets/img/icons/arrow-right.d.ts +2 -2
  17. package/dist/src/assets/img/icons/arrow-right.js +2 -2
  18. package/dist/src/assets/img/icons/chevron.d.ts +2 -2
  19. package/dist/src/assets/img/icons/chevron.js +2 -2
  20. package/dist/src/assets/img/icons/contract.d.ts +2 -2
  21. package/dist/src/assets/img/icons/contract.js +2 -2
  22. package/dist/src/assets/img/icons/empty-query.d.ts +2 -2
  23. package/dist/src/assets/img/icons/empty-query.js +2 -2
  24. package/dist/src/assets/img/icons/expand.d.ts +2 -2
  25. package/dist/src/assets/img/icons/expand.js +2 -2
  26. package/dist/src/assets/img/icons/eye-closed.d.ts +2 -2
  27. package/dist/src/assets/img/icons/eye-closed.js +2 -2
  28. package/dist/src/assets/img/icons/eye.d.ts +2 -2
  29. package/dist/src/assets/img/icons/eye.js +2 -2
  30. package/dist/src/assets/img/icons/favorite-filled.d.ts +1 -1
  31. package/dist/src/assets/img/icons/favorite-filled.js +2 -2
  32. package/dist/src/assets/img/icons/login-required.d.ts +1 -1
  33. package/dist/src/assets/img/icons/login-required.js +2 -2
  34. package/dist/src/assets/img/icons/mediatype/account.d.ts +1 -1
  35. package/dist/src/assets/img/icons/mediatype/account.js +2 -2
  36. package/dist/src/assets/img/icons/mediatype/audio.d.ts +1 -1
  37. package/dist/src/assets/img/icons/mediatype/audio.js +2 -2
  38. package/dist/src/assets/img/icons/mediatype/collection.d.ts +1 -1
  39. package/dist/src/assets/img/icons/mediatype/collection.js +2 -2
  40. package/dist/src/assets/img/icons/mediatype/data.d.ts +1 -1
  41. package/dist/src/assets/img/icons/mediatype/data.js +2 -2
  42. package/dist/src/assets/img/icons/mediatype/etree.d.ts +1 -1
  43. package/dist/src/assets/img/icons/mediatype/etree.js +2 -2
  44. package/dist/src/assets/img/icons/mediatype/film.d.ts +1 -1
  45. package/dist/src/assets/img/icons/mediatype/film.js +2 -2
  46. package/dist/src/assets/img/icons/mediatype/images.d.ts +1 -1
  47. package/dist/src/assets/img/icons/mediatype/images.js +2 -2
  48. package/dist/src/assets/img/icons/mediatype/radio.d.ts +1 -1
  49. package/dist/src/assets/img/icons/mediatype/radio.js +2 -2
  50. package/dist/src/assets/img/icons/mediatype/software.d.ts +1 -1
  51. package/dist/src/assets/img/icons/mediatype/software.js +2 -2
  52. package/dist/src/assets/img/icons/mediatype/texts.d.ts +1 -1
  53. package/dist/src/assets/img/icons/mediatype/texts.js +2 -2
  54. package/dist/src/assets/img/icons/mediatype/tv.d.ts +1 -1
  55. package/dist/src/assets/img/icons/mediatype/tv.js +2 -2
  56. package/dist/src/assets/img/icons/mediatype/video.d.ts +1 -1
  57. package/dist/src/assets/img/icons/mediatype/video.js +2 -2
  58. package/dist/src/assets/img/icons/mediatype/web.d.ts +1 -1
  59. package/dist/src/assets/img/icons/mediatype/web.js +2 -2
  60. package/dist/src/assets/img/icons/null-result.d.ts +2 -2
  61. package/dist/src/assets/img/icons/null-result.js +2 -2
  62. package/dist/src/assets/img/icons/restricted.d.ts +1 -1
  63. package/dist/src/assets/img/icons/restricted.js +2 -2
  64. package/dist/src/assets/img/icons/reviews.d.ts +1 -1
  65. package/dist/src/assets/img/icons/reviews.js +2 -2
  66. package/dist/src/assets/img/icons/upload.d.ts +1 -1
  67. package/dist/src/assets/img/icons/upload.js +2 -2
  68. package/dist/src/assets/img/icons/views.d.ts +1 -1
  69. package/dist/src/assets/img/icons/views.js +2 -2
  70. package/dist/src/circular-activity-indicator.d.ts +5 -5
  71. package/dist/src/circular-activity-indicator.js +17 -17
  72. package/dist/src/collection-browser.d.ts +522 -473
  73. package/dist/src/collection-browser.js +1846 -1697
  74. package/dist/src/collection-browser.js.map +1 -1
  75. package/dist/src/collection-facets/facet-tombstone-row.d.ts +5 -5
  76. package/dist/src/collection-facets/facet-tombstone-row.js +15 -15
  77. package/dist/src/collection-facets/facets-template.d.ts +20 -20
  78. package/dist/src/collection-facets/facets-template.js +152 -152
  79. package/dist/src/collection-facets/more-facets-content.d.ts +77 -77
  80. package/dist/src/collection-facets/more-facets-content.js +359 -359
  81. package/dist/src/collection-facets/more-facets-pagination.d.ts +36 -36
  82. package/dist/src/collection-facets/more-facets-pagination.js +196 -196
  83. package/dist/src/collection-facets/toggle-switch.d.ts +41 -41
  84. package/dist/src/collection-facets/toggle-switch.js +94 -94
  85. package/dist/src/collection-facets.d.ts +104 -103
  86. package/dist/src/collection-facets.js +511 -498
  87. package/dist/src/collection-facets.js.map +1 -1
  88. package/dist/src/empty-placeholder.d.ts +23 -23
  89. package/dist/src/empty-placeholder.js +74 -74
  90. package/dist/src/expanded-date-picker.d.ts +43 -43
  91. package/dist/src/expanded-date-picker.js +109 -109
  92. package/dist/src/language-code-handler/language-code-handler.d.ts +37 -37
  93. package/dist/src/language-code-handler/language-code-handler.js +26 -26
  94. package/dist/src/language-code-handler/language-code-mapping.d.ts +1 -1
  95. package/dist/src/language-code-handler/language-code-mapping.js +562 -562
  96. package/dist/src/manage/manage-bar.d.ts +26 -0
  97. package/dist/src/manage/manage-bar.js +147 -0
  98. package/dist/src/manage/manage-bar.js.map +1 -0
  99. package/dist/src/mediatype/mediatype-config.d.ts +3 -3
  100. package/dist/src/mediatype/mediatype-config.js +85 -85
  101. package/dist/src/models.d.ts +164 -163
  102. package/dist/src/models.js +269 -269
  103. package/dist/src/models.js.map +1 -1
  104. package/dist/src/restoration-state-handler.d.ts +70 -70
  105. package/dist/src/restoration-state-handler.js +355 -355
  106. package/dist/src/sort-filter-bar/alpha-bar-tooltip.d.ts +6 -6
  107. package/dist/src/sort-filter-bar/alpha-bar-tooltip.js +24 -24
  108. package/dist/src/sort-filter-bar/alpha-bar.d.ts +21 -21
  109. package/dist/src/sort-filter-bar/alpha-bar.js +128 -128
  110. package/dist/src/sort-filter-bar/img/compact.d.ts +1 -1
  111. package/dist/src/sort-filter-bar/img/compact.js +2 -2
  112. package/dist/src/sort-filter-bar/img/list.d.ts +1 -1
  113. package/dist/src/sort-filter-bar/img/list.js +2 -2
  114. package/dist/src/sort-filter-bar/img/sort-toggle-disabled.d.ts +1 -1
  115. package/dist/src/sort-filter-bar/img/sort-toggle-disabled.js +2 -2
  116. package/dist/src/sort-filter-bar/img/sort-toggle-down.d.ts +1 -1
  117. package/dist/src/sort-filter-bar/img/sort-toggle-down.js +2 -2
  118. package/dist/src/sort-filter-bar/img/sort-toggle-up.d.ts +1 -1
  119. package/dist/src/sort-filter-bar/img/sort-toggle-up.js +2 -2
  120. package/dist/src/sort-filter-bar/img/sort-triangle.d.ts +1 -1
  121. package/dist/src/sort-filter-bar/img/sort-triangle.js +2 -2
  122. package/dist/src/sort-filter-bar/img/tile.d.ts +1 -1
  123. package/dist/src/sort-filter-bar/img/tile.js +2 -2
  124. package/dist/src/sort-filter-bar/sort-filter-bar.d.ts +208 -208
  125. package/dist/src/sort-filter-bar/sort-filter-bar.js +637 -637
  126. package/dist/src/styles/item-image-styles.d.ts +8 -8
  127. package/dist/src/styles/item-image-styles.js +9 -9
  128. package/dist/src/styles/sr-only.d.ts +1 -1
  129. package/dist/src/styles/sr-only.js +2 -2
  130. package/dist/src/tiles/base-tile-component.d.ts +18 -18
  131. package/dist/src/tiles/base-tile-component.js +59 -59
  132. package/dist/src/tiles/collection-browser-loading-tile.d.ts +5 -5
  133. package/dist/src/tiles/collection-browser-loading-tile.js +15 -15
  134. package/dist/src/tiles/grid/account-tile.d.ts +18 -18
  135. package/dist/src/tiles/grid/account-tile.js +72 -72
  136. package/dist/src/tiles/grid/collection-tile.d.ts +15 -15
  137. package/dist/src/tiles/grid/collection-tile.js +80 -80
  138. package/dist/src/tiles/grid/item-tile.d.ts +27 -27
  139. package/dist/src/tiles/grid/item-tile.js +134 -134
  140. package/dist/src/tiles/grid/styles/tile-grid-shared-styles.d.ts +1 -1
  141. package/dist/src/tiles/grid/styles/tile-grid-shared-styles.js +8 -8
  142. package/dist/src/tiles/grid/tile-stats.d.ts +11 -11
  143. package/dist/src/tiles/grid/tile-stats.js +48 -48
  144. package/dist/src/tiles/hover/hover-pane-controller.d.ts +219 -219
  145. package/dist/src/tiles/hover/hover-pane-controller.js +352 -352
  146. package/dist/src/tiles/hover/tile-hover-pane.d.ts +15 -15
  147. package/dist/src/tiles/hover/tile-hover-pane.js +38 -38
  148. package/dist/src/tiles/image-block.d.ts +17 -17
  149. package/dist/src/tiles/image-block.js +72 -72
  150. package/dist/src/tiles/item-image.d.ts +35 -35
  151. package/dist/src/tiles/item-image.js +117 -117
  152. package/dist/src/tiles/list/tile-list-compact-header.d.ts +6 -6
  153. package/dist/src/tiles/list/tile-list-compact-header.js +38 -38
  154. package/dist/src/tiles/list/tile-list-compact.d.ts +15 -15
  155. package/dist/src/tiles/list/tile-list-compact.js +114 -114
  156. package/dist/src/tiles/list/tile-list.d.ts +46 -46
  157. package/dist/src/tiles/list/tile-list.js +298 -298
  158. package/dist/src/tiles/mediatype-icon.d.ts +9 -9
  159. package/dist/src/tiles/mediatype-icon.js +47 -47
  160. package/dist/src/tiles/overlay/icon-overlay.d.ts +10 -10
  161. package/dist/src/tiles/overlay/icon-overlay.js +40 -40
  162. package/dist/src/tiles/overlay/icon-text-overlay.d.ts +9 -9
  163. package/dist/src/tiles/overlay/icon-text-overlay.js +38 -38
  164. package/dist/src/tiles/overlay/text-overlay.d.ts +10 -10
  165. package/dist/src/tiles/overlay/text-overlay.js +42 -42
  166. package/dist/src/tiles/text-snippet-block.d.ts +27 -27
  167. package/dist/src/tiles/text-snippet-block.js +73 -73
  168. package/dist/src/tiles/tile-dispatcher.d.ts +63 -50
  169. package/dist/src/tiles/tile-dispatcher.js +255 -187
  170. package/dist/src/tiles/tile-dispatcher.js.map +1 -1
  171. package/dist/src/tiles/tile-display-value-provider.d.ts +43 -43
  172. package/dist/src/tiles/tile-display-value-provider.js +80 -80
  173. package/dist/src/utils/analytics-events.d.ts +25 -25
  174. package/dist/src/utils/analytics-events.js +27 -27
  175. package/dist/src/utils/array-equals.d.ts +4 -4
  176. package/dist/src/utils/array-equals.js +10 -10
  177. package/dist/src/utils/format-count.d.ts +7 -7
  178. package/dist/src/utils/format-count.js +76 -76
  179. package/dist/src/utils/format-date.d.ts +2 -2
  180. package/dist/src/utils/format-date.js +25 -25
  181. package/dist/src/utils/format-unit-size.d.ts +2 -2
  182. package/dist/src/utils/format-unit-size.js +33 -33
  183. package/dist/src/utils/local-date-from-utc.d.ts +9 -9
  184. package/dist/src/utils/local-date-from-utc.js +15 -15
  185. package/dist/src/utils/sha1.d.ts +2 -2
  186. package/dist/src/utils/sha1.js +8 -8
  187. package/dist/test/collection-browser.test.d.ts +1 -1
  188. package/dist/test/collection-browser.test.js +1122 -979
  189. package/dist/test/collection-browser.test.js.map +1 -1
  190. package/dist/test/collection-facets/facets-template.test.d.ts +1 -1
  191. package/dist/test/collection-facets/facets-template.test.js +134 -134
  192. package/dist/test/collection-facets/more-facets-content.test.d.ts +1 -1
  193. package/dist/test/collection-facets/more-facets-content.test.js +133 -133
  194. package/dist/test/collection-facets/more-facets-pagination.test.d.ts +1 -1
  195. package/dist/test/collection-facets/more-facets-pagination.test.js +117 -117
  196. package/dist/test/collection-facets/toggle-switch.test.d.ts +1 -1
  197. package/dist/test/collection-facets/toggle-switch.test.js +73 -73
  198. package/dist/test/collection-facets.test.d.ts +2 -2
  199. package/dist/test/collection-facets.test.js +682 -682
  200. package/dist/test/empty-placeholder.test.d.ts +1 -1
  201. package/dist/test/empty-placeholder.test.js +63 -63
  202. package/dist/test/expanded-date-picker.test.d.ts +1 -1
  203. package/dist/test/expanded-date-picker.test.js +95 -95
  204. package/dist/test/icon-overlay.test.d.ts +1 -1
  205. package/dist/test/icon-overlay.test.js +24 -24
  206. package/dist/test/image-block.test.d.ts +1 -1
  207. package/dist/test/image-block.test.js +48 -48
  208. package/dist/test/item-image.test.d.ts +1 -1
  209. package/dist/test/item-image.test.js +86 -84
  210. package/dist/test/item-image.test.js.map +1 -1
  211. package/dist/test/manage/manage-bar.test.d.ts +1 -0
  212. package/dist/test/manage/manage-bar.test.js +73 -0
  213. package/dist/test/manage/manage-bar.test.js.map +1 -0
  214. package/dist/test/mediatype-config.test.d.ts +1 -1
  215. package/dist/test/mediatype-config.test.js +16 -16
  216. package/dist/test/mocks/mock-analytics-handler.d.ts +10 -10
  217. package/dist/test/mocks/mock-analytics-handler.js +15 -15
  218. package/dist/test/mocks/mock-collection-name-cache.d.ts +9 -9
  219. package/dist/test/mocks/mock-collection-name-cache.js +17 -17
  220. package/dist/test/mocks/mock-search-responses.d.ts +21 -21
  221. package/dist/test/mocks/mock-search-responses.js +709 -707
  222. package/dist/test/mocks/mock-search-responses.js.map +1 -1
  223. package/dist/test/mocks/mock-search-service.d.ts +15 -15
  224. package/dist/test/mocks/mock-search-service.js +50 -50
  225. package/dist/test/restoration-state-handler.test.d.ts +1 -1
  226. package/dist/test/restoration-state-handler.test.js +270 -270
  227. package/dist/test/sort-filter-bar/alpha-bar-tooltip.test.d.ts +1 -1
  228. package/dist/test/sort-filter-bar/alpha-bar-tooltip.test.js +12 -12
  229. package/dist/test/sort-filter-bar/alpha-bar.test.d.ts +1 -1
  230. package/dist/test/sort-filter-bar/alpha-bar.test.js +73 -73
  231. package/dist/test/sort-filter-bar/sort-filter-bar.test.d.ts +1 -1
  232. package/dist/test/sort-filter-bar/sort-filter-bar.test.js +378 -378
  233. package/dist/test/text-overlay.test.d.ts +1 -1
  234. package/dist/test/text-overlay.test.js +48 -48
  235. package/dist/test/text-snippet-block.test.d.ts +1 -1
  236. package/dist/test/text-snippet-block.test.js +57 -57
  237. package/dist/test/tile-stats.test.d.ts +1 -1
  238. package/dist/test/tile-stats.test.js +33 -33
  239. package/dist/test/tiles/grid/account-tile.test.d.ts +1 -1
  240. package/dist/test/tiles/grid/account-tile.test.js +76 -76
  241. package/dist/test/tiles/grid/collection-tile.test.d.ts +1 -1
  242. package/dist/test/tiles/grid/collection-tile.test.js +73 -73
  243. package/dist/test/tiles/grid/item-tile.test.d.ts +1 -1
  244. package/dist/test/tiles/grid/item-tile.test.js +254 -254
  245. package/dist/test/tiles/hover/hover-pane-controller.test.d.ts +1 -1
  246. package/dist/test/tiles/hover/hover-pane-controller.test.js +258 -257
  247. package/dist/test/tiles/hover/hover-pane-controller.test.js.map +1 -1
  248. package/dist/test/tiles/hover/tile-hover-pane.test.d.ts +1 -1
  249. package/dist/test/tiles/hover/tile-hover-pane.test.js +13 -13
  250. package/dist/test/tiles/list/tile-list-compact.test.d.ts +1 -1
  251. package/dist/test/tiles/list/tile-list-compact.test.js +143 -143
  252. package/dist/test/tiles/list/tile-list.test.d.ts +1 -1
  253. package/dist/test/tiles/list/tile-list.test.js +242 -242
  254. package/dist/test/tiles/tile-dispatcher.test.d.ts +1 -1
  255. package/dist/test/tiles/tile-dispatcher.test.js +107 -67
  256. package/dist/test/tiles/tile-dispatcher.test.js.map +1 -1
  257. package/dist/test/tiles/tile-display-value-provider.test.d.ts +1 -1
  258. package/dist/test/tiles/tile-display-value-provider.test.js +141 -141
  259. package/dist/test/utils/array-equals.test.d.ts +1 -1
  260. package/dist/test/utils/array-equals.test.js +26 -26
  261. package/dist/test/utils/format-count.test.d.ts +1 -1
  262. package/dist/test/utils/format-count.test.js +23 -23
  263. package/dist/test/utils/format-date.test.d.ts +1 -1
  264. package/dist/test/utils/format-date.test.js +17 -17
  265. package/dist/test/utils/format-unit-size.test.d.ts +1 -1
  266. package/dist/test/utils/format-unit-size.test.js +17 -17
  267. package/dist/test/utils/local-date-from-utc.test.d.ts +1 -1
  268. package/dist/test/utils/local-date-from-utc.test.js +26 -26
  269. package/local.archive.org.cert +86 -86
  270. package/local.archive.org.key +27 -27
  271. package/package.json +2 -2
  272. package/renovate.json +6 -6
  273. package/src/app-root.ts +29 -0
  274. package/src/collection-browser.ts +197 -23
  275. package/src/collection-facets.ts +13 -1
  276. package/src/manage/manage-bar.ts +151 -0
  277. package/src/models.ts +1 -0
  278. package/src/tiles/tile-dispatcher.ts +71 -5
  279. package/test/collection-browser.test.ts +198 -1
  280. package/test/item-image.test.ts +2 -0
  281. package/test/manage/manage-bar.test.ts +107 -0
  282. package/test/mocks/mock-search-responses.ts +2 -0
  283. package/test/tiles/hover/hover-pane-controller.test.ts +1 -0
  284. package/test/tiles/tile-dispatcher.test.ts +52 -0
  285. package/tsconfig.json +21 -21
  286. package/web-dev-server.config.mjs +30 -30
  287. package/web-test-runner.config.mjs +41 -41
@@ -1,291 +1,297 @@
1
- import { __decorate } from "tslib";
2
- /* eslint-disable import/no-duplicates */
3
- import { html, css, LitElement, nothing, } from 'lit';
4
- import { customElement, property, query, state } from 'lit/decorators.js';
5
- import { classMap } from 'lit/directives/class-map.js';
6
- import { FilterConstraint, FilterMapBuilder, SearchType, } from '@internetarchive/search-service';
7
- import '@internetarchive/infinite-scroller';
8
- import './tiles/tile-dispatcher';
9
- import './tiles/collection-browser-loading-tile';
10
- import './sort-filter-bar/sort-filter-bar';
11
- import './collection-facets';
12
- import './circular-activity-indicator';
13
- import './sort-filter-bar/sort-filter-bar';
14
- import { SortField, getDefaultSelectedFacets, prefixFilterAggregationKeys, sortOptionFromAPIString, SORT_OPTIONS, } from './models';
15
- import { RestorationStateHandler, } from './restoration-state-handler';
16
- import chevronIcon from './assets/img/icons/chevron';
17
- import './empty-placeholder';
18
- import { analyticsActions, analyticsCategories, } from './utils/analytics-events';
19
- import { srOnlyStyle } from './styles/sr-only';
20
- import { sha1 } from './utils/sha1';
21
- let CollectionBrowser = class CollectionBrowser extends LitElement {
22
- constructor() {
23
- super(...arguments);
24
- this.baseImageUrl = 'https://archive.org';
25
- this.searchType = SearchType.METADATA;
26
- this.sortParam = null;
27
- this.selectedSort = SortField.default;
28
- this.selectedTitleFilter = null;
29
- this.selectedCreatorFilter = null;
30
- this.sortDirection = null;
31
- this.pageSize = 50;
32
- this.showHistogramDatePicker = false;
33
- this.collectionPagePath = '/details/';
34
- this.parentCollections = [];
35
- /** describes where this component is being used */
36
- this.searchContext = analyticsCategories.default;
37
- this.pageContext = 'search';
38
- this.restorationStateHandler = new RestorationStateHandler({
39
- context: this.pageContext,
40
- });
41
- this.mobileBreakpoint = 600;
42
- this.loggedIn = false;
43
- this.modalManager = undefined;
44
- /**
45
- * If item management UI active
46
- */
47
- this.isManageView = false;
48
- /**
49
- * The page that the consumer wants to load.
50
- */
51
- this.initialPageNumber = 1;
52
- /**
53
- * This the the number of pages that we want to show.
54
- *
55
- * The data isn't necessarily loaded for all of the pages, but this lets us
56
- * know how many cells we should render.
57
- */
58
- this.pagesToRender = this.initialPageNumber;
59
- /**
60
- * Whether the initial page fetch for a new query is currently in progress.
61
- */
62
- this.searchResultsLoading = false;
63
- this.facetsLoading = false;
64
- this.fullYearAggregationLoading = false;
65
- this.mobileView = false;
66
- this.mobileFacetsVisible = false;
67
- this.defaultSortField = SortField.relevance;
68
- this.defaultSortDirection = null;
69
- this.placeholderType = null;
70
- this.prefixFilterCountMap = {};
71
- /**
72
- * When we're animated scrolling to the page, we don't want to fetch
73
- * all of the pages as it scrolls so this lets us know if we're scrolling
74
- */
75
- this.isScrollingToCell = false;
76
- /**
77
- * When we've reached the end of the data, stop trying to fetch more
78
- */
79
- this.endOfDataReached = false;
80
- /**
81
- * When page width resizes from desktop to mobile, set true to
82
- * disable expand/collapse transition when loading.
83
- */
84
- this.isResizeToMobile = false;
85
- this.placeholderCellTemplate = html `<collection-browser-loading-tile></collection-browser-loading-tile>`;
86
- /**
87
- * The results per page so we can paginate.
88
- *
89
- * This allows us to start in the middle of the search results and
90
- * fetch data before or after the current page. If we don't have a key
91
- * for the previous/next page, we'll fetch the next/previous page to populate it
92
- */
93
- this.dataSource = {};
94
- /**
95
- * Updates the height of the left column according to its position on the page.
96
- * Arrow function ensures proper `this` binding.
97
- */
98
- this.updateLeftColumnHeight = () => {
99
- var _a, _b, _c, _d, _e;
100
- if (this.mobileView) {
101
- (_b = (_a = this.leftColumn) === null || _a === void 0 ? void 0 : _a.style) === null || _b === void 0 ? void 0 : _b.removeProperty('height');
102
- }
103
- else {
104
- const clientTop = (_c = this.leftColumn) === null || _c === void 0 ? void 0 : _c.getBoundingClientRect().top;
105
- (_e = (_d = this.leftColumn) === null || _d === void 0 ? void 0 : _d.style) === null || _e === void 0 ? void 0 : _e.setProperty('height', `${window.innerHeight - (clientTop !== null && clientTop !== void 0 ? clientTop : 0) - 3}px`);
106
- }
107
- };
108
- /**
109
- * Toggles whether the fade-out is visible at the bottom of the facets.
110
- * It should only be visible if the facets are not scrolled to the bottom.
111
- * Arrow function ensures proper `this` binding.
112
- */
113
- this.updateFacetFadeOut = (entries) => {
114
- var _a, _b;
115
- const fadeElmt = (_a = this.shadowRoot) === null || _a === void 0 ? void 0 : _a.getElementById('facets-bottom-fade');
116
- fadeElmt === null || fadeElmt === void 0 ? void 0 : fadeElmt.classList.toggle('hidden', (_b = entries === null || entries === void 0 ? void 0 : entries[0]) === null || _b === void 0 ? void 0 : _b.isIntersecting);
117
- };
118
- // we only want to scroll on the very first query change
119
- // so this keeps track of whether we've already set the initial query
120
- this.initialQueryChangeHappened = false;
121
- this.historyPopOccurred = false;
122
- /**
123
- * Internal property to store the private value backing the `initialSearchComplete` getter.
124
- */
125
- this._initialSearchCompletePromise = new Promise(res => {
126
- this._initialSearchCompleteResolver = res;
127
- });
128
- // this maps the query to the pages being fetched for that query
129
- this.pageFetchesInProgress = {};
130
- }
131
- tileModelAtCellIndex(index) {
132
- var _a;
133
- const pageNumber = Math.floor(index / this.pageSize) + 1;
134
- const itemIndex = index % this.pageSize;
135
- const model = (_a = this.dataSource[pageNumber]) === null || _a === void 0 ? void 0 : _a[itemIndex];
136
- /**
137
- * If we encounter a model we don't have yet and we're not in the middle of an
138
- * automated scroll, fetch the page and just return undefined.
139
- * The datasource will be updated once the page is loaded and the cell will be rendered.
140
- *
141
- * We disable it during the automated scroll since we may fetch pages for cells the
142
- * user may never see.
143
- */
144
- if (!model && !this.isScrollingToCell) {
145
- this.fetchPage(pageNumber);
146
- }
147
- return model;
148
- }
149
- get sortFilterQueries() {
150
- const queries = [this.titleQuery, this.creatorQuery];
151
- return queries.filter(q => q).join(' AND ');
152
- }
153
- // this is the total number of tiles we expect if
154
- // the data returned is a full page worth
155
- // this is useful for putting in placeholders for the expected number of tiles
156
- get estimatedTileCount() {
157
- return this.pagesToRender * this.pageSize;
158
- }
159
- /**
160
- * Returns a promise resolving to a unique string that persists for the current browser session.
161
- * Used in generating unique IDs for search requests, so that multiple requests coming from the
162
- * same browser session can be identified.
163
- */
164
- async getSessionId() {
165
- try {
166
- const storedSessionId = sessionStorage === null || sessionStorage === void 0 ? void 0 : sessionStorage.getItem('cb-session');
167
- if (storedSessionId) {
168
- return storedSessionId;
169
- }
170
- // If we enter this method a second time while a first session ID is already being generated,
171
- // ensure we produce the same ID from both calls instead of generating another one.
172
- if (this.sessionIdGenPromise) {
173
- return this.sessionIdGenPromise;
174
- }
175
- this.sessionIdGenPromise = sha1(Math.random().toString());
176
- const newSessionId = await this.sessionIdGenPromise;
177
- sessionStorage === null || sessionStorage === void 0 ? void 0 : sessionStorage.setItem('cb-session', newSessionId);
178
- return newSessionId;
179
- }
180
- catch (err) {
181
- // Either we can't generate the hash or we're restricted from accessing sessionStorage
182
- return '';
183
- }
184
- }
185
- /**
186
- * Go to the given page of results
187
- *
188
- * @param pageNumber
189
- */
190
- goToPage(pageNumber) {
191
- this.initialPageNumber = pageNumber;
192
- this.pagesToRender = pageNumber;
193
- return this.scrollToPage(pageNumber);
194
- }
195
- /**
196
- * Clears all selected/negated facets, date ranges, and letter filters.
197
- *
198
- * By default, the current sort field/direction are not cleared,
199
- * but this can be overridden by setting the `sort` option to `true`.
200
- *
201
- * Similarly, it is possible to finely control what is cleared by
202
- * setting any of the `facets`, `dateRange`, or `letterFilters` flags
203
- * in the options object.
204
- */
205
- clearFilters({ facets = true, dateRange = true, letterFilters = true, sort = false, } = {}) {
206
- // Don't bother clearing facets if none are checked, so that we don't
207
- // trigger unnecessary update cycles.
208
- if (facets && this.hasCheckedFacets) {
209
- this.selectedFacets = getDefaultSelectedFacets();
210
- }
211
- if (dateRange) {
212
- this.minSelectedDate = undefined;
213
- this.maxSelectedDate = undefined;
214
- }
215
- if (letterFilters) {
216
- this.selectedTitleFilter = null;
217
- this.selectedCreatorFilter = null;
218
- }
219
- if (sort) {
220
- this.sortParam = null;
221
- this.sortDirection = null;
222
- this.selectedSort = SortField.default;
223
- }
224
- }
225
- /**
226
- * Returns true if the current value of `this.selectedFacets` contains
227
- * any facet buckets than have been selected or negated, or false otherwise.
228
- */
229
- get hasCheckedFacets() {
230
- if (!this.selectedFacets)
231
- return false;
232
- for (const facetGroup of Object.values(this.selectedFacets)) {
233
- for (const bucket of Object.values(facetGroup)) {
234
- if (bucket.state !== 'none')
235
- return true;
236
- }
237
- }
238
- return false;
239
- }
240
- /**
241
- * Returns true if there are any currently selected/negated facet buckets,
242
- * any selected date range, or any selected letter filters. False otherwise.
243
- *
244
- * Ignores sorting options.
245
- */
246
- get hasActiveFilters() {
247
- return !!(this.hasCheckedFacets ||
248
- this.minSelectedDate ||
249
- this.maxSelectedDate ||
250
- this.selectedTitleFilter ||
251
- this.selectedCreatorFilter);
252
- }
253
- render() {
254
- this.setPlaceholderType();
1
+ import { __decorate } from "tslib";
2
+ /* eslint-disable import/no-duplicates */
3
+ import { html, css, LitElement, nothing, } from 'lit';
4
+ import { customElement, property, query, state } from 'lit/decorators.js';
5
+ import { classMap } from 'lit/directives/class-map.js';
6
+ import { FilterConstraint, FilterMapBuilder, SearchType, } from '@internetarchive/search-service';
7
+ import '@internetarchive/infinite-scroller';
8
+ import './tiles/tile-dispatcher';
9
+ import './tiles/collection-browser-loading-tile';
10
+ import './sort-filter-bar/sort-filter-bar';
11
+ import './manage/manage-bar';
12
+ import './collection-facets';
13
+ import './circular-activity-indicator';
14
+ import { SortField, getDefaultSelectedFacets, prefixFilterAggregationKeys, sortOptionFromAPIString, SORT_OPTIONS, } from './models';
15
+ import { RestorationStateHandler, } from './restoration-state-handler';
16
+ import chevronIcon from './assets/img/icons/chevron';
17
+ import './empty-placeholder';
18
+ import { analyticsActions, analyticsCategories, } from './utils/analytics-events';
19
+ import { srOnlyStyle } from './styles/sr-only';
20
+ import { sha1 } from './utils/sha1';
21
+ import { formatDate } from './utils/format-date';
22
+ let CollectionBrowser = class CollectionBrowser extends LitElement {
23
+ constructor() {
24
+ super(...arguments);
25
+ this.baseImageUrl = 'https://archive.org';
26
+ this.searchType = SearchType.METADATA;
27
+ this.sortParam = null;
28
+ this.selectedSort = SortField.default;
29
+ this.selectedTitleFilter = null;
30
+ this.selectedCreatorFilter = null;
31
+ this.sortDirection = null;
32
+ this.pageSize = 50;
33
+ this.showHistogramDatePicker = false;
34
+ this.collectionPagePath = '/details/';
35
+ this.parentCollections = [];
36
+ /** describes where this component is being used */
37
+ this.searchContext = analyticsCategories.default;
38
+ this.pageContext = 'search';
39
+ this.restorationStateHandler = new RestorationStateHandler({
40
+ context: this.pageContext,
41
+ });
42
+ this.mobileBreakpoint = 600;
43
+ this.loggedIn = false;
44
+ this.modalManager = undefined;
45
+ /**
46
+ * If item management UI active
47
+ */
48
+ this.isManageView = false;
49
+ /**
50
+ * The page that the consumer wants to load.
51
+ */
52
+ this.initialPageNumber = 1;
53
+ /**
54
+ * This the the number of pages that we want to show.
55
+ *
56
+ * The data isn't necessarily loaded for all of the pages, but this lets us
57
+ * know how many cells we should render.
58
+ */
59
+ this.pagesToRender = this.initialPageNumber;
60
+ /**
61
+ * Whether the initial page fetch for a new query is currently in progress.
62
+ */
63
+ this.searchResultsLoading = false;
64
+ this.facetsLoading = false;
65
+ this.fullYearAggregationLoading = false;
66
+ this.mobileView = false;
67
+ this.mobileFacetsVisible = false;
68
+ this.defaultSortField = SortField.relevance;
69
+ this.defaultSortDirection = null;
70
+ this.placeholderType = null;
71
+ this.prefixFilterCountMap = {};
72
+ /**
73
+ * When we're animated scrolling to the page, we don't want to fetch
74
+ * all of the pages as it scrolls so this lets us know if we're scrolling
75
+ */
76
+ this.isScrollingToCell = false;
77
+ /**
78
+ * When we've reached the end of the data, stop trying to fetch more
79
+ */
80
+ this.endOfDataReached = false;
81
+ /**
82
+ * When page width resizes from desktop to mobile, set true to
83
+ * disable expand/collapse transition when loading.
84
+ */
85
+ this.isResizeToMobile = false;
86
+ this.placeholderCellTemplate = html `<collection-browser-loading-tile></collection-browser-loading-tile>`;
87
+ /**
88
+ * The results per page so we can paginate.
89
+ *
90
+ * This allows us to start in the middle of the search results and
91
+ * fetch data before or after the current page. If we don't have a key
92
+ * for the previous/next page, we'll fetch the next/previous page to populate it
93
+ */
94
+ this.dataSource = {};
95
+ /**
96
+ * How many tiles to offset the data source by, to account for any removed tiles.
97
+ */
98
+ this.tileModelOffset = 0;
99
+ /**
100
+ * Updates the height of the left column according to its position on the page.
101
+ * Arrow function ensures proper `this` binding.
102
+ */
103
+ this.updateLeftColumnHeight = () => {
104
+ var _a, _b, _c, _d, _e;
105
+ if (this.mobileView) {
106
+ (_b = (_a = this.leftColumn) === null || _a === void 0 ? void 0 : _a.style) === null || _b === void 0 ? void 0 : _b.removeProperty('height');
107
+ }
108
+ else {
109
+ const clientTop = (_c = this.leftColumn) === null || _c === void 0 ? void 0 : _c.getBoundingClientRect().top;
110
+ (_e = (_d = this.leftColumn) === null || _d === void 0 ? void 0 : _d.style) === null || _e === void 0 ? void 0 : _e.setProperty('height', `${window.innerHeight - (clientTop !== null && clientTop !== void 0 ? clientTop : 0) - 3}px`);
111
+ }
112
+ };
113
+ /**
114
+ * Toggles whether the fade-out is visible at the bottom of the facets.
115
+ * It should only be visible if the facets are not scrolled to the bottom.
116
+ * Arrow function ensures proper `this` binding.
117
+ */
118
+ this.updateFacetFadeOut = (entries) => {
119
+ var _a, _b;
120
+ const fadeElmt = (_a = this.shadowRoot) === null || _a === void 0 ? void 0 : _a.getElementById('facets-bottom-fade');
121
+ fadeElmt === null || fadeElmt === void 0 ? void 0 : fadeElmt.classList.toggle('hidden', (_b = entries === null || entries === void 0 ? void 0 : entries[0]) === null || _b === void 0 ? void 0 : _b.isIntersecting);
122
+ };
123
+ // we only want to scroll on the very first query change
124
+ // so this keeps track of whether we've already set the initial query
125
+ this.initialQueryChangeHappened = false;
126
+ this.historyPopOccurred = false;
127
+ /**
128
+ * Internal property to store the private value backing the `initialSearchComplete` getter.
129
+ */
130
+ this._initialSearchCompletePromise = new Promise(res => {
131
+ this._initialSearchCompleteResolver = res;
132
+ });
133
+ // this maps the query to the pages being fetched for that query
134
+ this.pageFetchesInProgress = {};
135
+ }
136
+ tileModelAtCellIndex(index) {
137
+ var _a;
138
+ const offsetIndex = index + this.tileModelOffset;
139
+ const pageNumber = Math.floor(offsetIndex / this.pageSize) + 1;
140
+ const itemIndex = offsetIndex % this.pageSize;
141
+ const model = (_a = this.dataSource[pageNumber]) === null || _a === void 0 ? void 0 : _a[itemIndex];
142
+ /**
143
+ * If we encounter a model we don't have yet and we're not in the middle of an
144
+ * automated scroll, fetch the page and just return undefined.
145
+ * The datasource will be updated once the page is loaded and the cell will be rendered.
146
+ *
147
+ * We disable it during the automated scroll since we may fetch pages for cells the
148
+ * user may never see.
149
+ */
150
+ if (!model && !this.isScrollingToCell) {
151
+ this.fetchPage(pageNumber);
152
+ }
153
+ return model;
154
+ }
155
+ get sortFilterQueries() {
156
+ const queries = [this.titleQuery, this.creatorQuery];
157
+ return queries.filter(q => q).join(' AND ');
158
+ }
159
+ // this is the total number of tiles we expect if
160
+ // the data returned is a full page worth
161
+ // this is useful for putting in placeholders for the expected number of tiles
162
+ get estimatedTileCount() {
163
+ return this.pagesToRender * this.pageSize;
164
+ }
165
+ /**
166
+ * Returns a promise resolving to a unique string that persists for the current browser session.
167
+ * Used in generating unique IDs for search requests, so that multiple requests coming from the
168
+ * same browser session can be identified.
169
+ */
170
+ async getSessionId() {
171
+ try {
172
+ const storedSessionId = sessionStorage === null || sessionStorage === void 0 ? void 0 : sessionStorage.getItem('cb-session');
173
+ if (storedSessionId) {
174
+ return storedSessionId;
175
+ }
176
+ // If we enter this method a second time while a first session ID is already being generated,
177
+ // ensure we produce the same ID from both calls instead of generating another one.
178
+ if (this.sessionIdGenPromise) {
179
+ return this.sessionIdGenPromise;
180
+ }
181
+ this.sessionIdGenPromise = sha1(Math.random().toString());
182
+ const newSessionId = await this.sessionIdGenPromise;
183
+ sessionStorage === null || sessionStorage === void 0 ? void 0 : sessionStorage.setItem('cb-session', newSessionId);
184
+ return newSessionId;
185
+ }
186
+ catch (err) {
187
+ // Either we can't generate the hash or we're restricted from accessing sessionStorage
188
+ return '';
189
+ }
190
+ }
191
+ /**
192
+ * Go to the given page of results
193
+ *
194
+ * @param pageNumber
195
+ */
196
+ goToPage(pageNumber) {
197
+ this.initialPageNumber = pageNumber;
198
+ this.pagesToRender = pageNumber;
199
+ return this.scrollToPage(pageNumber);
200
+ }
201
+ /**
202
+ * Clears all selected/negated facets, date ranges, and letter filters.
203
+ *
204
+ * By default, the current sort field/direction are not cleared,
205
+ * but this can be overridden by setting the `sort` option to `true`.
206
+ *
207
+ * Similarly, it is possible to finely control what is cleared by
208
+ * setting any of the `facets`, `dateRange`, or `letterFilters` flags
209
+ * in the options object.
210
+ */
211
+ clearFilters({ facets = true, dateRange = true, letterFilters = true, sort = false, } = {}) {
212
+ // Don't bother clearing facets if none are checked, so that we don't
213
+ // trigger unnecessary update cycles.
214
+ if (facets && this.hasCheckedFacets) {
215
+ this.selectedFacets = getDefaultSelectedFacets();
216
+ }
217
+ if (dateRange) {
218
+ this.minSelectedDate = undefined;
219
+ this.maxSelectedDate = undefined;
220
+ }
221
+ if (letterFilters) {
222
+ this.selectedTitleFilter = null;
223
+ this.selectedCreatorFilter = null;
224
+ }
225
+ if (sort) {
226
+ this.sortParam = null;
227
+ this.sortDirection = null;
228
+ this.selectedSort = SortField.default;
229
+ }
230
+ }
231
+ /**
232
+ * Returns true if the current value of `this.selectedFacets` contains
233
+ * any facet buckets than have been selected or negated, or false otherwise.
234
+ */
235
+ get hasCheckedFacets() {
236
+ if (!this.selectedFacets)
237
+ return false;
238
+ for (const facetGroup of Object.values(this.selectedFacets)) {
239
+ for (const bucket of Object.values(facetGroup)) {
240
+ if (bucket.state !== 'none')
241
+ return true;
242
+ }
243
+ }
244
+ return false;
245
+ }
246
+ /**
247
+ * Returns true if there are any currently selected/negated facet buckets,
248
+ * any selected date range, or any selected letter filters. False otherwise.
249
+ *
250
+ * Ignores sorting options.
251
+ */
252
+ get hasActiveFilters() {
253
+ return !!(this.hasCheckedFacets ||
254
+ this.minSelectedDate ||
255
+ this.maxSelectedDate ||
256
+ this.selectedTitleFilter ||
257
+ this.selectedCreatorFilter);
258
+ }
259
+ render() {
260
+ this.setPlaceholderType();
255
261
  return html `
256
262
  <div
257
263
  id="content-container"
258
264
  class=${this.mobileView ? 'mobile' : 'desktop'}
259
265
  >
260
- ${this.placeholderType
261
- ? this.emptyPlaceholderTemplate
266
+ ${this.placeholderType
267
+ ? this.emptyPlaceholderTemplate
262
268
  : this.collectionBrowserTemplate}
263
269
  </div>
264
- `;
265
- }
266
- setPlaceholderType() {
267
- var _a;
268
- const hasQuery = !!((_a = this.baseQuery) === null || _a === void 0 ? void 0 : _a.trim());
269
- const isCollection = !!this.withinCollection;
270
- const noResults = !this.searchResultsLoading &&
271
- (this.totalResults === 0 || !this.searchService);
272
- this.placeholderType = null;
273
- if (!hasQuery && !isCollection) {
274
- this.placeholderType = 'empty-query';
275
- }
276
- else if (noResults) {
277
- // Within a collection, no query + no results means the collection simply has no viewable items.
278
- // Otherwise, we must have a user query that produced 0 results.
279
- this.placeholderType =
280
- !hasQuery && isCollection ? 'empty-collection' : 'no-results';
281
- }
282
- if (this.queryErrorMessage) {
283
- this.placeholderType =
284
- !hasQuery && isCollection ? 'collection-error' : 'query-error';
285
- }
286
- }
287
- get emptyPlaceholderTemplate() {
288
- var _a;
270
+ `;
271
+ }
272
+ setPlaceholderType() {
273
+ var _a;
274
+ const hasQuery = !!((_a = this.baseQuery) === null || _a === void 0 ? void 0 : _a.trim());
275
+ const isCollection = !!this.withinCollection;
276
+ const noResults = !this.searchResultsLoading &&
277
+ (this.totalResults === 0 || !this.searchService);
278
+ this.placeholderType = null;
279
+ if (!hasQuery && !isCollection) {
280
+ this.placeholderType = 'empty-query';
281
+ }
282
+ else if (noResults) {
283
+ // Within a collection, no query + no results means the collection simply has no viewable items.
284
+ // Otherwise, we must have a user query that produced 0 results.
285
+ this.placeholderType =
286
+ !hasQuery && isCollection ? 'empty-collection' : 'no-results';
287
+ }
288
+ if (this.queryErrorMessage) {
289
+ this.placeholderType =
290
+ !hasQuery && isCollection ? 'collection-error' : 'query-error';
291
+ }
292
+ }
293
+ get emptyPlaceholderTemplate() {
294
+ var _a;
289
295
  return html `
290
296
  <empty-placeholder
291
297
  .placeholderType=${this.placeholderType}
@@ -295,33 +301,33 @@ let CollectionBrowser = class CollectionBrowser extends LitElement {
295
301
  .baseNavigationUrl=${this.baseNavigationUrl}
296
302
  ></empty-placeholder>
297
303
  ${this.infiniteScrollerTemplate}
298
- `;
299
- }
300
- /**
301
- * Top-level template for rendering the left (facets) and right (results) columns.
302
- */
303
- get collectionBrowserTemplate() {
304
+ `;
305
+ }
306
+ /**
307
+ * Top-level template for rendering the left (facets) and right (results) columns.
308
+ */
309
+ get collectionBrowserTemplate() {
304
310
  return html `
305
311
  <div id="left-column-scroll-sentinel"></div>
306
312
  ${this.leftColumnTemplate} ${this.rightColumnTemplate}
307
- `;
308
- }
309
- /**
310
- * Template for either the mobile or desktop version of the left column, depending
311
- * on current component state.
312
- */
313
- get leftColumnTemplate() {
314
- if (this.mobileView) {
315
- return this.mobileLeftColumnTemplate;
316
- }
317
- return this.desktopLeftColumnTemplate;
318
- }
319
- /**
320
- * Template for the mobile version of the "left column" (which in this case, appears
321
- * *above* the search results rather than beside them), for rendering the
322
- * accordion-style facets.
323
- */
324
- get mobileLeftColumnTemplate() {
313
+ `;
314
+ }
315
+ /**
316
+ * Template for either the mobile or desktop version of the left column, depending
317
+ * on current component state.
318
+ */
319
+ get leftColumnTemplate() {
320
+ if (this.mobileView) {
321
+ return this.mobileLeftColumnTemplate;
322
+ }
323
+ return this.desktopLeftColumnTemplate;
324
+ }
325
+ /**
326
+ * Template for the mobile version of the "left column" (which in this case, appears
327
+ * *above* the search results rather than beside them), for rendering the
328
+ * accordion-style facets.
329
+ */
330
+ get mobileLeftColumnTemplate() {
325
331
  return html `
326
332
  <div
327
333
  id="left-column"
@@ -330,12 +336,12 @@ let CollectionBrowser = class CollectionBrowser extends LitElement {
330
336
  ${this.resultsCountTemplate}
331
337
  <div id="facets-header-container">${this.mobileFacetsTemplate}</div>
332
338
  </div>
333
- `;
334
- }
335
- /**
336
- * Template for the desktop version of the left column, displaying the facets sidebar.
337
- */
338
- get desktopLeftColumnTemplate() {
339
+ `;
340
+ }
341
+ /**
342
+ * Template for the desktop version of the left column, displaying the facets sidebar.
343
+ */
344
+ get desktopLeftColumnTemplate() {
339
345
  return html `
340
346
  <div id="left-column" class="column">
341
347
  <div id="facets-header-container">
@@ -348,17 +354,17 @@ let CollectionBrowser = class CollectionBrowser extends LitElement {
348
354
  </div>
349
355
  <div id="facets-bottom-fade"></div>
350
356
  </div>
351
- `;
352
- }
353
- /**
354
- * Template for the "X Results" count at the top of the search results.
355
- * Changes to the "Searching..." label if the search results are still loading.
356
- */
357
- get resultsCountTemplate() {
358
- var _a;
359
- const shouldShowSearching = this.searchResultsLoading || this.totalResults === undefined;
360
- const resultsCount = (_a = this.totalResults) === null || _a === void 0 ? void 0 : _a.toLocaleString();
361
- const resultsLabel = this.totalResults === 1 ? 'Result' : 'Results';
357
+ `;
358
+ }
359
+ /**
360
+ * Template for the "X Results" count at the top of the search results.
361
+ * Changes to the "Searching..." label if the search results are still loading.
362
+ */
363
+ get resultsCountTemplate() {
364
+ var _a;
365
+ const shouldShowSearching = this.searchResultsLoading || this.totalResults === undefined;
366
+ const resultsCount = (_a = this.totalResults) === null || _a === void 0 ? void 0 : _a.toLocaleString();
367
+ const resultsLabel = this.totalResults === 1 ? 'Result' : 'Results';
362
368
  return html `
363
369
  <div id="results-total">
364
370
  <span id="big-results-count">
@@ -368,24 +374,26 @@ let CollectionBrowser = class CollectionBrowser extends LitElement {
368
374
  ${shouldShowSearching ? nothing : resultsLabel}
369
375
  </span>
370
376
  </div>
371
- `;
372
- }
373
- /**
374
- * Template for the right column of the collection browser, where the result
375
- * tiles and sort/filter bar are shown.
376
- */
377
- get rightColumnTemplate() {
377
+ `;
378
+ }
379
+ /**
380
+ * Template for the right column of the collection browser, where the result
381
+ * tiles and sort/filter bar are shown.
382
+ */
383
+ get rightColumnTemplate() {
378
384
  return html `
379
385
  <div id="right-column" class="column">
380
- ${this.sortFilterBarTemplate}
381
- ${this.displayMode === `list-compact`
382
- ? this.listHeaderTemplate
386
+ ${this.isManageView
387
+ ? this.manageBarTemplate
388
+ : this.sortFilterBarTemplate}
389
+ ${this.displayMode === `list-compact`
390
+ ? this.listHeaderTemplate
383
391
  : nothing}
384
392
  ${this.infiniteScrollerTemplate}
385
393
  </div>
386
- `;
387
- }
388
- get infiniteScrollerTemplate() {
394
+ `;
395
+ }
396
+ get infiniteScrollerTemplate() {
389
397
  return html `<infinite-scroller
390
398
  class=${this.infiniteScrollerClasses}
391
399
  itemCount=${this.placeholderType ? 0 : nothing}
@@ -394,17 +402,17 @@ let CollectionBrowser = class CollectionBrowser extends LitElement {
394
402
  .placeholderCellTemplate=${this.placeholderCellTemplate}
395
403
  @scrollThresholdReached=${this.scrollThresholdReached}
396
404
  @visibleCellsChanged=${this.visibleCellsChanged}
397
- ></infinite-scroller>`;
398
- }
399
- get infiniteScrollerClasses() {
400
- var _a;
401
- return classMap({
402
- [(_a = this.displayMode) !== null && _a !== void 0 ? _a : '']: !!this.displayMode,
403
- hidden: !!this.placeholderType,
404
- });
405
- }
406
- get sortFilterBarTemplate() {
407
- var _a;
405
+ ></infinite-scroller>`;
406
+ }
407
+ get infiniteScrollerClasses() {
408
+ var _a;
409
+ return classMap({
410
+ [(_a = this.displayMode) !== null && _a !== void 0 ? _a : '']: !!this.displayMode,
411
+ hidden: !!this.placeholderType,
412
+ });
413
+ }
414
+ get sortFilterBarTemplate() {
415
+ var _a;
408
416
  return html `
409
417
  <sort-filter-bar
410
418
  .defaultSortField=${this.defaultSortField}
@@ -424,135 +432,259 @@ let CollectionBrowser = class CollectionBrowser extends LitElement {
424
432
  @creatorLetterChanged=${this.creatorLetterSelected}
425
433
  >
426
434
  </sort-filter-bar>
427
- `;
428
- }
429
- userChangedSort(e) {
430
- var _a;
431
- const { selectedSort, sortDirection } = e.detail;
432
- this.selectedSort = selectedSort;
433
- this.sortDirection = sortDirection;
434
- if (((_a = this.currentPage) !== null && _a !== void 0 ? _a : 1) > 1) {
435
- this.goToPage(1);
436
- }
437
- this.currentPage = 1;
438
- }
439
- sendSortByAnalytics(prevSortDirection) {
440
- var _a;
441
- const directionCleared = prevSortDirection && !this.sortDirection;
442
- (_a = this.analyticsHandler) === null || _a === void 0 ? void 0 : _a.sendEvent({
443
- category: this.searchContext,
444
- action: analyticsActions.sortBy,
445
- label: `${this.selectedSort}${this.sortDirection || directionCleared ? `-${this.sortDirection}` : ''}`,
446
- });
447
- }
448
- selectedSortChanged() {
449
- var _a;
450
- const sortOption = SORT_OPTIONS[this.selectedSort];
451
- if (!sortOption.handledBySearchService) {
452
- this.sortParam = null;
453
- return;
454
- }
455
- // If the sort option specified in the URL is unrecognized, we just use it as-is
456
- const urlSortParam = new URL(window.location.href).searchParams.get('sort');
457
- const sortField = (_a = sortOption.searchServiceKey) !== null && _a !== void 0 ? _a : urlSortParam === null || urlSortParam === void 0 ? void 0 : urlSortParam.replace(/^-/, '');
458
- // If the sort direction is still null at this point, then we assume ascending
459
- // (i.e., it was unrecognized and had no directional flag)
460
- if (!this.sortDirection)
461
- this.sortDirection = 'asc';
462
- if (!sortField)
463
- return;
464
- this.sortParam = { field: sortField, direction: this.sortDirection };
465
- // Lazy-load the alphabet counts for title/creator sort bar as needed
466
- this.updatePrefixFiltersForCurrentSort();
467
- }
468
- displayModeChanged(e) {
469
- var _a;
470
- this.displayMode = e.detail.displayMode;
471
- if (this.displayMode) {
472
- (_a = this.analyticsHandler) === null || _a === void 0 ? void 0 : _a.sendEvent({
473
- category: this.searchContext,
474
- action: analyticsActions.displayMode,
475
- label: this.displayMode,
476
- });
477
- }
478
- }
479
- /**
480
- * Returns a query clause identifying the currently selected title filter,
481
- * e.g., `firstTitle:X`.
482
- */
483
- get titleQuery() {
484
- return this.selectedTitleFilter
485
- ? `firstTitle:${this.selectedTitleFilter}`
486
- : undefined;
487
- }
488
- /**
489
- * Returns a query clause identifying the currently selected creator filter,
490
- * e.g., `firstCreator:X`.
491
- */
492
- get creatorQuery() {
493
- return this.selectedCreatorFilter
494
- ? `firstCreator:${this.selectedCreatorFilter}`
495
- : undefined;
496
- }
497
- /**
498
- * Send Analytics when sorting by title's first letter
499
- * labels: 'start-<ToLetter>' | 'clear-<FromLetter>' | '<FromLetter>-<ToLetter>'
500
- */
501
- sendFilterByTitleAnalytics(prevSelectedLetter) {
502
- var _a;
503
- if (!prevSelectedLetter && !this.selectedTitleFilter) {
504
- return;
505
- }
506
- const cleared = prevSelectedLetter && !this.selectedTitleFilter;
507
- (_a = this.analyticsHandler) === null || _a === void 0 ? void 0 : _a.sendEvent({
508
- category: this.searchContext,
509
- action: analyticsActions.filterByTitle,
510
- label: cleared
511
- ? `clear-${prevSelectedLetter}`
512
- : `${prevSelectedLetter || 'start'}-${this.selectedTitleFilter}`,
513
- });
514
- }
515
- /**
516
- * Send Analytics when filtering by creator's first letter
517
- * labels: 'start-<ToLetter>' | 'clear-<FromLetter>' | '<FromLetter>-<ToLetter>'
518
- */
519
- sendFilterByCreatorAnalytics(prevSelectedLetter) {
520
- var _a;
521
- if (!prevSelectedLetter && !this.selectedCreatorFilter) {
522
- return;
523
- }
524
- const cleared = prevSelectedLetter && !this.selectedCreatorFilter;
525
- (_a = this.analyticsHandler) === null || _a === void 0 ? void 0 : _a.sendEvent({
526
- category: this.searchContext,
527
- action: analyticsActions.filterByCreator,
528
- label: cleared
529
- ? `clear-${prevSelectedLetter}`
530
- : `${prevSelectedLetter || 'start'}-${this.selectedCreatorFilter}`,
531
- });
532
- }
533
- /**
534
- * Handler for changes to which letter is selected in the title alphabet bar.
535
- */
536
- titleLetterSelected(e) {
537
- this.selectedCreatorFilter = null;
538
- this.selectedTitleFilter = e.detail.selectedLetter;
539
- }
540
- /**
541
- * Handler for changes to which letter is selected in the creator alphabet bar.
542
- */
543
- creatorLetterSelected(e) {
544
- this.selectedTitleFilter = null;
545
- this.selectedCreatorFilter = e.detail.selectedLetter;
546
- }
547
- /**
548
- * The full template for how the facets should be structured in mobile view,
549
- * including the collapsible container (with header) and the facets themselves.
550
- */
551
- get mobileFacetsTemplate() {
552
- const toggleFacetsVisible = () => {
553
- this.isResizeToMobile = false;
554
- this.mobileFacetsVisible = !this.mobileFacetsVisible;
555
- };
435
+ `;
436
+ }
437
+ get manageBarTemplate() {
438
+ return html `
439
+ <manage-bar
440
+ showSelectAll
441
+ showUnselectAll
442
+ @removeItems=${this.handleRemoveItems}
443
+ @selectAll=${this.checkAllTiles}
444
+ @unselectAll=${this.uncheckAllTiles}
445
+ @cancel=${() => {
446
+ this.isManageView = false;
447
+ this.uncheckAllTiles();
448
+ }}
449
+ ></manage-bar>
450
+ `;
451
+ }
452
+ /**
453
+ * Handler for when the user requests to remove all checked items via the manage bar.
454
+ * Emits an `itemRemovalRequested` event with all checked tile models.
455
+ */
456
+ handleRemoveItems() {
457
+ this.dispatchEvent(new CustomEvent('itemRemovalRequested', {
458
+ detail: {
459
+ items: this.checkedTileModels.map(model => ({
460
+ ...model,
461
+ date: formatDate(model.datePublished, 'long'),
462
+ })),
463
+ },
464
+ }));
465
+ }
466
+ /**
467
+ * Removes all tile models that are currently checked & adjusts the paging
468
+ * of the data source to account for any new gaps in the data.
469
+ */
470
+ removeCheckedTiles() {
471
+ // To make sure our data source remains page-aligned, we will offset our data source by
472
+ // the number of removed tiles, so that we can just add the offset when the infinite
473
+ // scroller queries for cell contents.
474
+ // This only matters while we're still viewing the same set of results. If the user changes
475
+ // their query/filters/sort, then the data source is overwritten and the offset cleared.
476
+ const { checkedTileModels, uncheckedTileModels } = this;
477
+ const numChecked = checkedTileModels.length;
478
+ if (numChecked === 0)
479
+ return;
480
+ this.tileModelOffset += numChecked;
481
+ const newDataSource = {};
482
+ // Which page the remaining tile models start on, post-offset
483
+ let offsetPageNumber = Math.floor(this.tileModelOffset / this.pageSize) + 1;
484
+ let indexOnPage = this.tileModelOffset % this.pageSize;
485
+ // Fill the pages up to that point with empty models
486
+ for (let page = 1; page <= offsetPageNumber; page += 1) {
487
+ const remainingHidden = this.tileModelOffset - this.pageSize * (page - 1);
488
+ const offsetCellsOnPage = Math.min(this.pageSize, remainingHidden);
489
+ newDataSource[page] = Array(offsetCellsOnPage).fill(undefined);
490
+ }
491
+ // Shift all the remaining tiles into their new positions in the data source
492
+ for (const model of uncheckedTileModels) {
493
+ if (!newDataSource[offsetPageNumber])
494
+ newDataSource[offsetPageNumber] = [];
495
+ newDataSource[offsetPageNumber].push(model);
496
+ indexOnPage += 1;
497
+ if (indexOnPage >= this.pageSize) {
498
+ offsetPageNumber += 1;
499
+ indexOnPage = 0;
500
+ }
501
+ }
502
+ // Swap in the new data source and update the infinite scroller
503
+ this.dataSource = newDataSource;
504
+ if (this.totalResults)
505
+ this.totalResults -= numChecked;
506
+ if (this.infiniteScroller) {
507
+ this.infiniteScroller.itemCount -= numChecked;
508
+ this.infiniteScroller.refreshAllVisibleCells();
509
+ }
510
+ }
511
+ /**
512
+ * Checks every tile's management checkbox
513
+ */
514
+ checkAllTiles() {
515
+ this.mapDataSource(model => ({ ...model, checked: true }));
516
+ }
517
+ /**
518
+ * Unchecks every tile's management checkbox
519
+ */
520
+ uncheckAllTiles() {
521
+ this.mapDataSource(model => ({ ...model, checked: false }));
522
+ }
523
+ /**
524
+ * Applies the given map function to all of the tile models in every page of the data
525
+ * source. This method updates the data source object in immutable fashion.
526
+ *
527
+ * @param mapFn A callback function to apply on each tile model, as with Array.map
528
+ */
529
+ mapDataSource(mapFn) {
530
+ var _a;
531
+ this.dataSource = Object.fromEntries(Object.entries(this.dataSource).map(([page, tileModels]) => [
532
+ page,
533
+ tileModels.map((model, index, array) => model ? mapFn(model, index, array) : model),
534
+ ]));
535
+ (_a = this.infiniteScroller) === null || _a === void 0 ? void 0 : _a.refreshAllVisibleCells();
536
+ }
537
+ /**
538
+ * An array of all the tile models whose management checkboxes are checked
539
+ */
540
+ get checkedTileModels() {
541
+ return this.getFilteredTileModels(model => model.checked);
542
+ }
543
+ /**
544
+ * An array of all the tile models whose management checkboxes are unchecked
545
+ */
546
+ get uncheckedTileModels() {
547
+ return this.getFilteredTileModels(model => !model.checked);
548
+ }
549
+ /**
550
+ * Returns a flattened, filtered array of all the tile models in the data source
551
+ * for which the given predicate returns a truthy value.
552
+ *
553
+ * @param predicate A callback function to apply on each tile model, as with Array.filter
554
+ * @returns A filtered array of tile models satisfying the predicate
555
+ */
556
+ getFilteredTileModels(predicate) {
557
+ return Object.values(this.dataSource)
558
+ .flat()
559
+ .filter((model, index, array) => model ? predicate(model, index, array) : false);
560
+ }
561
+ userChangedSort(e) {
562
+ var _a;
563
+ const { selectedSort, sortDirection } = e.detail;
564
+ this.selectedSort = selectedSort;
565
+ this.sortDirection = sortDirection;
566
+ if (((_a = this.currentPage) !== null && _a !== void 0 ? _a : 1) > 1) {
567
+ this.goToPage(1);
568
+ }
569
+ this.currentPage = 1;
570
+ }
571
+ sendSortByAnalytics(prevSortDirection) {
572
+ var _a;
573
+ const directionCleared = prevSortDirection && !this.sortDirection;
574
+ (_a = this.analyticsHandler) === null || _a === void 0 ? void 0 : _a.sendEvent({
575
+ category: this.searchContext,
576
+ action: analyticsActions.sortBy,
577
+ label: `${this.selectedSort}${this.sortDirection || directionCleared ? `-${this.sortDirection}` : ''}`,
578
+ });
579
+ }
580
+ selectedSortChanged() {
581
+ var _a;
582
+ const sortOption = SORT_OPTIONS[this.selectedSort];
583
+ if (!sortOption.handledBySearchService) {
584
+ this.sortParam = null;
585
+ return;
586
+ }
587
+ // If the sort option specified in the URL is unrecognized, we just use it as-is
588
+ const urlSortParam = new URL(window.location.href).searchParams.get('sort');
589
+ const sortField = (_a = sortOption.searchServiceKey) !== null && _a !== void 0 ? _a : urlSortParam === null || urlSortParam === void 0 ? void 0 : urlSortParam.replace(/^-/, '');
590
+ // If the sort direction is still null at this point, then we assume ascending
591
+ // (i.e., it was unrecognized and had no directional flag)
592
+ if (!this.sortDirection)
593
+ this.sortDirection = 'asc';
594
+ if (!sortField)
595
+ return;
596
+ this.sortParam = { field: sortField, direction: this.sortDirection };
597
+ // Lazy-load the alphabet counts for title/creator sort bar as needed
598
+ this.updatePrefixFiltersForCurrentSort();
599
+ }
600
+ displayModeChanged(e) {
601
+ var _a;
602
+ this.displayMode = e.detail.displayMode;
603
+ if (this.displayMode) {
604
+ (_a = this.analyticsHandler) === null || _a === void 0 ? void 0 : _a.sendEvent({
605
+ category: this.searchContext,
606
+ action: analyticsActions.displayMode,
607
+ label: this.displayMode,
608
+ });
609
+ }
610
+ }
611
+ /**
612
+ * Returns a query clause identifying the currently selected title filter,
613
+ * e.g., `firstTitle:X`.
614
+ */
615
+ get titleQuery() {
616
+ return this.selectedTitleFilter
617
+ ? `firstTitle:${this.selectedTitleFilter}`
618
+ : undefined;
619
+ }
620
+ /**
621
+ * Returns a query clause identifying the currently selected creator filter,
622
+ * e.g., `firstCreator:X`.
623
+ */
624
+ get creatorQuery() {
625
+ return this.selectedCreatorFilter
626
+ ? `firstCreator:${this.selectedCreatorFilter}`
627
+ : undefined;
628
+ }
629
+ /**
630
+ * Send Analytics when sorting by title's first letter
631
+ * labels: 'start-<ToLetter>' | 'clear-<FromLetter>' | '<FromLetter>-<ToLetter>'
632
+ */
633
+ sendFilterByTitleAnalytics(prevSelectedLetter) {
634
+ var _a;
635
+ if (!prevSelectedLetter && !this.selectedTitleFilter) {
636
+ return;
637
+ }
638
+ const cleared = prevSelectedLetter && !this.selectedTitleFilter;
639
+ (_a = this.analyticsHandler) === null || _a === void 0 ? void 0 : _a.sendEvent({
640
+ category: this.searchContext,
641
+ action: analyticsActions.filterByTitle,
642
+ label: cleared
643
+ ? `clear-${prevSelectedLetter}`
644
+ : `${prevSelectedLetter || 'start'}-${this.selectedTitleFilter}`,
645
+ });
646
+ }
647
+ /**
648
+ * Send Analytics when filtering by creator's first letter
649
+ * labels: 'start-<ToLetter>' | 'clear-<FromLetter>' | '<FromLetter>-<ToLetter>'
650
+ */
651
+ sendFilterByCreatorAnalytics(prevSelectedLetter) {
652
+ var _a;
653
+ if (!prevSelectedLetter && !this.selectedCreatorFilter) {
654
+ return;
655
+ }
656
+ const cleared = prevSelectedLetter && !this.selectedCreatorFilter;
657
+ (_a = this.analyticsHandler) === null || _a === void 0 ? void 0 : _a.sendEvent({
658
+ category: this.searchContext,
659
+ action: analyticsActions.filterByCreator,
660
+ label: cleared
661
+ ? `clear-${prevSelectedLetter}`
662
+ : `${prevSelectedLetter || 'start'}-${this.selectedCreatorFilter}`,
663
+ });
664
+ }
665
+ /**
666
+ * Handler for changes to which letter is selected in the title alphabet bar.
667
+ */
668
+ titleLetterSelected(e) {
669
+ this.selectedCreatorFilter = null;
670
+ this.selectedTitleFilter = e.detail.selectedLetter;
671
+ }
672
+ /**
673
+ * Handler for changes to which letter is selected in the creator alphabet bar.
674
+ */
675
+ creatorLetterSelected(e) {
676
+ this.selectedTitleFilter = null;
677
+ this.selectedCreatorFilter = e.detail.selectedLetter;
678
+ }
679
+ /**
680
+ * The full template for how the facets should be structured in mobile view,
681
+ * including the collapsible container (with header) and the facets themselves.
682
+ */
683
+ get mobileFacetsTemplate() {
684
+ const toggleFacetsVisible = () => {
685
+ this.isResizeToMobile = false;
686
+ this.mobileFacetsVisible = !this.mobileFacetsVisible;
687
+ };
556
688
  return html `
557
689
  <details
558
690
  id="mobile-filter-collapse"
@@ -566,12 +698,12 @@ let CollectionBrowser = class CollectionBrowser extends LitElement {
566
698
  </summary>
567
699
  ${this.facetsTemplate}
568
700
  </details>
569
- `;
570
- }
571
- /**
572
- * The template for the facets component alone, without any surrounding wrappers.
573
- */
574
- get facetsTemplate() {
701
+ `;
702
+ }
703
+ /**
704
+ * The template for the facets component alone, without any surrounding wrappers.
705
+ */
706
+ get facetsTemplate() {
575
707
  return html `
576
708
  <collection-facets
577
709
  @facetsChanged=${this.facetsChanged}
@@ -596,6 +728,7 @@ let CollectionBrowser = class CollectionBrowser extends LitElement {
596
728
  .contentWidth=${this.contentWidth}
597
729
  .query=${this.baseQuery}
598
730
  .filterMap=${this.filterMap}
731
+ .isManageView=${this.isManageView}
599
732
  .modalManager=${this.modalManager}
600
733
  ?collapsableFacets=${this.mobileView}
601
734
  ?facetsLoading=${this.facetsLoading}
@@ -604,41 +737,41 @@ let CollectionBrowser = class CollectionBrowser extends LitElement {
604
737
  .analyticsHandler=${this.analyticsHandler}
605
738
  >
606
739
  </collection-facets>
607
- `;
608
- }
609
- /**
610
- * The HTML template for the "Clear all filters" button, or `nothing` if no
611
- * filters are currently active.
612
- *
613
- * @param mobile Whether to style/shorten the button for mobile view
614
- */
615
- clearFiltersBtnTemplate(mobile) {
616
- if (!this.hasActiveFilters)
617
- return nothing;
618
- const buttonClasses = classMap({
619
- 'clear-filters-btn': true,
620
- mobile,
621
- });
622
- const buttonText = mobile ? 'Clear all' : 'Clear all filters';
740
+ `;
741
+ }
742
+ /**
743
+ * The HTML template for the "Clear all filters" button, or `nothing` if no
744
+ * filters are currently active.
745
+ *
746
+ * @param mobile Whether to style/shorten the button for mobile view
747
+ */
748
+ clearFiltersBtnTemplate(mobile) {
749
+ if (!this.hasActiveFilters)
750
+ return nothing;
751
+ const buttonClasses = classMap({
752
+ 'clear-filters-btn': true,
753
+ mobile,
754
+ });
755
+ const buttonText = mobile ? 'Clear all' : 'Clear all filters';
623
756
  return html `
624
757
  <div class="clear-filters-btn-row">
625
- ${mobile
626
- ? html `<span class="clear-filters-btn-separator">&nbsp;</span>`
758
+ ${mobile
759
+ ? html `<span class="clear-filters-btn-separator">&nbsp;</span>`
627
760
  : nothing}
628
761
  <button class=${buttonClasses} @click=${this.clearFilters}>
629
762
  ${buttonText}
630
763
  </button>
631
764
  </div>
632
- `;
633
- }
634
- get loadingTemplate() {
765
+ `;
766
+ }
767
+ get loadingTemplate() {
635
768
  return html `
636
769
  <div class="loading-cover">
637
770
  <circular-activity-indicator></circular-activity-indicator>
638
771
  </div>
639
- `;
640
- }
641
- get listHeaderTemplate() {
772
+ `;
773
+ }
774
+ get listHeaderTemplate() {
642
775
  return html `
643
776
  <div id="list-header">
644
777
  <tile-dispatcher
@@ -650,1019 +783,1034 @@ let CollectionBrowser = class CollectionBrowser extends LitElement {
650
783
  >
651
784
  </tile-dispatcher>
652
785
  </div>
653
- `;
654
- }
655
- histogramDateRangeUpdated(e) {
656
- var _a;
657
- const { minDate, maxDate } = e.detail;
658
- [this.minSelectedDate, this.maxSelectedDate] = [minDate, maxDate];
659
- (_a = this.analyticsHandler) === null || _a === void 0 ? void 0 : _a.sendEvent({
660
- category: this.searchContext,
661
- action: analyticsActions.histogramChanged,
662
- label: this.dateRangeQueryClause,
663
- });
664
- }
665
- get dateRangeQueryClause() {
666
- if (!this.minSelectedDate || !this.maxSelectedDate) {
667
- return undefined;
668
- }
669
- return `year:[${this.minSelectedDate} TO ${this.maxSelectedDate}]`;
670
- }
671
- firstUpdated() {
672
- this.setupStateRestorationObserver();
673
- this.restoreState();
674
- }
675
- updated(changed) {
676
- var _a;
677
- if (changed.has('placeholderType') && this.placeholderType === null) {
678
- if (!this.leftColIntersectionObserver) {
679
- this.setupLeftColumnScrollListeners();
680
- }
681
- if (!this.facetsIntersectionObserver) {
682
- this.setupFacetsScrollListeners();
683
- }
684
- this.updateLeftColumnHeight();
685
- }
686
- if (changed.has('displayMode') ||
687
- changed.has('baseNavigationUrl') ||
688
- changed.has('baseImageUrl') ||
689
- changed.has('loggedIn')) {
690
- (_a = this.infiniteScroller) === null || _a === void 0 ? void 0 : _a.reload();
691
- }
692
- if (changed.has('baseQuery') ||
693
- changed.has('searchType') ||
694
- changed.has('withinCollection')) {
695
- // Unless this query/search type update is from the initial page load or the
696
- // result of hitting the back button,
697
- // we need to clear any existing filters since they may no longer be valid for
698
- // the new set of search results.
699
- if (!this.historyPopOccurred && this.initialQueryChangeHappened) {
700
- // Ordinarily, we leave the sort param unchanged between searches.
701
- // However, if we are changing the target collection itself, we want the sort cleared too,
702
- // since different collections may have different sorting options available.
703
- const shouldClearSort = changed.has('withinCollection') &&
704
- !changed.has('selectedSort') &&
705
- !changed.has('sortDirection');
706
- // Otherwise, only clear filters that haven't been simultaneously applied in this update
707
- this.clearFilters({
708
- sort: shouldClearSort,
709
- facets: !changed.has('selectedFacets'),
710
- dateRange: !(changed.has('minSelectedDate') || changed.has('maxSelectedDate')),
711
- letterFilters: !(changed.has('selectedTitleFilter') ||
712
- changed.has('selectedCreatorFilter')),
713
- });
714
- }
715
- }
716
- if (changed.has('baseQuery')) {
717
- this.emitBaseQueryChanged();
718
- }
719
- if (changed.has('searchType')) {
720
- this.emitSearchTypeChanged();
721
- }
722
- if (changed.has('currentPage') || changed.has('displayMode')) {
723
- this.persistState();
724
- }
725
- if (changed.has('baseQuery') ||
726
- changed.has('minSelectedDate') ||
727
- changed.has('maxSelectedDate') ||
728
- changed.has('selectedFacets') ||
729
- changed.has('searchService') ||
730
- changed.has('withinCollection')) {
731
- this.refreshLetterCounts();
732
- }
733
- if (changed.has('selectedSort') || changed.has('sortDirection')) {
734
- const prevSortDirection = changed.get('sortDirection');
735
- this.sendSortByAnalytics(prevSortDirection);
736
- this.selectedSortChanged();
737
- }
738
- if (changed.has('selectedTitleFilter')) {
739
- this.sendFilterByTitleAnalytics(changed.get('selectedTitleFilter'));
740
- }
741
- if (changed.has('selectedCreatorFilter')) {
742
- this.sendFilterByCreatorAnalytics(changed.get('selectedCreatorFilter'));
743
- }
744
- if (changed.has('baseQuery') ||
745
- changed.has('searchType') ||
746
- changed.has('selectedTitleFilter') ||
747
- changed.has('selectedCreatorFilter') ||
748
- changed.has('minSelectedDate') ||
749
- changed.has('maxSelectedDate') ||
750
- changed.has('sortParam') ||
751
- changed.has('selectedFacets') ||
752
- changed.has('searchService') ||
753
- changed.has('withinCollection')) {
754
- this.handleQueryChange();
755
- }
756
- if (changed.has('searchResultsLoading')) {
757
- this.emitSearchResultsLoadingChanged();
758
- }
759
- if (changed.has('facetsLoading') &&
760
- this.facetsLoading &&
761
- this.collectionFacets) {
762
- this.collectionFacets.moreLinksVisible =
763
- this.searchType !== SearchType.FULLTEXT;
764
- }
765
- if (changed.has('pagesToRender')) {
766
- if (!this.endOfDataReached && this.infiniteScroller) {
767
- this.infiniteScroller.itemCount = this.estimatedTileCount;
768
- }
769
- }
770
- if (changed.has('resizeObserver')) {
771
- const oldObserver = changed.get('resizeObserver');
772
- if (oldObserver)
773
- this.disconnectResizeObserver(oldObserver);
774
- this.setupResizeObserver();
775
- }
776
- }
777
- disconnectedCallback() {
778
- var _a, _b;
779
- if (this.resizeObserver) {
780
- this.disconnectResizeObserver(this.resizeObserver);
781
- }
782
- if (this.boundNavigationHandler) {
783
- window.removeEventListener('popstate', this.boundNavigationHandler);
784
- }
785
- (_a = this.leftColIntersectionObserver) === null || _a === void 0 ? void 0 : _a.disconnect();
786
- (_b = this.facetsIntersectionObserver) === null || _b === void 0 ? void 0 : _b.disconnect();
787
- window.removeEventListener('resize', this.updateLeftColumnHeight);
788
- }
789
- handleResize(entry) {
790
- const previousView = this.mobileView;
791
- if (entry.target === this.contentContainer) {
792
- this.contentWidth = entry.contentRect.width;
793
- this.mobileView =
794
- this.contentWidth > 0 && this.contentWidth < this.mobileBreakpoint;
795
- // If changing from desktop to mobile disable transition
796
- if (this.mobileView && !previousView) {
797
- this.isResizeToMobile = true;
798
- }
799
- }
800
- // Ensure the facet sidebar remains sized correctly
801
- this.updateLeftColumnHeight();
802
- }
803
- /**
804
- * Sets up listeners for events that may require updating the left column height.
805
- */
806
- setupLeftColumnScrollListeners() {
807
- var _a;
808
- // We observe intersections between the left column's scroll sentinel and
809
- // the viewport, so that we can ensure the left column is always sized to
810
- // match the _available_ viewport height. This should generally be more
811
- // performant than listening to scroll events on the page or column.
812
- const leftColumnSentinel = (_a = this.shadowRoot) === null || _a === void 0 ? void 0 : _a.querySelector('#left-column-scroll-sentinel');
813
- if (leftColumnSentinel) {
814
- this.leftColIntersectionObserver = new IntersectionObserver(this.updateLeftColumnHeight, {
815
- threshold: [...Array(101).keys()].map(n => n / 100), // Threshold every 1%
816
- });
817
- this.leftColIntersectionObserver.observe(leftColumnSentinel);
818
- }
819
- // We also listen for window resize events, as they are not always captured
820
- // by the resize observer and can affect the desired height of the left column.
821
- window.addEventListener('resize', this.updateLeftColumnHeight);
822
- }
823
- /**
824
- * Sets up listeners to control whether the facet sidebar shows its bottom fade-out.
825
- * Note this uses a separate IntersectionObserver from the left column, because we
826
- * don't need granular intersection thresholds for this.
827
- */
828
- setupFacetsScrollListeners() {
829
- var _a;
830
- const facetsSentinel = (_a = this.shadowRoot) === null || _a === void 0 ? void 0 : _a.querySelector('#facets-scroll-sentinel');
831
- if (facetsSentinel) {
832
- this.facetsIntersectionObserver = new IntersectionObserver(this.updateFacetFadeOut);
833
- this.facetsIntersectionObserver.observe(facetsSentinel);
834
- }
835
- }
836
- emitBaseQueryChanged() {
837
- this.dispatchEvent(new CustomEvent('baseQueryChanged', {
838
- detail: {
839
- baseQuery: this.baseQuery,
840
- },
841
- }));
842
- }
843
- emitSearchTypeChanged() {
844
- this.dispatchEvent(new CustomEvent('searchTypeChanged', {
845
- detail: this.searchType,
846
- }));
847
- }
848
- emitTabChanged(tabId) {
849
- this.dispatchEvent(new CustomEvent('tabChanged', {
850
- detail: tabId,
851
- }));
852
- }
853
- disconnectResizeObserver(resizeObserver) {
854
- resizeObserver.removeObserver({
855
- target: this.contentContainer,
856
- handler: this,
857
- });
858
- }
859
- setupResizeObserver() {
860
- if (!this.resizeObserver)
861
- return;
862
- this.resizeObserver.addObserver({
863
- target: this.contentContainer,
864
- handler: this,
865
- });
866
- }
867
- /**
868
- * When the visible cells change from the infinite scroller, we want to emit
869
- * which page is currently visible so the consumer can update its UI or the URL
870
- *
871
- * @param e
872
- * @returns
873
- */
874
- visibleCellsChanged(e) {
875
- if (this.isScrollingToCell)
876
- return;
877
- const { visibleCellIndices } = e.detail;
878
- if (visibleCellIndices.length === 0)
879
- return;
880
- const lastVisibleCellIndex = visibleCellIndices[visibleCellIndices.length - 1];
881
- const lastVisibleCellPage = Math.floor(lastVisibleCellIndex / this.pageSize) + 1;
882
- if (this.currentPage !== lastVisibleCellPage) {
883
- this.currentPage = lastVisibleCellPage;
884
- }
885
- const event = new CustomEvent('visiblePageChanged', {
886
- detail: {
887
- pageNumber: lastVisibleCellPage,
888
- },
889
- });
890
- this.dispatchEvent(event);
891
- }
892
- /**
893
- * A Promise which, after each query change, resolves once the fetches for the initial
894
- * search have completed. Waits for *both* the hits and aggregations fetches to finish.
895
- *
896
- * Ensure you await this component's `updateComplete` promise before awaiting this
897
- * one, to ensure you do not await an obsolete promise from the previous update.
898
- */
899
- get initialSearchComplete() {
900
- return this._initialSearchCompletePromise;
901
- }
902
- async handleQueryChange() {
903
- var _a;
904
- // only reset if the query has actually changed
905
- if (!this.searchService || this.pageFetchQueryKey === this.previousQueryKey)
906
- return;
907
- // If the new state prevents us from updating the search results, don't reset
908
- if (!this.canPerformSearch)
909
- return;
910
- this.previousQueryKey = this.pageFetchQueryKey;
911
- this.dataSource = {};
912
- this.totalResults = undefined;
913
- this.aggregations = undefined;
914
- this.fullYearsHistogramAggregation = undefined;
915
- this.pageFetchesInProgress = {};
916
- this.endOfDataReached = false;
917
- this.pagesToRender =
918
- this.initialPageNumber === 1
919
- ? 2 // First two pages are batched into one request when starting from page 1
920
- : this.initialPageNumber;
921
- this.queryErrorMessage = undefined;
922
- // Reset the infinite scroller's item count, so that it
923
- // shows tile placeholders until the new query's results load in
924
- if (this.infiniteScroller) {
925
- this.infiniteScroller.itemCount = this.estimatedTileCount;
926
- this.infiniteScroller.reload();
927
- }
928
- if (this.withinCollection && ((_a = this.baseQuery) === null || _a === void 0 ? void 0 : _a.trim())) {
929
- this.defaultSortField = SortField.relevance;
930
- this.defaultSortDirection = null;
931
- }
932
- if (!this.initialQueryChangeHappened && this.initialPageNumber > 1) {
933
- this.scrollToPage(this.initialPageNumber);
934
- }
935
- this.initialQueryChangeHappened = true;
936
- // if the query changed as part of a window.history pop event, we don't want to
937
- // persist the state because it overwrites the forward history
938
- if (!this.historyPopOccurred) {
939
- this.persistState();
940
- }
941
- this.historyPopOccurred = false;
942
- // Reset the `initialSearchComplete` promise with a new value for the imminent search
943
- this._initialSearchCompletePromise = new Promise(res => {
944
- this._initialSearchCompleteResolver = res;
945
- });
946
- // Fire the initial page and facets requests
947
- await Promise.all([this.doInitialPageFetch(), this.fetchFacets()]);
948
- // Resolve the `initialSearchComplete` promise for this search
949
- this._initialSearchCompleteResolver(true);
950
- }
951
- setupStateRestorationObserver() {
952
- if (this.boundNavigationHandler)
953
- return;
954
- this.boundNavigationHandler = this.historyNavigationHandler.bind(this);
955
- // when the user navigates back, we want to update the UI to match the URL
956
- window.addEventListener('popstate', this.boundNavigationHandler);
957
- }
958
- historyNavigationHandler() {
959
- this.historyPopOccurred = true;
960
- this.restoreState();
961
- }
962
- restoreState() {
963
- var _a, _b, _c, _d, _e;
964
- const restorationState = this.restorationStateHandler.getRestorationState();
965
- this.displayMode = restorationState.displayMode;
966
- if (restorationState.searchType != null)
967
- this.searchType = restorationState.searchType;
968
- this.selectedSort = (_a = restorationState.selectedSort) !== null && _a !== void 0 ? _a : SortField.default;
969
- this.sortDirection = (_b = restorationState.sortDirection) !== null && _b !== void 0 ? _b : null;
970
- this.selectedTitleFilter = (_c = restorationState.selectedTitleFilter) !== null && _c !== void 0 ? _c : null;
971
- this.selectedCreatorFilter = (_d = restorationState.selectedCreatorFilter) !== null && _d !== void 0 ? _d : null;
972
- this.selectedFacets = restorationState.selectedFacets;
973
- this.baseQuery = restorationState.baseQuery;
974
- this.currentPage = (_e = restorationState.currentPage) !== null && _e !== void 0 ? _e : 1;
975
- this.minSelectedDate = restorationState.minSelectedDate;
976
- this.maxSelectedDate = restorationState.maxSelectedDate;
977
- if (this.currentPage > 1) {
978
- this.goToPage(this.currentPage);
979
- }
980
- }
981
- persistState() {
982
- var _a, _b, _c, _d;
983
- const restorationState = {
984
- displayMode: this.displayMode,
985
- searchType: this.searchType,
986
- selectedSort: this.selectedSort,
987
- sortDirection: (_a = this.sortDirection) !== null && _a !== void 0 ? _a : undefined,
988
- selectedFacets: (_b = this.selectedFacets) !== null && _b !== void 0 ? _b : getDefaultSelectedFacets(),
989
- baseQuery: this.baseQuery,
990
- currentPage: this.currentPage,
991
- titleQuery: this.titleQuery,
992
- creatorQuery: this.creatorQuery,
993
- minSelectedDate: this.minSelectedDate,
994
- maxSelectedDate: this.maxSelectedDate,
995
- selectedTitleFilter: (_c = this.selectedTitleFilter) !== null && _c !== void 0 ? _c : undefined,
996
- selectedCreatorFilter: (_d = this.selectedCreatorFilter) !== null && _d !== void 0 ? _d : undefined,
997
- };
998
- this.restorationStateHandler.persistState(restorationState);
999
- }
1000
- async doInitialPageFetch() {
1001
- this.searchResultsLoading = true;
1002
- // Try to batch 2 initial page requests when possible
1003
- await this.fetchPage(this.initialPageNumber, 2);
1004
- this.searchResultsLoading = false;
1005
- }
1006
- emitSearchResultsLoadingChanged() {
1007
- this.dispatchEvent(new CustomEvent('searchResultsLoadingChanged', {
1008
- detail: {
1009
- loading: this.searchResultsLoading,
1010
- },
1011
- }));
1012
- }
1013
- /**
1014
- * Produces a compact unique ID for a search request that can help with debugging
1015
- * on the backend by making related requests easier to trace through different services.
1016
- * (e.g., tying the hits/aggregations requests for the same page back to a single hash).
1017
- *
1018
- * @param params The search service parameters for the request
1019
- * @param kind The kind of request (hits-only, aggregations-only, or both)
1020
- * @returns A Promise resolving to the uid to apply to the request
1021
- */
1022
- async requestUID(params, kind) {
1023
- var _a;
1024
- const paramsToHash = JSON.stringify({
1025
- pageType: params.pageType,
1026
- pageTarget: params.pageTarget,
1027
- query: params.query,
1028
- fields: params.fields,
1029
- filters: params.filters,
1030
- sort: params.sort,
1031
- searchType: this.searchType,
1032
- });
1033
- const fullQueryHash = (await sha1(paramsToHash)).slice(0, 20); // First 80 bits of SHA-1 are plenty for this
1034
- const sessionId = (await this.getSessionId()).slice(0, 20); // Likewise
1035
- const page = (_a = params.page) !== null && _a !== void 0 ? _a : 0;
1036
- const kindPrefix = kind.charAt(0); // f = full, h = hits, a = aggregations
1037
- const currentTime = Date.now();
1038
- return `R:${fullQueryHash}-S:${sessionId}-P:${page}-K:${kindPrefix}-T:${currentTime}`;
1039
- }
1040
- /**
1041
- * Constructs a search service FilterMap object from the combination of
1042
- * all the currently-applied filters. This includes any facets, letter
1043
- * filters, and date range.
1044
- */
1045
- get filterMap() {
1046
- const builder = new FilterMapBuilder();
1047
- // Add the date range, if applicable
1048
- if (this.minSelectedDate) {
1049
- builder.addFilter('year', this.minSelectedDate, FilterConstraint.GREATER_OR_EQUAL);
1050
- }
1051
- if (this.maxSelectedDate) {
1052
- builder.addFilter('year', this.maxSelectedDate, FilterConstraint.LESS_OR_EQUAL);
1053
- }
1054
- // Add any selected facets
1055
- if (this.selectedFacets) {
1056
- for (const [facetName, facetValues] of Object.entries(this.selectedFacets)) {
1057
- const { name, values } = this.prepareFacetForFetch(facetName, facetValues);
1058
- for (const [value, bucket] of Object.entries(values)) {
1059
- let constraint;
1060
- if (bucket.state === 'selected') {
1061
- constraint = FilterConstraint.INCLUDE;
1062
- }
1063
- else if (bucket.state === 'hidden') {
1064
- constraint = FilterConstraint.EXCLUDE;
1065
- }
1066
- if (constraint) {
1067
- builder.addFilter(name, value, constraint);
1068
- }
1069
- }
1070
- }
1071
- }
1072
- // Add any letter filters
1073
- if (this.selectedTitleFilter) {
1074
- builder.addFilter('firstTitle', this.selectedTitleFilter, FilterConstraint.INCLUDE);
1075
- }
1076
- if (this.selectedCreatorFilter) {
1077
- builder.addFilter('firstCreator', this.selectedCreatorFilter, FilterConstraint.INCLUDE);
1078
- }
1079
- const filterMap = builder.build();
1080
- return filterMap;
1081
- }
1082
- /** The full query, including year facets and date range clauses */
1083
- get fullQuery() {
1084
- var _a, _b;
1085
- let fullQuery = (_b = (_a = this.baseQuery) === null || _a === void 0 ? void 0 : _a.trim()) !== null && _b !== void 0 ? _b : '';
1086
- const { facetQuery, dateRangeQueryClause, sortFilterQueries } = this;
1087
- if (facetQuery) {
1088
- fullQuery += ` AND ${facetQuery}`;
1089
- }
1090
- if (dateRangeQueryClause) {
1091
- fullQuery += ` AND ${dateRangeQueryClause}`;
1092
- }
1093
- if (sortFilterQueries) {
1094
- fullQuery += ` AND ${sortFilterQueries}`;
1095
- }
1096
- return fullQuery.trim();
1097
- }
1098
- /**
1099
- * Generates a query string for the given facets
1100
- *
1101
- * Example: `mediatype:("collection" OR "audio" OR -"etree") AND year:("2000" OR "2001")`
1102
- */
1103
- get facetQuery() {
1104
- var _a;
1105
- if (!this.selectedFacets)
1106
- return undefined;
1107
- const facetClauses = [];
1108
- for (const [facetName, facetValues] of Object.entries(this.selectedFacets)) {
1109
- facetClauses.push(this.buildFacetClause(facetName, facetValues));
1110
- }
1111
- return (_a = this.joinFacetClauses(facetClauses)) === null || _a === void 0 ? void 0 : _a.trim();
1112
- }
1113
- /**
1114
- * Builds an OR-joined facet clause for the given facet name and values.
1115
- *
1116
- * E.g., for name `subject` and values
1117
- * `{ foo: { state: 'selected' }, bar: { state: 'hidden' } }`
1118
- * this will produce the clause
1119
- * `subject:("foo" OR -"bar")`.
1120
- *
1121
- * @param facetName The facet type (e.g., 'collection')
1122
- * @param facetValues The facet buckets, mapped by their keys
1123
- */
1124
- buildFacetClause(facetName, facetValues) {
1125
- const { name: facetQueryName, values } = this.prepareFacetForFetch(facetName, facetValues);
1126
- const facetEntries = Object.entries(values);
1127
- if (facetEntries.length === 0)
1128
- return '';
1129
- const facetValuesArray = [];
1130
- for (const [key, facetData] of facetEntries) {
1131
- const plusMinusPrefix = facetData.state === 'hidden' ? '-' : '';
1132
- facetValuesArray.push(`${plusMinusPrefix}"${key}"`);
1133
- }
1134
- const valueQuery = facetValuesArray.join(` OR `);
1135
- return `${facetQueryName}:(${valueQuery})`;
1136
- }
1137
- /**
1138
- * Handles some special pre-request normalization steps for certain facet types
1139
- * that require them.
1140
- *
1141
- * @param facetName The name of the facet type (e.g., 'language')
1142
- * @param facetValues An array of values for that facet type
1143
- */
1144
- prepareFacetForFetch(facetName, facetValues) {
1145
- // eslint-disable-next-line prefer-const
1146
- let [normalizedName, normalizedValues] = [facetName, facetValues];
1147
- // The full "search engine" name of the lending field is "lending___status"
1148
- if (facetName === 'lending') {
1149
- normalizedName = 'lending___status';
1150
- }
1151
- return {
1152
- name: normalizedName,
1153
- values: normalizedValues,
1154
- };
1155
- }
1156
- /**
1157
- * Takes an array of facet clauses, and combines them into a
1158
- * full AND-joined facet query string. Empty clauses are ignored.
1159
- */
1160
- joinFacetClauses(facetClauses) {
1161
- const nonEmptyFacetClauses = facetClauses.filter(clause => clause.length > 0);
1162
- return nonEmptyFacetClauses.length > 0
1163
- ? `(${nonEmptyFacetClauses.join(' AND ')})`
1164
- : undefined;
1165
- }
1166
- facetsChanged(e) {
1167
- this.selectedFacets = e.detail;
1168
- }
1169
- facetClickHandler({ detail: { key, state: facetState, negative }, }) {
1170
- var _a, _b;
1171
- if (negative) {
1172
- (_a = this.analyticsHandler) === null || _a === void 0 ? void 0 : _a.sendEvent({
1173
- category: this.searchContext,
1174
- action: facetState !== 'none'
1175
- ? analyticsActions.facetNegativeSelected
1176
- : analyticsActions.facetNegativeDeselected,
1177
- label: key,
1178
- });
1179
- }
1180
- else {
1181
- (_b = this.analyticsHandler) === null || _b === void 0 ? void 0 : _b.sendEvent({
1182
- category: this.searchContext,
1183
- action: facetState !== 'none'
1184
- ? analyticsActions.facetSelected
1185
- : analyticsActions.facetDeselected,
1186
- label: key,
1187
- });
1188
- }
1189
- }
1190
- async fetchFacets() {
1191
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
1192
- const trimmedQuery = (_a = this.baseQuery) === null || _a === void 0 ? void 0 : _a.trim();
1193
- if (!this.canPerformSearch)
1194
- return;
1195
- const { facetFetchQueryKey } = this;
1196
- const sortParams = this.sortParam ? [this.sortParam] : [];
1197
- const params = {
1198
- ...this.collectionParams,
1199
- query: trimmedQuery || '',
1200
- rows: 0,
1201
- filters: this.filterMap,
1202
- // Fetch a few extra buckets beyond the 6 we show, in case some get suppressed
1203
- aggregationsSize: 10,
1204
- // Note: we don't need an aggregations param to fetch the default aggregations from the PPS.
1205
- // The default aggregations for the search_results page type should be what we need here.
1206
- };
1207
- params.uid = await this.requestUID({ ...params, sort: sortParams }, 'aggregations');
1208
- this.facetsLoading = true;
1209
- const searchResponse = await ((_b = this.searchService) === null || _b === void 0 ? void 0 : _b.search(params, this.searchType));
1210
- const success = searchResponse === null || searchResponse === void 0 ? void 0 : searchResponse.success;
1211
- // This is checking to see if the query has changed since the data was fetched.
1212
- // If so, we just want to discard this set of aggregations because they are
1213
- // likely no longer valid for the newer query.
1214
- const queryChangedSinceFetch = facetFetchQueryKey !== this.facetFetchQueryKey;
1215
- if (queryChangedSinceFetch)
1216
- return;
1217
- if (!success) {
1218
- const errorMsg = (_c = searchResponse === null || searchResponse === void 0 ? void 0 : searchResponse.error) === null || _c === void 0 ? void 0 : _c.message;
1219
- const detailMsg = (_e = (_d = searchResponse === null || searchResponse === void 0 ? void 0 : searchResponse.error) === null || _d === void 0 ? void 0 : _d.details) === null || _e === void 0 ? void 0 : _e.message;
1220
- if (!errorMsg && !detailMsg) {
1221
- // @ts-ignore: Property 'Sentry' does not exist on type 'Window & typeof globalThis'
1222
- (_g = (_f = window === null || window === void 0 ? void 0 : window.Sentry) === null || _f === void 0 ? void 0 : _f.captureMessage) === null || _g === void 0 ? void 0 : _g.call(_f, 'Missing or malformed facet response from backend', 'error');
1223
- }
1224
- return;
1225
- }
1226
- const { aggregations, collectionTitles } = success.response;
1227
- this.aggregations = aggregations;
1228
- if (collectionTitles) {
1229
- (_h = this.collectionNameCache) === null || _h === void 0 ? void 0 : _h.addKnownTitles(collectionTitles);
1230
- }
1231
- else if ((_j = this.aggregations) === null || _j === void 0 ? void 0 : _j.collection) {
1232
- (_k = this.collectionNameCache) === null || _k === void 0 ? void 0 : _k.preloadIdentifiers(this.aggregations.collection.buckets.map(bucket => { var _a; return (_a = bucket.key) === null || _a === void 0 ? void 0 : _a.toString(); }));
1233
- }
1234
- this.fullYearsHistogramAggregation =
1235
- (_m = (_l = success === null || success === void 0 ? void 0 : success.response) === null || _l === void 0 ? void 0 : _l.aggregations) === null || _m === void 0 ? void 0 : _m.year_histogram;
1236
- this.facetsLoading = false;
1237
- }
1238
- scrollToPage(pageNumber) {
1239
- return new Promise(resolve => {
1240
- const cellIndexToScrollTo = this.pageSize * (pageNumber - 1);
1241
- // without this setTimeout, Safari just pauses until the `fetchPage` is complete
1242
- // then scrolls to the cell
1243
- setTimeout(() => {
1244
- var _a;
1245
- this.isScrollingToCell = true;
1246
- (_a = this.infiniteScroller) === null || _a === void 0 ? void 0 : _a.scrollToCell(cellIndexToScrollTo, true);
1247
- // This timeout is to give the scroll animation time to finish
1248
- // then updating the infinite scroller once we're done scrolling
1249
- // There's no scroll animation completion callback so we're
1250
- // giving it 0.5s to finish.
1251
- setTimeout(() => {
1252
- var _a;
1253
- this.isScrollingToCell = false;
1254
- (_a = this.infiniteScroller) === null || _a === void 0 ? void 0 : _a.reload();
1255
- resolve();
1256
- }, 500);
1257
- }, 0);
1258
- });
1259
- }
1260
- /**
1261
- * Whether sorting by relevance makes sense for the current state.
1262
- * Currently equivalent to having a non-empty query.
1263
- */
1264
- get isRelevanceSortAvailable() {
1265
- var _a;
1266
- return !!((_a = this.baseQuery) === null || _a === void 0 ? void 0 : _a.trim());
1267
- }
1268
- /**
1269
- * Whether a search may be performed in the current state of the component.
1270
- * This is only true if the search service is defined, and either
1271
- * (a) a non-empty query is set, or
1272
- * (b) we are on a collection page in metadata search mode.
1273
- */
1274
- get canPerformSearch() {
1275
- var _a;
1276
- if (!this.searchService)
1277
- return false;
1278
- const trimmedQuery = (_a = this.baseQuery) === null || _a === void 0 ? void 0 : _a.trim();
1279
- const hasNonEmptyQuery = !!trimmedQuery;
1280
- const isCollectionSearch = !!this.withinCollection;
1281
- const isMetadataSearch = this.searchType === SearchType.METADATA;
1282
- // Metadata searches within a collection are allowed to have no query.
1283
- // Otherwise, a non-empty query must be set.
1284
- return hasNonEmptyQuery || (isCollectionSearch && isMetadataSearch);
1285
- }
1286
- /**
1287
- * Additional params to pass to the search service if targeting a collection page,
1288
- * or null otherwise.
1289
- */
1290
- get collectionParams() {
1291
- return this.withinCollection
1292
- ? { pageType: 'collection_details', pageTarget: this.withinCollection }
1293
- : null;
1294
- }
1295
- /**
1296
- * The query key is a string that uniquely identifies the current search.
1297
- * It consists of:
1298
- * - The current base query
1299
- * - The current collection
1300
- * - The current search type
1301
- * - Any currently-applied facets
1302
- * - Any currently-applied date range
1303
- * - Any currently-applied prefix filters
1304
- * - The current sort options
1305
- *
1306
- * This lets us keep track of queries so we don't persist data that's
1307
- * no longer relevant.
1308
- */
1309
- get pageFetchQueryKey() {
1310
- var _a, _b, _c, _d;
1311
- const sortField = (_b = (_a = this.sortParam) === null || _a === void 0 ? void 0 : _a.field) !== null && _b !== void 0 ? _b : 'none';
1312
- const sortDirection = (_d = (_c = this.sortParam) === null || _c === void 0 ? void 0 : _c.direction) !== null && _d !== void 0 ? _d : 'none';
1313
- return `${this.fullQuery}-${this.withinCollection}-${this.searchType}-${sortField}-${sortDirection}`;
1314
- }
1315
- /**
1316
- * Similar to `pageFetchQueryKey` above, but excludes sort fields since they
1317
- * are not relevant in determining aggregation queries.
1318
- */
1319
- get facetFetchQueryKey() {
1320
- return `${this.fullQuery}-${this.withinCollection}-${this.searchType}`;
1321
- }
1322
- /**
1323
- * Fetches one or more pages of results and updates the data source.
1324
- *
1325
- * @param pageNumber The page number to fetch
1326
- * @param numInitialPages If this is an initial page fetch (`pageNumber = 1`),
1327
- * specifies how many pages to batch together in one request. Ignored
1328
- * if `pageNumber != 1`, defaulting to a single page.
1329
- */
1330
- async fetchPage(pageNumber, numInitialPages = 1) {
1331
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
1332
- const trimmedQuery = (_a = this.baseQuery) === null || _a === void 0 ? void 0 : _a.trim();
1333
- if (!this.canPerformSearch)
1334
- return;
1335
- // if we already have data, don't fetch again
1336
- if (this.dataSource[pageNumber])
1337
- return;
1338
- if (this.endOfDataReached)
1339
- return;
1340
- // Batch multiple initial page requests together if needed (e.g., can request
1341
- // pages 1 and 2 together in a single request).
1342
- const numPages = pageNumber === 1 ? numInitialPages : 1;
1343
- const numRows = this.pageSize * numPages;
1344
- // if a fetch is already in progress for this query and page, don't fetch again
1345
- const { pageFetchQueryKey } = this;
1346
- const pageFetches = (_b = this.pageFetchesInProgress[pageFetchQueryKey]) !== null && _b !== void 0 ? _b : new Set();
1347
- if (pageFetches.has(pageNumber))
1348
- return;
1349
- for (let i = 0; i < numPages; i += 1) {
1350
- pageFetches.add(pageNumber + i);
1351
- }
1352
- this.pageFetchesInProgress[pageFetchQueryKey] = pageFetches;
1353
- const sortParams = this.sortParam ? [this.sortParam] : [];
1354
- const params = {
1355
- ...this.collectionParams,
1356
- query: trimmedQuery || '',
1357
- page: pageNumber,
1358
- rows: numRows,
1359
- sort: sortParams,
1360
- filters: this.filterMap,
1361
- aggregations: { omit: true },
1362
- };
1363
- params.uid = await this.requestUID(params, 'hits');
1364
- const searchResponse = await ((_c = this.searchService) === null || _c === void 0 ? void 0 : _c.search(params, this.searchType));
1365
- const success = searchResponse === null || searchResponse === void 0 ? void 0 : searchResponse.success;
1366
- // This is checking to see if the query has changed since the data was fetched.
1367
- // If so, we just want to discard the data since there should be a new query
1368
- // right behind it.
1369
- const queryChangedSinceFetch = pageFetchQueryKey !== this.pageFetchQueryKey;
1370
- if (queryChangedSinceFetch)
1371
- return;
1372
- if (!success) {
1373
- const errorMsg = (_d = searchResponse === null || searchResponse === void 0 ? void 0 : searchResponse.error) === null || _d === void 0 ? void 0 : _d.message;
1374
- const detailMsg = (_f = (_e = searchResponse === null || searchResponse === void 0 ? void 0 : searchResponse.error) === null || _e === void 0 ? void 0 : _e.details) === null || _f === void 0 ? void 0 : _f.message;
1375
- this.queryErrorMessage = `${errorMsg !== null && errorMsg !== void 0 ? errorMsg : ''}${detailMsg ? `; ${detailMsg}` : ''}`;
1376
- if (!this.queryErrorMessage) {
1377
- this.queryErrorMessage = 'Missing or malformed response from backend';
1378
- // @ts-ignore: Property 'Sentry' does not exist on type 'Window & typeof globalThis'
1379
- (_h = (_g = window === null || window === void 0 ? void 0 : window.Sentry) === null || _g === void 0 ? void 0 : _g.captureMessage) === null || _h === void 0 ? void 0 : _h.call(_g, this.queryErrorMessage, 'error');
1380
- }
1381
- for (let i = 0; i < numPages; i += 1) {
1382
- (_j = this.pageFetchesInProgress[pageFetchQueryKey]) === null || _j === void 0 ? void 0 : _j.delete(pageNumber + i);
1383
- }
1384
- this.searchResultsLoading = false;
1385
- return;
1386
- }
1387
- this.totalResults = success.response.totalResults;
1388
- // switch tab to ?tab=about if this.totalResults is 0
1389
- if (this.totalResults === 0) {
1390
- this.emitTabChanged('about');
1391
- }
1392
- if (this.withinCollection) {
1393
- this.collectionInfo = success.response.collectionExtraInfo;
1394
- // For collections, we want the UI to respect the default sort option
1395
- // which can be specified in metadata, or otherwise assumed to be week:desc
1396
- this.applyDefaultCollectionSort(this.collectionInfo);
1397
- if (this.collectionInfo) {
1398
- this.parentCollections = [].concat((_l = (_k = this.collectionInfo.public_metadata) === null || _k === void 0 ? void 0 : _k.collection) !== null && _l !== void 0 ? _l : []);
1399
- }
1400
- }
1401
- const { results, collectionTitles } = success.response;
1402
- if (results && results.length > 0) {
1403
- // Load any collection titles present on the response into the cache,
1404
- // or queue up preload fetches for them if none were present.
1405
- if (collectionTitles) {
1406
- (_m = this.collectionNameCache) === null || _m === void 0 ? void 0 : _m.addKnownTitles(collectionTitles);
1407
- }
1408
- else {
1409
- this.preloadCollectionNames(results);
1410
- }
1411
- // Update the data source for each returned page
1412
- for (let i = 0; i < numPages; i += 1) {
1413
- const pageStartIndex = this.pageSize * i;
1414
- this.updateDataSource(pageNumber + i, results.slice(pageStartIndex, pageStartIndex + this.pageSize));
1415
- }
1416
- }
1417
- // When we reach the end of the data, we can set the infinite scroller's
1418
- // item count to the real total number of results (rather than the
1419
- // temporary estimates based on pages rendered so far).
1420
- const resultCountDiscrepancy = numRows - results.length;
1421
- if (resultCountDiscrepancy > 0) {
1422
- this.endOfDataReached = true;
1423
- if (this.infiniteScroller) {
1424
- this.infiniteScroller.itemCount =
1425
- this.estimatedTileCount - resultCountDiscrepancy;
1426
- }
1427
- }
1428
- for (let i = 0; i < numPages; i += 1) {
1429
- (_o = this.pageFetchesInProgress[pageFetchQueryKey]) === null || _o === void 0 ? void 0 : _o.delete(pageNumber + i);
1430
- }
1431
- }
1432
- preloadCollectionNames(results) {
1433
- var _a;
1434
- const collectionIds = results
1435
- .map(result => { var _a; return (_a = result.collection) === null || _a === void 0 ? void 0 : _a.values; })
1436
- .flat();
1437
- const collectionIdsArray = Array.from(new Set(collectionIds));
1438
- (_a = this.collectionNameCache) === null || _a === void 0 ? void 0 : _a.preloadIdentifiers(collectionIdsArray);
1439
- }
1440
- /**
1441
- * Applies any default sort option for the current collection, by checking
1442
- * for one in the collection's metadata. If none is found, defaults to sorting
1443
- * descending by:
1444
- * - Date Favorited for fav-* collections
1445
- * - Weekly views for all other collections
1446
- */
1447
- applyDefaultCollectionSort(collectionInfo) {
1448
- var _a, _b, _c;
1449
- if (this.baseQuery) {
1450
- // If there's a query set, then we default to relevance sorting regardless of
1451
- // the collection metadata-specified sort.
1452
- this.defaultSortField = SortField.relevance;
1453
- this.defaultSortDirection = null;
1454
- return;
1455
- }
1456
- // Favorite collections sort on Date Favorited by default.
1457
- // Other collections fall back to sorting on weekly views.
1458
- const baseDefaultSort = ((_b = (_a = collectionInfo === null || collectionInfo === void 0 ? void 0 : collectionInfo.public_metadata) === null || _a === void 0 ? void 0 : _a.identifier) === null || _b === void 0 ? void 0 : _b.startsWith('fav-'))
1459
- ? '-favoritedate'
1460
- : '-week';
1461
- // The collection metadata may override the default sorting with something else
1462
- const metadataSort = (_c = collectionInfo === null || collectionInfo === void 0 ? void 0 : collectionInfo.public_metadata) === null || _c === void 0 ? void 0 : _c['sort-by'];
1463
- // Prefer the metadata-specified sort if one exists
1464
- const defaultSortToApply = metadataSort !== null && metadataSort !== void 0 ? metadataSort : baseDefaultSort;
1465
- // Account for both -field and field:dir formats
1466
- let [field, dir] = defaultSortToApply.split(':');
1467
- if (field.startsWith('-')) {
1468
- field = field.slice(1);
1469
- dir = 'desc';
1470
- }
1471
- else if (!['asc', 'desc'].includes(dir)) {
1472
- dir = 'asc';
1473
- }
1474
- const sortOption = sortOptionFromAPIString(field);
1475
- const sortField = sortOption.field;
1476
- if (sortField && sortField !== SortField.default) {
1477
- this.defaultSortField = sortField;
1478
- this.defaultSortDirection = dir;
1479
- }
1480
- }
1481
- /**
1482
- * This is useful for determining whether we need to reload the scroller.
1483
- *
1484
- * When the fetch completes, we need to reload the scroller if the cells for that
1485
- * page are visible, but if the page is not currenlty visible, we don't need to reload
1486
- */
1487
- get currentVisiblePageNumbers() {
1488
- var _a, _b;
1489
- const visibleCells = (_b = (_a = this.infiniteScroller) === null || _a === void 0 ? void 0 : _a.getVisibleCellIndices()) !== null && _b !== void 0 ? _b : [];
1490
- const visiblePages = new Set();
1491
- visibleCells.forEach(cellIndex => {
1492
- const visiblePage = Math.floor(cellIndex / this.pageSize) + 1;
1493
- visiblePages.add(visiblePage);
1494
- });
1495
- return Array.from(visiblePages);
1496
- }
1497
- /**
1498
- * Update the datasource from the fetch response
1499
- *
1500
- * @param pageNumber
1501
- * @param results
1502
- */
1503
- updateDataSource(pageNumber, results) {
1504
- var _a;
1505
- // copy our existing datasource so when we set it below, it gets set
1506
- // instead of modifying the existing dataSource since object changes
1507
- // don't trigger a re-render
1508
- const datasource = { ...this.dataSource };
1509
- const tiles = [];
1510
- results === null || results === void 0 ? void 0 : results.forEach(result => {
1511
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15;
1512
- if (!result.identifier)
1513
- return;
1514
- let loginRequired = false;
1515
- let contentWarning = false;
1516
- // Check if item and item in "modifying" collection, setting above flags
1517
- if (((_a = result.collection) === null || _a === void 0 ? void 0 : _a.values.length) &&
1518
- ((_b = result.mediatype) === null || _b === void 0 ? void 0 : _b.value) !== 'collection') {
1519
- for (const collection of (_d = (_c = result.collection) === null || _c === void 0 ? void 0 : _c.values) !== null && _d !== void 0 ? _d : []) {
1520
- if (collection === 'loggedin') {
1521
- loginRequired = true;
1522
- if (contentWarning)
1523
- break;
1524
- }
1525
- if (collection === 'no-preview') {
1526
- contentWarning = true;
1527
- if (loginRequired)
1528
- break;
1529
- }
1530
- }
1531
- }
1532
- tiles.push({
1533
- averageRating: (_e = result.avg_rating) === null || _e === void 0 ? void 0 : _e.value,
1534
- collections: (_g = (_f = result.collection) === null || _f === void 0 ? void 0 : _f.values) !== null && _g !== void 0 ? _g : [],
1535
- collectionFilesCount: (_j = (_h = result.collection_files_count) === null || _h === void 0 ? void 0 : _h.value) !== null && _j !== void 0 ? _j : 0,
1536
- collectionSize: (_l = (_k = result.collection_size) === null || _k === void 0 ? void 0 : _k.value) !== null && _l !== void 0 ? _l : 0,
1537
- commentCount: (_o = (_m = result.num_reviews) === null || _m === void 0 ? void 0 : _m.value) !== null && _o !== void 0 ? _o : 0,
1538
- creator: (_p = result.creator) === null || _p === void 0 ? void 0 : _p.value,
1539
- creators: (_r = (_q = result.creator) === null || _q === void 0 ? void 0 : _q.values) !== null && _r !== void 0 ? _r : [],
1540
- dateAdded: (_s = result.addeddate) === null || _s === void 0 ? void 0 : _s.value,
1541
- dateArchived: (_t = result.publicdate) === null || _t === void 0 ? void 0 : _t.value,
1542
- datePublished: (_u = result.date) === null || _u === void 0 ? void 0 : _u.value,
1543
- dateReviewed: (_v = result.reviewdate) === null || _v === void 0 ? void 0 : _v.value,
1544
- description: (_w = result.description) === null || _w === void 0 ? void 0 : _w.values.join('\n'),
1545
- favCount: (_y = (_x = result.num_favorites) === null || _x === void 0 ? void 0 : _x.value) !== null && _y !== void 0 ? _y : 0,
1546
- href: this.collapseRepeatedQuotes((_z = result.__href__) === null || _z === void 0 ? void 0 : _z.value),
1547
- identifier: result.identifier,
1548
- issue: (_0 = result.issue) === null || _0 === void 0 ? void 0 : _0.value,
1549
- itemCount: (_2 = (_1 = result.item_count) === null || _1 === void 0 ? void 0 : _1.value) !== null && _2 !== void 0 ? _2 : 0,
1550
- mediatype: (_4 = (_3 = result.mediatype) === null || _3 === void 0 ? void 0 : _3.value) !== null && _4 !== void 0 ? _4 : 'data',
1551
- snippets: (_6 = (_5 = result.highlight) === null || _5 === void 0 ? void 0 : _5.values) !== null && _6 !== void 0 ? _6 : [],
1552
- source: (_7 = result.source) === null || _7 === void 0 ? void 0 : _7.value,
1553
- subjects: (_9 = (_8 = result.subject) === null || _8 === void 0 ? void 0 : _8.values) !== null && _9 !== void 0 ? _9 : [],
1554
- title: (_11 = (_10 = result.title) === null || _10 === void 0 ? void 0 : _10.value) !== null && _11 !== void 0 ? _11 : '',
1555
- volume: (_12 = result.volume) === null || _12 === void 0 ? void 0 : _12.value,
1556
- viewCount: (_14 = (_13 = result.downloads) === null || _13 === void 0 ? void 0 : _13.value) !== null && _14 !== void 0 ? _14 : 0,
1557
- weeklyViewCount: (_15 = result.week) === null || _15 === void 0 ? void 0 : _15.value,
1558
- loginRequired,
1559
- contentWarning,
1560
- });
1561
- });
1562
- datasource[pageNumber] = tiles;
1563
- this.dataSource = datasource;
1564
- const visiblePages = this.currentVisiblePageNumbers;
1565
- const needsReload = visiblePages.includes(pageNumber);
1566
- if (needsReload) {
1567
- (_a = this.infiniteScroller) === null || _a === void 0 ? void 0 : _a.reload();
1568
- }
1569
- }
1570
- /**
1571
- * Returns the input string, but removing one set of quotes from all instances of
1572
- * ""clauses wrapped in two sets of quotes"". This assumes the quotes are already
1573
- * URL-encoded.
1574
- *
1575
- * This should be a temporary measure to address the fact that the __href__ field
1576
- * sometimes acquires extra quotation marks during query rewriting. Once there is a
1577
- * full Lucene parser in place that handles quoted queries correctly, this can likely
1578
- * be removed.
1579
- */
1580
- collapseRepeatedQuotes(str) {
1581
- return str === null || str === void 0 ? void 0 : str.replace(/%22%22(?!%22%22)(.+?)%22%22/g, '%22$1%22');
1582
- }
1583
- /** Fetches the aggregation buckets for the given prefix filter type. */
1584
- async fetchPrefixFilterBuckets(filterType) {
1585
- var _a, _b, _c, _d, _e, _f, _g;
1586
- const trimmedQuery = (_a = this.baseQuery) === null || _a === void 0 ? void 0 : _a.trim();
1587
- if (!this.canPerformSearch)
1588
- return [];
1589
- const filterAggregationKey = prefixFilterAggregationKeys[filterType];
1590
- const sortParams = this.sortParam ? [this.sortParam] : [];
1591
- const params = {
1592
- ...this.collectionParams,
1593
- query: trimmedQuery || '',
1594
- rows: 0,
1595
- filters: this.filterMap,
1596
- // Only fetch the firstTitle or firstCreator aggregation
1597
- aggregations: { simpleParams: [filterAggregationKey] },
1598
- // Fetch all 26 letter buckets
1599
- aggregationsSize: 26,
1600
- };
1601
- params.uid = await this.requestUID({ ...params, sort: sortParams }, 'aggregations');
1602
- const searchResponse = await ((_b = this.searchService) === null || _b === void 0 ? void 0 : _b.search(params, this.searchType));
1603
- return ((_g = (_f = (_e = (_d = (_c = searchResponse === null || searchResponse === void 0 ? void 0 : searchResponse.success) === null || _c === void 0 ? void 0 : _c.response) === null || _d === void 0 ? void 0 : _d.aggregations) === null || _e === void 0 ? void 0 : _e[filterAggregationKey]) === null || _f === void 0 ? void 0 : _f.buckets) !== null && _g !== void 0 ? _g : []);
1604
- }
1605
- /** Fetches and caches the prefix filter counts for the given filter type. */
1606
- async updatePrefixFilterCounts(filterType) {
1607
- const { facetFetchQueryKey } = this;
1608
- const buckets = await this.fetchPrefixFilterBuckets(filterType);
1609
- // Don't update the filter counts for an outdated query (if it has been changed
1610
- // since we sent the request)
1611
- const queryChangedSinceFetch = facetFetchQueryKey !== this.facetFetchQueryKey;
1612
- if (queryChangedSinceFetch)
1613
- return;
1614
- // Unpack the aggregation buckets into a simple map like { 'A': 50, 'B': 25, ... }
1615
- this.prefixFilterCountMap = { ...this.prefixFilterCountMap }; // Clone the object to trigger an update
1616
- this.prefixFilterCountMap[filterType] = buckets.reduce((acc, bucket) => {
1617
- acc[bucket.key.toUpperCase()] = bucket.doc_count;
1618
- return acc;
1619
- }, {});
1620
- }
1621
- /**
1622
- * Fetches and caches the prefix filter counts for the current sort type,
1623
- * provided it is one that permits prefix filtering. (If not, this does nothing).
1624
- */
1625
- async updatePrefixFiltersForCurrentSort() {
1626
- if (['title', 'creator'].includes(this.selectedSort)) {
1627
- const filterType = this.selectedSort;
1628
- if (!this.prefixFilterCountMap[filterType]) {
1629
- this.updatePrefixFilterCounts(filterType);
1630
- }
1631
- }
1632
- }
1633
- /**
1634
- * Clears the cached letter counts for both title and creator, and
1635
- * fetches a new set of counts for whichever of them is the currently
1636
- * selected sort option (which may be neither).
1637
- *
1638
- * Call this whenever the counts are invalidated (e.g., by a query change).
1639
- */
1640
- refreshLetterCounts() {
1641
- if (Object.keys(this.prefixFilterCountMap).length > 0) {
1642
- this.prefixFilterCountMap = {};
1643
- }
1644
- this.updatePrefixFiltersForCurrentSort();
1645
- }
1646
- /**
1647
- * Callback when a result is selected
1648
- */
1649
- resultSelected(event) {
1650
- var _a, _b;
1651
- (_a = this.analyticsHandler) === null || _a === void 0 ? void 0 : _a.sendEvent({
1652
- category: this.searchContext,
1653
- action: analyticsActions.resultSelected,
1654
- label: event.detail.mediatype,
1655
- });
1656
- (_b = this.analyticsHandler) === null || _b === void 0 ? void 0 : _b.sendEvent({
1657
- category: this.searchContext,
1658
- action: analyticsActions.resultSelected,
1659
- label: `page-${this.currentPage}`,
1660
- });
1661
- }
1662
- cellForIndex(index) {
1663
- const model = this.tileModelAtCellIndex(index);
1664
- if (!model)
1665
- return undefined;
786
+ `;
787
+ }
788
+ histogramDateRangeUpdated(e) {
789
+ var _a;
790
+ const { minDate, maxDate } = e.detail;
791
+ [this.minSelectedDate, this.maxSelectedDate] = [minDate, maxDate];
792
+ (_a = this.analyticsHandler) === null || _a === void 0 ? void 0 : _a.sendEvent({
793
+ category: this.searchContext,
794
+ action: analyticsActions.histogramChanged,
795
+ label: this.dateRangeQueryClause,
796
+ });
797
+ }
798
+ get dateRangeQueryClause() {
799
+ if (!this.minSelectedDate || !this.maxSelectedDate) {
800
+ return undefined;
801
+ }
802
+ return `year:[${this.minSelectedDate} TO ${this.maxSelectedDate}]`;
803
+ }
804
+ /**
805
+ * Emits an event indicating a change in whether the manage mode is shown.
806
+ */
807
+ emitManageModeChangedEvent() {
808
+ this.dispatchEvent(new CustomEvent('manageModeChanged', {
809
+ detail: this.isManageView,
810
+ }));
811
+ }
812
+ firstUpdated() {
813
+ this.setupStateRestorationObserver();
814
+ this.restoreState();
815
+ }
816
+ updated(changed) {
817
+ var _a, _b;
818
+ if (changed.has('placeholderType') && this.placeholderType === null) {
819
+ if (!this.leftColIntersectionObserver) {
820
+ this.setupLeftColumnScrollListeners();
821
+ }
822
+ if (!this.facetsIntersectionObserver) {
823
+ this.setupFacetsScrollListeners();
824
+ }
825
+ this.updateLeftColumnHeight();
826
+ }
827
+ if (changed.has('displayMode') ||
828
+ changed.has('baseNavigationUrl') ||
829
+ changed.has('baseImageUrl') ||
830
+ changed.has('loggedIn')) {
831
+ (_a = this.infiniteScroller) === null || _a === void 0 ? void 0 : _a.refreshAllVisibleCells();
832
+ }
833
+ if (changed.has('baseQuery') ||
834
+ changed.has('searchType') ||
835
+ changed.has('withinCollection')) {
836
+ // Unless this query/search type update is from the initial page load or the
837
+ // result of hitting the back button,
838
+ // we need to clear any existing filters since they may no longer be valid for
839
+ // the new set of search results.
840
+ if (!this.historyPopOccurred && this.initialQueryChangeHappened) {
841
+ // Ordinarily, we leave the sort param unchanged between searches.
842
+ // However, if we are changing the target collection itself, we want the sort cleared too,
843
+ // since different collections may have different sorting options available.
844
+ const shouldClearSort = changed.has('withinCollection') &&
845
+ !changed.has('selectedSort') &&
846
+ !changed.has('sortDirection');
847
+ // Otherwise, only clear filters that haven't been simultaneously applied in this update
848
+ this.clearFilters({
849
+ sort: shouldClearSort,
850
+ facets: !changed.has('selectedFacets'),
851
+ dateRange: !(changed.has('minSelectedDate') || changed.has('maxSelectedDate')),
852
+ letterFilters: !(changed.has('selectedTitleFilter') ||
853
+ changed.has('selectedCreatorFilter')),
854
+ });
855
+ }
856
+ }
857
+ if (changed.has('baseQuery')) {
858
+ this.emitBaseQueryChanged();
859
+ }
860
+ if (changed.has('searchType')) {
861
+ this.emitSearchTypeChanged();
862
+ }
863
+ if (changed.has('currentPage') || changed.has('displayMode')) {
864
+ this.persistState();
865
+ }
866
+ if (changed.has('baseQuery') ||
867
+ changed.has('minSelectedDate') ||
868
+ changed.has('maxSelectedDate') ||
869
+ changed.has('selectedFacets') ||
870
+ changed.has('searchService') ||
871
+ changed.has('withinCollection')) {
872
+ this.refreshLetterCounts();
873
+ }
874
+ if (changed.has('selectedSort') || changed.has('sortDirection')) {
875
+ const prevSortDirection = changed.get('sortDirection');
876
+ this.sendSortByAnalytics(prevSortDirection);
877
+ this.selectedSortChanged();
878
+ }
879
+ if (changed.has('selectedTitleFilter')) {
880
+ this.sendFilterByTitleAnalytics(changed.get('selectedTitleFilter'));
881
+ }
882
+ if (changed.has('selectedCreatorFilter')) {
883
+ this.sendFilterByCreatorAnalytics(changed.get('selectedCreatorFilter'));
884
+ }
885
+ if (changed.has('baseQuery') ||
886
+ changed.has('searchType') ||
887
+ changed.has('selectedTitleFilter') ||
888
+ changed.has('selectedCreatorFilter') ||
889
+ changed.has('minSelectedDate') ||
890
+ changed.has('maxSelectedDate') ||
891
+ changed.has('sortParam') ||
892
+ changed.has('selectedFacets') ||
893
+ changed.has('searchService') ||
894
+ changed.has('withinCollection')) {
895
+ this.handleQueryChange();
896
+ }
897
+ if (changed.has('searchResultsLoading')) {
898
+ this.emitSearchResultsLoadingChanged();
899
+ }
900
+ if (changed.has('facetsLoading') &&
901
+ this.facetsLoading &&
902
+ this.collectionFacets) {
903
+ this.collectionFacets.moreLinksVisible =
904
+ this.searchType !== SearchType.FULLTEXT;
905
+ }
906
+ if (changed.has('pagesToRender')) {
907
+ if (!this.endOfDataReached && this.infiniteScroller) {
908
+ this.infiniteScroller.itemCount = this.estimatedTileCount;
909
+ }
910
+ }
911
+ if (changed.has('isManageView')) {
912
+ if (this.isManageView)
913
+ this.displayMode = 'grid';
914
+ (_b = this.infiniteScroller) === null || _b === void 0 ? void 0 : _b.refreshAllVisibleCells();
915
+ this.emitManageModeChangedEvent();
916
+ }
917
+ if (changed.has('resizeObserver')) {
918
+ const oldObserver = changed.get('resizeObserver');
919
+ if (oldObserver)
920
+ this.disconnectResizeObserver(oldObserver);
921
+ this.setupResizeObserver();
922
+ }
923
+ }
924
+ disconnectedCallback() {
925
+ var _a, _b;
926
+ if (this.resizeObserver) {
927
+ this.disconnectResizeObserver(this.resizeObserver);
928
+ }
929
+ if (this.boundNavigationHandler) {
930
+ window.removeEventListener('popstate', this.boundNavigationHandler);
931
+ }
932
+ (_a = this.leftColIntersectionObserver) === null || _a === void 0 ? void 0 : _a.disconnect();
933
+ (_b = this.facetsIntersectionObserver) === null || _b === void 0 ? void 0 : _b.disconnect();
934
+ window.removeEventListener('resize', this.updateLeftColumnHeight);
935
+ }
936
+ handleResize(entry) {
937
+ const previousView = this.mobileView;
938
+ if (entry.target === this.contentContainer) {
939
+ this.contentWidth = entry.contentRect.width;
940
+ this.mobileView =
941
+ this.contentWidth > 0 && this.contentWidth < this.mobileBreakpoint;
942
+ // If changing from desktop to mobile disable transition
943
+ if (this.mobileView && !previousView) {
944
+ this.isResizeToMobile = true;
945
+ }
946
+ }
947
+ // Ensure the facet sidebar remains sized correctly
948
+ this.updateLeftColumnHeight();
949
+ }
950
+ /**
951
+ * Sets up listeners for events that may require updating the left column height.
952
+ */
953
+ setupLeftColumnScrollListeners() {
954
+ var _a;
955
+ // We observe intersections between the left column's scroll sentinel and
956
+ // the viewport, so that we can ensure the left column is always sized to
957
+ // match the _available_ viewport height. This should generally be more
958
+ // performant than listening to scroll events on the page or column.
959
+ const leftColumnSentinel = (_a = this.shadowRoot) === null || _a === void 0 ? void 0 : _a.querySelector('#left-column-scroll-sentinel');
960
+ if (leftColumnSentinel) {
961
+ this.leftColIntersectionObserver = new IntersectionObserver(this.updateLeftColumnHeight, {
962
+ threshold: [...Array(101).keys()].map(n => n / 100), // Threshold every 1%
963
+ });
964
+ this.leftColIntersectionObserver.observe(leftColumnSentinel);
965
+ }
966
+ // We also listen for window resize events, as they are not always captured
967
+ // by the resize observer and can affect the desired height of the left column.
968
+ window.addEventListener('resize', this.updateLeftColumnHeight);
969
+ }
970
+ /**
971
+ * Sets up listeners to control whether the facet sidebar shows its bottom fade-out.
972
+ * Note this uses a separate IntersectionObserver from the left column, because we
973
+ * don't need granular intersection thresholds for this.
974
+ */
975
+ setupFacetsScrollListeners() {
976
+ var _a;
977
+ const facetsSentinel = (_a = this.shadowRoot) === null || _a === void 0 ? void 0 : _a.querySelector('#facets-scroll-sentinel');
978
+ if (facetsSentinel) {
979
+ this.facetsIntersectionObserver = new IntersectionObserver(this.updateFacetFadeOut);
980
+ this.facetsIntersectionObserver.observe(facetsSentinel);
981
+ }
982
+ }
983
+ emitBaseQueryChanged() {
984
+ this.dispatchEvent(new CustomEvent('baseQueryChanged', {
985
+ detail: {
986
+ baseQuery: this.baseQuery,
987
+ },
988
+ }));
989
+ }
990
+ emitSearchTypeChanged() {
991
+ this.dispatchEvent(new CustomEvent('searchTypeChanged', {
992
+ detail: this.searchType,
993
+ }));
994
+ }
995
+ disconnectResizeObserver(resizeObserver) {
996
+ resizeObserver.removeObserver({
997
+ target: this.contentContainer,
998
+ handler: this,
999
+ });
1000
+ }
1001
+ setupResizeObserver() {
1002
+ if (!this.resizeObserver)
1003
+ return;
1004
+ this.resizeObserver.addObserver({
1005
+ target: this.contentContainer,
1006
+ handler: this,
1007
+ });
1008
+ }
1009
+ /**
1010
+ * When the visible cells change from the infinite scroller, we want to emit
1011
+ * which page is currently visible so the consumer can update its UI or the URL
1012
+ *
1013
+ * @param e
1014
+ * @returns
1015
+ */
1016
+ visibleCellsChanged(e) {
1017
+ if (this.isScrollingToCell)
1018
+ return;
1019
+ const { visibleCellIndices } = e.detail;
1020
+ if (visibleCellIndices.length === 0)
1021
+ return;
1022
+ const lastVisibleCellIndex = visibleCellIndices[visibleCellIndices.length - 1];
1023
+ const lastVisibleCellPage = Math.floor(lastVisibleCellIndex / this.pageSize) + 1;
1024
+ if (this.currentPage !== lastVisibleCellPage) {
1025
+ this.currentPage = lastVisibleCellPage;
1026
+ }
1027
+ const event = new CustomEvent('visiblePageChanged', {
1028
+ detail: {
1029
+ pageNumber: lastVisibleCellPage,
1030
+ },
1031
+ });
1032
+ this.dispatchEvent(event);
1033
+ }
1034
+ /**
1035
+ * A Promise which, after each query change, resolves once the fetches for the initial
1036
+ * search have completed. Waits for *both* the hits and aggregations fetches to finish.
1037
+ *
1038
+ * Ensure you await this component's `updateComplete` promise before awaiting this
1039
+ * one, to ensure you do not await an obsolete promise from the previous update.
1040
+ */
1041
+ get initialSearchComplete() {
1042
+ return this._initialSearchCompletePromise;
1043
+ }
1044
+ async handleQueryChange() {
1045
+ var _a;
1046
+ // only reset if the query has actually changed
1047
+ if (!this.searchService || this.pageFetchQueryKey === this.previousQueryKey)
1048
+ return;
1049
+ // If the new state prevents us from updating the search results, don't reset
1050
+ if (!this.canPerformSearch)
1051
+ return;
1052
+ this.previousQueryKey = this.pageFetchQueryKey;
1053
+ this.dataSource = {};
1054
+ this.tileModelOffset = 0;
1055
+ this.totalResults = undefined;
1056
+ this.aggregations = undefined;
1057
+ this.fullYearsHistogramAggregation = undefined;
1058
+ this.pageFetchesInProgress = {};
1059
+ this.endOfDataReached = false;
1060
+ this.pagesToRender =
1061
+ this.initialPageNumber === 1
1062
+ ? 2 // First two pages are batched into one request when starting from page 1
1063
+ : this.initialPageNumber;
1064
+ this.queryErrorMessage = undefined;
1065
+ // Reset the infinite scroller's item count, so that it
1066
+ // shows tile placeholders until the new query's results load in
1067
+ if (this.infiniteScroller) {
1068
+ this.infiniteScroller.itemCount = this.estimatedTileCount;
1069
+ this.infiniteScroller.reload();
1070
+ }
1071
+ if (this.withinCollection && ((_a = this.baseQuery) === null || _a === void 0 ? void 0 : _a.trim())) {
1072
+ this.defaultSortField = SortField.relevance;
1073
+ this.defaultSortDirection = null;
1074
+ }
1075
+ if (!this.initialQueryChangeHappened && this.initialPageNumber > 1) {
1076
+ this.scrollToPage(this.initialPageNumber);
1077
+ }
1078
+ this.initialQueryChangeHappened = true;
1079
+ // if the query changed as part of a window.history pop event, we don't want to
1080
+ // persist the state because it overwrites the forward history
1081
+ if (!this.historyPopOccurred) {
1082
+ this.persistState();
1083
+ }
1084
+ this.historyPopOccurred = false;
1085
+ // Reset the `initialSearchComplete` promise with a new value for the imminent search
1086
+ this._initialSearchCompletePromise = new Promise(res => {
1087
+ this._initialSearchCompleteResolver = res;
1088
+ });
1089
+ // Fire the initial page and facets requests
1090
+ await Promise.all([this.doInitialPageFetch(), this.fetchFacets()]);
1091
+ // Resolve the `initialSearchComplete` promise for this search
1092
+ this._initialSearchCompleteResolver(true);
1093
+ }
1094
+ setupStateRestorationObserver() {
1095
+ if (this.boundNavigationHandler)
1096
+ return;
1097
+ this.boundNavigationHandler = this.historyNavigationHandler.bind(this);
1098
+ // when the user navigates back, we want to update the UI to match the URL
1099
+ window.addEventListener('popstate', this.boundNavigationHandler);
1100
+ }
1101
+ historyNavigationHandler() {
1102
+ this.historyPopOccurred = true;
1103
+ this.restoreState();
1104
+ }
1105
+ restoreState() {
1106
+ var _a, _b, _c, _d, _e;
1107
+ const restorationState = this.restorationStateHandler.getRestorationState();
1108
+ this.displayMode = restorationState.displayMode;
1109
+ if (restorationState.searchType != null)
1110
+ this.searchType = restorationState.searchType;
1111
+ this.selectedSort = (_a = restorationState.selectedSort) !== null && _a !== void 0 ? _a : SortField.default;
1112
+ this.sortDirection = (_b = restorationState.sortDirection) !== null && _b !== void 0 ? _b : null;
1113
+ this.selectedTitleFilter = (_c = restorationState.selectedTitleFilter) !== null && _c !== void 0 ? _c : null;
1114
+ this.selectedCreatorFilter = (_d = restorationState.selectedCreatorFilter) !== null && _d !== void 0 ? _d : null;
1115
+ this.selectedFacets = restorationState.selectedFacets;
1116
+ this.baseQuery = restorationState.baseQuery;
1117
+ this.currentPage = (_e = restorationState.currentPage) !== null && _e !== void 0 ? _e : 1;
1118
+ this.minSelectedDate = restorationState.minSelectedDate;
1119
+ this.maxSelectedDate = restorationState.maxSelectedDate;
1120
+ if (this.currentPage > 1) {
1121
+ this.goToPage(this.currentPage);
1122
+ }
1123
+ }
1124
+ persistState() {
1125
+ var _a, _b, _c, _d;
1126
+ const restorationState = {
1127
+ displayMode: this.displayMode,
1128
+ searchType: this.searchType,
1129
+ selectedSort: this.selectedSort,
1130
+ sortDirection: (_a = this.sortDirection) !== null && _a !== void 0 ? _a : undefined,
1131
+ selectedFacets: (_b = this.selectedFacets) !== null && _b !== void 0 ? _b : getDefaultSelectedFacets(),
1132
+ baseQuery: this.baseQuery,
1133
+ currentPage: this.currentPage,
1134
+ titleQuery: this.titleQuery,
1135
+ creatorQuery: this.creatorQuery,
1136
+ minSelectedDate: this.minSelectedDate,
1137
+ maxSelectedDate: this.maxSelectedDate,
1138
+ selectedTitleFilter: (_c = this.selectedTitleFilter) !== null && _c !== void 0 ? _c : undefined,
1139
+ selectedCreatorFilter: (_d = this.selectedCreatorFilter) !== null && _d !== void 0 ? _d : undefined,
1140
+ };
1141
+ this.restorationStateHandler.persistState(restorationState);
1142
+ }
1143
+ async doInitialPageFetch() {
1144
+ this.searchResultsLoading = true;
1145
+ // Try to batch 2 initial page requests when possible
1146
+ await this.fetchPage(this.initialPageNumber, 2);
1147
+ this.searchResultsLoading = false;
1148
+ }
1149
+ emitSearchResultsLoadingChanged() {
1150
+ this.dispatchEvent(new CustomEvent('searchResultsLoadingChanged', {
1151
+ detail: {
1152
+ loading: this.searchResultsLoading,
1153
+ },
1154
+ }));
1155
+ }
1156
+ /**
1157
+ * Produces a compact unique ID for a search request that can help with debugging
1158
+ * on the backend by making related requests easier to trace through different services.
1159
+ * (e.g., tying the hits/aggregations requests for the same page back to a single hash).
1160
+ *
1161
+ * @param params The search service parameters for the request
1162
+ * @param kind The kind of request (hits-only, aggregations-only, or both)
1163
+ * @returns A Promise resolving to the uid to apply to the request
1164
+ */
1165
+ async requestUID(params, kind) {
1166
+ var _a;
1167
+ const paramsToHash = JSON.stringify({
1168
+ pageType: params.pageType,
1169
+ pageTarget: params.pageTarget,
1170
+ query: params.query,
1171
+ fields: params.fields,
1172
+ filters: params.filters,
1173
+ sort: params.sort,
1174
+ searchType: this.searchType,
1175
+ });
1176
+ const fullQueryHash = (await sha1(paramsToHash)).slice(0, 20); // First 80 bits of SHA-1 are plenty for this
1177
+ const sessionId = (await this.getSessionId()).slice(0, 20); // Likewise
1178
+ const page = (_a = params.page) !== null && _a !== void 0 ? _a : 0;
1179
+ const kindPrefix = kind.charAt(0); // f = full, h = hits, a = aggregations
1180
+ const currentTime = Date.now();
1181
+ return `R:${fullQueryHash}-S:${sessionId}-P:${page}-K:${kindPrefix}-T:${currentTime}`;
1182
+ }
1183
+ /**
1184
+ * Constructs a search service FilterMap object from the combination of
1185
+ * all the currently-applied filters. This includes any facets, letter
1186
+ * filters, and date range.
1187
+ */
1188
+ get filterMap() {
1189
+ const builder = new FilterMapBuilder();
1190
+ // Add the date range, if applicable
1191
+ if (this.minSelectedDate) {
1192
+ builder.addFilter('year', this.minSelectedDate, FilterConstraint.GREATER_OR_EQUAL);
1193
+ }
1194
+ if (this.maxSelectedDate) {
1195
+ builder.addFilter('year', this.maxSelectedDate, FilterConstraint.LESS_OR_EQUAL);
1196
+ }
1197
+ // Add any selected facets
1198
+ if (this.selectedFacets) {
1199
+ for (const [facetName, facetValues] of Object.entries(this.selectedFacets)) {
1200
+ const { name, values } = this.prepareFacetForFetch(facetName, facetValues);
1201
+ for (const [value, bucket] of Object.entries(values)) {
1202
+ let constraint;
1203
+ if (bucket.state === 'selected') {
1204
+ constraint = FilterConstraint.INCLUDE;
1205
+ }
1206
+ else if (bucket.state === 'hidden') {
1207
+ constraint = FilterConstraint.EXCLUDE;
1208
+ }
1209
+ if (constraint) {
1210
+ builder.addFilter(name, value, constraint);
1211
+ }
1212
+ }
1213
+ }
1214
+ }
1215
+ // Add any letter filters
1216
+ if (this.selectedTitleFilter) {
1217
+ builder.addFilter('firstTitle', this.selectedTitleFilter, FilterConstraint.INCLUDE);
1218
+ }
1219
+ if (this.selectedCreatorFilter) {
1220
+ builder.addFilter('firstCreator', this.selectedCreatorFilter, FilterConstraint.INCLUDE);
1221
+ }
1222
+ const filterMap = builder.build();
1223
+ return filterMap;
1224
+ }
1225
+ /** The full query, including year facets and date range clauses */
1226
+ get fullQuery() {
1227
+ var _a, _b;
1228
+ let fullQuery = (_b = (_a = this.baseQuery) === null || _a === void 0 ? void 0 : _a.trim()) !== null && _b !== void 0 ? _b : '';
1229
+ const { facetQuery, dateRangeQueryClause, sortFilterQueries } = this;
1230
+ if (facetQuery) {
1231
+ fullQuery += ` AND ${facetQuery}`;
1232
+ }
1233
+ if (dateRangeQueryClause) {
1234
+ fullQuery += ` AND ${dateRangeQueryClause}`;
1235
+ }
1236
+ if (sortFilterQueries) {
1237
+ fullQuery += ` AND ${sortFilterQueries}`;
1238
+ }
1239
+ return fullQuery.trim();
1240
+ }
1241
+ /**
1242
+ * Generates a query string for the given facets
1243
+ *
1244
+ * Example: `mediatype:("collection" OR "audio" OR -"etree") AND year:("2000" OR "2001")`
1245
+ */
1246
+ get facetQuery() {
1247
+ var _a;
1248
+ if (!this.selectedFacets)
1249
+ return undefined;
1250
+ const facetClauses = [];
1251
+ for (const [facetName, facetValues] of Object.entries(this.selectedFacets)) {
1252
+ facetClauses.push(this.buildFacetClause(facetName, facetValues));
1253
+ }
1254
+ return (_a = this.joinFacetClauses(facetClauses)) === null || _a === void 0 ? void 0 : _a.trim();
1255
+ }
1256
+ /**
1257
+ * Builds an OR-joined facet clause for the given facet name and values.
1258
+ *
1259
+ * E.g., for name `subject` and values
1260
+ * `{ foo: { state: 'selected' }, bar: { state: 'hidden' } }`
1261
+ * this will produce the clause
1262
+ * `subject:("foo" OR -"bar")`.
1263
+ *
1264
+ * @param facetName The facet type (e.g., 'collection')
1265
+ * @param facetValues The facet buckets, mapped by their keys
1266
+ */
1267
+ buildFacetClause(facetName, facetValues) {
1268
+ const { name: facetQueryName, values } = this.prepareFacetForFetch(facetName, facetValues);
1269
+ const facetEntries = Object.entries(values);
1270
+ if (facetEntries.length === 0)
1271
+ return '';
1272
+ const facetValuesArray = [];
1273
+ for (const [key, facetData] of facetEntries) {
1274
+ const plusMinusPrefix = facetData.state === 'hidden' ? '-' : '';
1275
+ facetValuesArray.push(`${plusMinusPrefix}"${key}"`);
1276
+ }
1277
+ const valueQuery = facetValuesArray.join(` OR `);
1278
+ return `${facetQueryName}:(${valueQuery})`;
1279
+ }
1280
+ /**
1281
+ * Handles some special pre-request normalization steps for certain facet types
1282
+ * that require them.
1283
+ *
1284
+ * @param facetName The name of the facet type (e.g., 'language')
1285
+ * @param facetValues An array of values for that facet type
1286
+ */
1287
+ prepareFacetForFetch(facetName, facetValues) {
1288
+ // eslint-disable-next-line prefer-const
1289
+ let [normalizedName, normalizedValues] = [facetName, facetValues];
1290
+ // The full "search engine" name of the lending field is "lending___status"
1291
+ if (facetName === 'lending') {
1292
+ normalizedName = 'lending___status';
1293
+ }
1294
+ return {
1295
+ name: normalizedName,
1296
+ values: normalizedValues,
1297
+ };
1298
+ }
1299
+ /**
1300
+ * Takes an array of facet clauses, and combines them into a
1301
+ * full AND-joined facet query string. Empty clauses are ignored.
1302
+ */
1303
+ joinFacetClauses(facetClauses) {
1304
+ const nonEmptyFacetClauses = facetClauses.filter(clause => clause.length > 0);
1305
+ return nonEmptyFacetClauses.length > 0
1306
+ ? `(${nonEmptyFacetClauses.join(' AND ')})`
1307
+ : undefined;
1308
+ }
1309
+ facetsChanged(e) {
1310
+ this.selectedFacets = e.detail;
1311
+ }
1312
+ facetClickHandler({ detail: { key, state: facetState, negative }, }) {
1313
+ var _a, _b;
1314
+ if (negative) {
1315
+ (_a = this.analyticsHandler) === null || _a === void 0 ? void 0 : _a.sendEvent({
1316
+ category: this.searchContext,
1317
+ action: facetState !== 'none'
1318
+ ? analyticsActions.facetNegativeSelected
1319
+ : analyticsActions.facetNegativeDeselected,
1320
+ label: key,
1321
+ });
1322
+ }
1323
+ else {
1324
+ (_b = this.analyticsHandler) === null || _b === void 0 ? void 0 : _b.sendEvent({
1325
+ category: this.searchContext,
1326
+ action: facetState !== 'none'
1327
+ ? analyticsActions.facetSelected
1328
+ : analyticsActions.facetDeselected,
1329
+ label: key,
1330
+ });
1331
+ }
1332
+ }
1333
+ async fetchFacets() {
1334
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
1335
+ const trimmedQuery = (_a = this.baseQuery) === null || _a === void 0 ? void 0 : _a.trim();
1336
+ if (!this.canPerformSearch)
1337
+ return;
1338
+ const { facetFetchQueryKey } = this;
1339
+ const sortParams = this.sortParam ? [this.sortParam] : [];
1340
+ const params = {
1341
+ ...this.collectionParams,
1342
+ query: trimmedQuery || '',
1343
+ rows: 0,
1344
+ filters: this.filterMap,
1345
+ // Fetch a few extra buckets beyond the 6 we show, in case some get suppressed
1346
+ aggregationsSize: 10,
1347
+ // Note: we don't need an aggregations param to fetch the default aggregations from the PPS.
1348
+ // The default aggregations for the search_results page type should be what we need here.
1349
+ };
1350
+ params.uid = await this.requestUID({ ...params, sort: sortParams }, 'aggregations');
1351
+ this.facetsLoading = true;
1352
+ const searchResponse = await ((_b = this.searchService) === null || _b === void 0 ? void 0 : _b.search(params, this.searchType));
1353
+ const success = searchResponse === null || searchResponse === void 0 ? void 0 : searchResponse.success;
1354
+ // This is checking to see if the query has changed since the data was fetched.
1355
+ // If so, we just want to discard this set of aggregations because they are
1356
+ // likely no longer valid for the newer query.
1357
+ const queryChangedSinceFetch = facetFetchQueryKey !== this.facetFetchQueryKey;
1358
+ if (queryChangedSinceFetch)
1359
+ return;
1360
+ if (!success) {
1361
+ const errorMsg = (_c = searchResponse === null || searchResponse === void 0 ? void 0 : searchResponse.error) === null || _c === void 0 ? void 0 : _c.message;
1362
+ const detailMsg = (_e = (_d = searchResponse === null || searchResponse === void 0 ? void 0 : searchResponse.error) === null || _d === void 0 ? void 0 : _d.details) === null || _e === void 0 ? void 0 : _e.message;
1363
+ if (!errorMsg && !detailMsg) {
1364
+ // @ts-ignore: Property 'Sentry' does not exist on type 'Window & typeof globalThis'
1365
+ (_g = (_f = window === null || window === void 0 ? void 0 : window.Sentry) === null || _f === void 0 ? void 0 : _f.captureMessage) === null || _g === void 0 ? void 0 : _g.call(_f, 'Missing or malformed facet response from backend', 'error');
1366
+ }
1367
+ return;
1368
+ }
1369
+ const { aggregations, collectionTitles } = success.response;
1370
+ this.aggregations = aggregations;
1371
+ if (collectionTitles) {
1372
+ (_h = this.collectionNameCache) === null || _h === void 0 ? void 0 : _h.addKnownTitles(collectionTitles);
1373
+ }
1374
+ else if ((_j = this.aggregations) === null || _j === void 0 ? void 0 : _j.collection) {
1375
+ (_k = this.collectionNameCache) === null || _k === void 0 ? void 0 : _k.preloadIdentifiers(this.aggregations.collection.buckets.map(bucket => { var _a; return (_a = bucket.key) === null || _a === void 0 ? void 0 : _a.toString(); }));
1376
+ }
1377
+ this.fullYearsHistogramAggregation =
1378
+ (_m = (_l = success === null || success === void 0 ? void 0 : success.response) === null || _l === void 0 ? void 0 : _l.aggregations) === null || _m === void 0 ? void 0 : _m.year_histogram;
1379
+ this.facetsLoading = false;
1380
+ }
1381
+ scrollToPage(pageNumber) {
1382
+ return new Promise(resolve => {
1383
+ const cellIndexToScrollTo = this.pageSize * (pageNumber - 1);
1384
+ // without this setTimeout, Safari just pauses until the `fetchPage` is complete
1385
+ // then scrolls to the cell
1386
+ setTimeout(() => {
1387
+ var _a;
1388
+ this.isScrollingToCell = true;
1389
+ (_a = this.infiniteScroller) === null || _a === void 0 ? void 0 : _a.scrollToCell(cellIndexToScrollTo, true);
1390
+ // This timeout is to give the scroll animation time to finish
1391
+ // then updating the infinite scroller once we're done scrolling
1392
+ // There's no scroll animation completion callback so we're
1393
+ // giving it 0.5s to finish.
1394
+ setTimeout(() => {
1395
+ var _a;
1396
+ this.isScrollingToCell = false;
1397
+ (_a = this.infiniteScroller) === null || _a === void 0 ? void 0 : _a.refreshAllVisibleCells();
1398
+ resolve();
1399
+ }, 500);
1400
+ }, 0);
1401
+ });
1402
+ }
1403
+ /**
1404
+ * Whether sorting by relevance makes sense for the current state.
1405
+ * Currently equivalent to having a non-empty query.
1406
+ */
1407
+ get isRelevanceSortAvailable() {
1408
+ var _a;
1409
+ return !!((_a = this.baseQuery) === null || _a === void 0 ? void 0 : _a.trim());
1410
+ }
1411
+ /**
1412
+ * Whether a search may be performed in the current state of the component.
1413
+ * This is only true if the search service is defined, and either
1414
+ * (a) a non-empty query is set, or
1415
+ * (b) we are on a collection page in metadata search mode.
1416
+ */
1417
+ get canPerformSearch() {
1418
+ var _a;
1419
+ if (!this.searchService)
1420
+ return false;
1421
+ const trimmedQuery = (_a = this.baseQuery) === null || _a === void 0 ? void 0 : _a.trim();
1422
+ const hasNonEmptyQuery = !!trimmedQuery;
1423
+ const isCollectionSearch = !!this.withinCollection;
1424
+ const isMetadataSearch = this.searchType === SearchType.METADATA;
1425
+ // Metadata searches within a collection are allowed to have no query.
1426
+ // Otherwise, a non-empty query must be set.
1427
+ return hasNonEmptyQuery || (isCollectionSearch && isMetadataSearch);
1428
+ }
1429
+ /**
1430
+ * Additional params to pass to the search service if targeting a collection page,
1431
+ * or null otherwise.
1432
+ */
1433
+ get collectionParams() {
1434
+ return this.withinCollection
1435
+ ? { pageType: 'collection_details', pageTarget: this.withinCollection }
1436
+ : null;
1437
+ }
1438
+ /**
1439
+ * The query key is a string that uniquely identifies the current search.
1440
+ * It consists of:
1441
+ * - The current base query
1442
+ * - The current collection
1443
+ * - The current search type
1444
+ * - Any currently-applied facets
1445
+ * - Any currently-applied date range
1446
+ * - Any currently-applied prefix filters
1447
+ * - The current sort options
1448
+ *
1449
+ * This lets us keep track of queries so we don't persist data that's
1450
+ * no longer relevant.
1451
+ */
1452
+ get pageFetchQueryKey() {
1453
+ var _a, _b, _c, _d;
1454
+ const sortField = (_b = (_a = this.sortParam) === null || _a === void 0 ? void 0 : _a.field) !== null && _b !== void 0 ? _b : 'none';
1455
+ const sortDirection = (_d = (_c = this.sortParam) === null || _c === void 0 ? void 0 : _c.direction) !== null && _d !== void 0 ? _d : 'none';
1456
+ return `${this.fullQuery}-${this.withinCollection}-${this.searchType}-${sortField}-${sortDirection}`;
1457
+ }
1458
+ /**
1459
+ * Similar to `pageFetchQueryKey` above, but excludes sort fields since they
1460
+ * are not relevant in determining aggregation queries.
1461
+ */
1462
+ get facetFetchQueryKey() {
1463
+ return `${this.fullQuery}-${this.withinCollection}-${this.searchType}`;
1464
+ }
1465
+ /**
1466
+ * Fetches one or more pages of results and updates the data source.
1467
+ *
1468
+ * @param pageNumber The page number to fetch
1469
+ * @param numInitialPages If this is an initial page fetch (`pageNumber = 1`),
1470
+ * specifies how many pages to batch together in one request. Ignored
1471
+ * if `pageNumber != 1`, defaulting to a single page.
1472
+ */
1473
+ async fetchPage(pageNumber, numInitialPages = 1) {
1474
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
1475
+ const trimmedQuery = (_a = this.baseQuery) === null || _a === void 0 ? void 0 : _a.trim();
1476
+ if (!this.canPerformSearch)
1477
+ return;
1478
+ // if we already have data, don't fetch again
1479
+ if (this.dataSource[pageNumber])
1480
+ return;
1481
+ if (this.endOfDataReached)
1482
+ return;
1483
+ // Batch multiple initial page requests together if needed (e.g., can request
1484
+ // pages 1 and 2 together in a single request).
1485
+ const numPages = pageNumber === 1 ? numInitialPages : 1;
1486
+ const numRows = this.pageSize * numPages;
1487
+ // if a fetch is already in progress for this query and page, don't fetch again
1488
+ const { pageFetchQueryKey } = this;
1489
+ const pageFetches = (_b = this.pageFetchesInProgress[pageFetchQueryKey]) !== null && _b !== void 0 ? _b : new Set();
1490
+ if (pageFetches.has(pageNumber))
1491
+ return;
1492
+ for (let i = 0; i < numPages; i += 1) {
1493
+ pageFetches.add(pageNumber + i);
1494
+ }
1495
+ this.pageFetchesInProgress[pageFetchQueryKey] = pageFetches;
1496
+ const sortParams = this.sortParam ? [this.sortParam] : [];
1497
+ const params = {
1498
+ ...this.collectionParams,
1499
+ query: trimmedQuery || '',
1500
+ page: pageNumber,
1501
+ rows: numRows,
1502
+ sort: sortParams,
1503
+ filters: this.filterMap,
1504
+ aggregations: { omit: true },
1505
+ };
1506
+ params.uid = await this.requestUID(params, 'hits');
1507
+ const searchResponse = await ((_c = this.searchService) === null || _c === void 0 ? void 0 : _c.search(params, this.searchType));
1508
+ const success = searchResponse === null || searchResponse === void 0 ? void 0 : searchResponse.success;
1509
+ // This is checking to see if the query has changed since the data was fetched.
1510
+ // If so, we just want to discard the data since there should be a new query
1511
+ // right behind it.
1512
+ const queryChangedSinceFetch = pageFetchQueryKey !== this.pageFetchQueryKey;
1513
+ if (queryChangedSinceFetch)
1514
+ return;
1515
+ if (!success) {
1516
+ const errorMsg = (_d = searchResponse === null || searchResponse === void 0 ? void 0 : searchResponse.error) === null || _d === void 0 ? void 0 : _d.message;
1517
+ const detailMsg = (_f = (_e = searchResponse === null || searchResponse === void 0 ? void 0 : searchResponse.error) === null || _e === void 0 ? void 0 : _e.details) === null || _f === void 0 ? void 0 : _f.message;
1518
+ this.queryErrorMessage = `${errorMsg !== null && errorMsg !== void 0 ? errorMsg : ''}${detailMsg ? `; ${detailMsg}` : ''}`;
1519
+ if (!this.queryErrorMessage) {
1520
+ this.queryErrorMessage = 'Missing or malformed response from backend';
1521
+ // @ts-ignore: Property 'Sentry' does not exist on type 'Window & typeof globalThis'
1522
+ (_h = (_g = window === null || window === void 0 ? void 0 : window.Sentry) === null || _g === void 0 ? void 0 : _g.captureMessage) === null || _h === void 0 ? void 0 : _h.call(_g, this.queryErrorMessage, 'error');
1523
+ }
1524
+ for (let i = 0; i < numPages; i += 1) {
1525
+ (_j = this.pageFetchesInProgress[pageFetchQueryKey]) === null || _j === void 0 ? void 0 : _j.delete(pageNumber + i);
1526
+ }
1527
+ this.searchResultsLoading = false;
1528
+ return;
1529
+ }
1530
+ this.totalResults = success.response.totalResults - this.tileModelOffset;
1531
+ if (this.withinCollection) {
1532
+ this.collectionInfo = success.response.collectionExtraInfo;
1533
+ // For collections, we want the UI to respect the default sort option
1534
+ // which can be specified in metadata, or otherwise assumed to be week:desc
1535
+ this.applyDefaultCollectionSort(this.collectionInfo);
1536
+ if (this.collectionInfo) {
1537
+ this.parentCollections = [].concat((_l = (_k = this.collectionInfo.public_metadata) === null || _k === void 0 ? void 0 : _k.collection) !== null && _l !== void 0 ? _l : []);
1538
+ }
1539
+ }
1540
+ const { results, collectionTitles } = success.response;
1541
+ if (results && results.length > 0) {
1542
+ // Load any collection titles present on the response into the cache,
1543
+ // or queue up preload fetches for them if none were present.
1544
+ if (collectionTitles) {
1545
+ (_m = this.collectionNameCache) === null || _m === void 0 ? void 0 : _m.addKnownTitles(collectionTitles);
1546
+ }
1547
+ else {
1548
+ this.preloadCollectionNames(results);
1549
+ }
1550
+ // Update the data source for each returned page
1551
+ for (let i = 0; i < numPages; i += 1) {
1552
+ const pageStartIndex = this.pageSize * i;
1553
+ this.updateDataSource(pageNumber + i, results.slice(pageStartIndex, pageStartIndex + this.pageSize));
1554
+ }
1555
+ }
1556
+ // When we reach the end of the data, we can set the infinite scroller's
1557
+ // item count to the real total number of results (rather than the
1558
+ // temporary estimates based on pages rendered so far).
1559
+ const resultCountDiscrepancy = numRows - results.length;
1560
+ if (resultCountDiscrepancy > 0) {
1561
+ this.endOfDataReached = true;
1562
+ if (this.infiniteScroller) {
1563
+ this.infiniteScroller.itemCount = this.totalResults;
1564
+ }
1565
+ }
1566
+ for (let i = 0; i < numPages; i += 1) {
1567
+ (_o = this.pageFetchesInProgress[pageFetchQueryKey]) === null || _o === void 0 ? void 0 : _o.delete(pageNumber + i);
1568
+ }
1569
+ }
1570
+ preloadCollectionNames(results) {
1571
+ var _a;
1572
+ const collectionIds = results
1573
+ .map(result => { var _a; return (_a = result.collection) === null || _a === void 0 ? void 0 : _a.values; })
1574
+ .flat();
1575
+ const collectionIdsArray = Array.from(new Set(collectionIds));
1576
+ (_a = this.collectionNameCache) === null || _a === void 0 ? void 0 : _a.preloadIdentifiers(collectionIdsArray);
1577
+ }
1578
+ /**
1579
+ * Applies any default sort option for the current collection, by checking
1580
+ * for one in the collection's metadata. If none is found, defaults to sorting
1581
+ * descending by:
1582
+ * - Date Favorited for fav-* collections
1583
+ * - Weekly views for all other collections
1584
+ */
1585
+ applyDefaultCollectionSort(collectionInfo) {
1586
+ var _a, _b, _c;
1587
+ if (this.baseQuery) {
1588
+ // If there's a query set, then we default to relevance sorting regardless of
1589
+ // the collection metadata-specified sort.
1590
+ this.defaultSortField = SortField.relevance;
1591
+ this.defaultSortDirection = null;
1592
+ return;
1593
+ }
1594
+ // Favorite collections sort on Date Favorited by default.
1595
+ // Other collections fall back to sorting on weekly views.
1596
+ const baseDefaultSort = ((_b = (_a = collectionInfo === null || collectionInfo === void 0 ? void 0 : collectionInfo.public_metadata) === null || _a === void 0 ? void 0 : _a.identifier) === null || _b === void 0 ? void 0 : _b.startsWith('fav-'))
1597
+ ? '-favoritedate'
1598
+ : '-week';
1599
+ // The collection metadata may override the default sorting with something else
1600
+ const metadataSort = (_c = collectionInfo === null || collectionInfo === void 0 ? void 0 : collectionInfo.public_metadata) === null || _c === void 0 ? void 0 : _c['sort-by'];
1601
+ // Prefer the metadata-specified sort if one exists
1602
+ const defaultSortToApply = metadataSort !== null && metadataSort !== void 0 ? metadataSort : baseDefaultSort;
1603
+ // Account for both -field and field:dir formats
1604
+ let [field, dir] = defaultSortToApply.split(':');
1605
+ if (field.startsWith('-')) {
1606
+ field = field.slice(1);
1607
+ dir = 'desc';
1608
+ }
1609
+ else if (!['asc', 'desc'].includes(dir)) {
1610
+ dir = 'asc';
1611
+ }
1612
+ const sortOption = sortOptionFromAPIString(field);
1613
+ const sortField = sortOption.field;
1614
+ if (sortField && sortField !== SortField.default) {
1615
+ this.defaultSortField = sortField;
1616
+ this.defaultSortDirection = dir;
1617
+ }
1618
+ }
1619
+ /**
1620
+ * This is useful for determining whether we need to reload the scroller.
1621
+ *
1622
+ * When the fetch completes, we need to reload the scroller if the cells for that
1623
+ * page are visible, but if the page is not currenlty visible, we don't need to reload
1624
+ */
1625
+ get currentVisiblePageNumbers() {
1626
+ var _a, _b;
1627
+ const visibleCells = (_b = (_a = this.infiniteScroller) === null || _a === void 0 ? void 0 : _a.getVisibleCellIndices()) !== null && _b !== void 0 ? _b : [];
1628
+ const visiblePages = new Set();
1629
+ visibleCells.forEach(cellIndex => {
1630
+ const visiblePage = Math.floor(cellIndex / this.pageSize) + 1;
1631
+ visiblePages.add(visiblePage);
1632
+ });
1633
+ return Array.from(visiblePages);
1634
+ }
1635
+ /**
1636
+ * Update the datasource from the fetch response
1637
+ *
1638
+ * @param pageNumber
1639
+ * @param results
1640
+ */
1641
+ updateDataSource(pageNumber, results) {
1642
+ var _a;
1643
+ // copy our existing datasource so when we set it below, it gets set
1644
+ // instead of modifying the existing dataSource since object changes
1645
+ // don't trigger a re-render
1646
+ const datasource = { ...this.dataSource };
1647
+ const tiles = [];
1648
+ results === null || results === void 0 ? void 0 : results.forEach(result => {
1649
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15;
1650
+ if (!result.identifier)
1651
+ return;
1652
+ let loginRequired = false;
1653
+ let contentWarning = false;
1654
+ // Check if item and item in "modifying" collection, setting above flags
1655
+ if (((_a = result.collection) === null || _a === void 0 ? void 0 : _a.values.length) &&
1656
+ ((_b = result.mediatype) === null || _b === void 0 ? void 0 : _b.value) !== 'collection') {
1657
+ for (const collection of (_d = (_c = result.collection) === null || _c === void 0 ? void 0 : _c.values) !== null && _d !== void 0 ? _d : []) {
1658
+ if (collection === 'loggedin') {
1659
+ loginRequired = true;
1660
+ if (contentWarning)
1661
+ break;
1662
+ }
1663
+ if (collection === 'no-preview') {
1664
+ contentWarning = true;
1665
+ if (loginRequired)
1666
+ break;
1667
+ }
1668
+ }
1669
+ }
1670
+ tiles.push({
1671
+ averageRating: (_e = result.avg_rating) === null || _e === void 0 ? void 0 : _e.value,
1672
+ checked: false,
1673
+ collections: (_g = (_f = result.collection) === null || _f === void 0 ? void 0 : _f.values) !== null && _g !== void 0 ? _g : [],
1674
+ collectionFilesCount: (_j = (_h = result.collection_files_count) === null || _h === void 0 ? void 0 : _h.value) !== null && _j !== void 0 ? _j : 0,
1675
+ collectionSize: (_l = (_k = result.collection_size) === null || _k === void 0 ? void 0 : _k.value) !== null && _l !== void 0 ? _l : 0,
1676
+ commentCount: (_o = (_m = result.num_reviews) === null || _m === void 0 ? void 0 : _m.value) !== null && _o !== void 0 ? _o : 0,
1677
+ creator: (_p = result.creator) === null || _p === void 0 ? void 0 : _p.value,
1678
+ creators: (_r = (_q = result.creator) === null || _q === void 0 ? void 0 : _q.values) !== null && _r !== void 0 ? _r : [],
1679
+ dateAdded: (_s = result.addeddate) === null || _s === void 0 ? void 0 : _s.value,
1680
+ dateArchived: (_t = result.publicdate) === null || _t === void 0 ? void 0 : _t.value,
1681
+ datePublished: (_u = result.date) === null || _u === void 0 ? void 0 : _u.value,
1682
+ dateReviewed: (_v = result.reviewdate) === null || _v === void 0 ? void 0 : _v.value,
1683
+ description: (_w = result.description) === null || _w === void 0 ? void 0 : _w.values.join('\n'),
1684
+ favCount: (_y = (_x = result.num_favorites) === null || _x === void 0 ? void 0 : _x.value) !== null && _y !== void 0 ? _y : 0,
1685
+ href: this.collapseRepeatedQuotes((_z = result.__href__) === null || _z === void 0 ? void 0 : _z.value),
1686
+ identifier: result.identifier,
1687
+ issue: (_0 = result.issue) === null || _0 === void 0 ? void 0 : _0.value,
1688
+ itemCount: (_2 = (_1 = result.item_count) === null || _1 === void 0 ? void 0 : _1.value) !== null && _2 !== void 0 ? _2 : 0,
1689
+ mediatype: (_4 = (_3 = result.mediatype) === null || _3 === void 0 ? void 0 : _3.value) !== null && _4 !== void 0 ? _4 : 'data',
1690
+ snippets: (_6 = (_5 = result.highlight) === null || _5 === void 0 ? void 0 : _5.values) !== null && _6 !== void 0 ? _6 : [],
1691
+ source: (_7 = result.source) === null || _7 === void 0 ? void 0 : _7.value,
1692
+ subjects: (_9 = (_8 = result.subject) === null || _8 === void 0 ? void 0 : _8.values) !== null && _9 !== void 0 ? _9 : [],
1693
+ title: (_11 = (_10 = result.title) === null || _10 === void 0 ? void 0 : _10.value) !== null && _11 !== void 0 ? _11 : '',
1694
+ volume: (_12 = result.volume) === null || _12 === void 0 ? void 0 : _12.value,
1695
+ viewCount: (_14 = (_13 = result.downloads) === null || _13 === void 0 ? void 0 : _13.value) !== null && _14 !== void 0 ? _14 : 0,
1696
+ weeklyViewCount: (_15 = result.week) === null || _15 === void 0 ? void 0 : _15.value,
1697
+ loginRequired,
1698
+ contentWarning,
1699
+ });
1700
+ });
1701
+ datasource[pageNumber] = tiles;
1702
+ this.dataSource = datasource;
1703
+ const visiblePages = this.currentVisiblePageNumbers;
1704
+ const needsReload = visiblePages.includes(pageNumber);
1705
+ if (needsReload) {
1706
+ (_a = this.infiniteScroller) === null || _a === void 0 ? void 0 : _a.refreshAllVisibleCells();
1707
+ }
1708
+ }
1709
+ /**
1710
+ * Returns the input string, but removing one set of quotes from all instances of
1711
+ * ""clauses wrapped in two sets of quotes"". This assumes the quotes are already
1712
+ * URL-encoded.
1713
+ *
1714
+ * This should be a temporary measure to address the fact that the __href__ field
1715
+ * sometimes acquires extra quotation marks during query rewriting. Once there is a
1716
+ * full Lucene parser in place that handles quoted queries correctly, this can likely
1717
+ * be removed.
1718
+ */
1719
+ collapseRepeatedQuotes(str) {
1720
+ return str === null || str === void 0 ? void 0 : str.replace(/%22%22(?!%22%22)(.+?)%22%22/g, '%22$1%22');
1721
+ }
1722
+ /** Fetches the aggregation buckets for the given prefix filter type. */
1723
+ async fetchPrefixFilterBuckets(filterType) {
1724
+ var _a, _b, _c, _d, _e, _f, _g;
1725
+ const trimmedQuery = (_a = this.baseQuery) === null || _a === void 0 ? void 0 : _a.trim();
1726
+ if (!this.canPerformSearch)
1727
+ return [];
1728
+ const filterAggregationKey = prefixFilterAggregationKeys[filterType];
1729
+ const sortParams = this.sortParam ? [this.sortParam] : [];
1730
+ const params = {
1731
+ ...this.collectionParams,
1732
+ query: trimmedQuery || '',
1733
+ rows: 0,
1734
+ filters: this.filterMap,
1735
+ // Only fetch the firstTitle or firstCreator aggregation
1736
+ aggregations: { simpleParams: [filterAggregationKey] },
1737
+ // Fetch all 26 letter buckets
1738
+ aggregationsSize: 26,
1739
+ };
1740
+ params.uid = await this.requestUID({ ...params, sort: sortParams }, 'aggregations');
1741
+ const searchResponse = await ((_b = this.searchService) === null || _b === void 0 ? void 0 : _b.search(params, this.searchType));
1742
+ return ((_g = (_f = (_e = (_d = (_c = searchResponse === null || searchResponse === void 0 ? void 0 : searchResponse.success) === null || _c === void 0 ? void 0 : _c.response) === null || _d === void 0 ? void 0 : _d.aggregations) === null || _e === void 0 ? void 0 : _e[filterAggregationKey]) === null || _f === void 0 ? void 0 : _f.buckets) !== null && _g !== void 0 ? _g : []);
1743
+ }
1744
+ /** Fetches and caches the prefix filter counts for the given filter type. */
1745
+ async updatePrefixFilterCounts(filterType) {
1746
+ const { facetFetchQueryKey } = this;
1747
+ const buckets = await this.fetchPrefixFilterBuckets(filterType);
1748
+ // Don't update the filter counts for an outdated query (if it has been changed
1749
+ // since we sent the request)
1750
+ const queryChangedSinceFetch = facetFetchQueryKey !== this.facetFetchQueryKey;
1751
+ if (queryChangedSinceFetch)
1752
+ return;
1753
+ // Unpack the aggregation buckets into a simple map like { 'A': 50, 'B': 25, ... }
1754
+ this.prefixFilterCountMap = { ...this.prefixFilterCountMap }; // Clone the object to trigger an update
1755
+ this.prefixFilterCountMap[filterType] = buckets.reduce((acc, bucket) => {
1756
+ acc[bucket.key.toUpperCase()] = bucket.doc_count;
1757
+ return acc;
1758
+ }, {});
1759
+ }
1760
+ /**
1761
+ * Fetches and caches the prefix filter counts for the current sort type,
1762
+ * provided it is one that permits prefix filtering. (If not, this does nothing).
1763
+ */
1764
+ async updatePrefixFiltersForCurrentSort() {
1765
+ if (['title', 'creator'].includes(this.selectedSort)) {
1766
+ const filterType = this.selectedSort;
1767
+ if (!this.prefixFilterCountMap[filterType]) {
1768
+ this.updatePrefixFilterCounts(filterType);
1769
+ }
1770
+ }
1771
+ }
1772
+ /**
1773
+ * Clears the cached letter counts for both title and creator, and
1774
+ * fetches a new set of counts for whichever of them is the currently
1775
+ * selected sort option (which may be neither).
1776
+ *
1777
+ * Call this whenever the counts are invalidated (e.g., by a query change).
1778
+ */
1779
+ refreshLetterCounts() {
1780
+ if (Object.keys(this.prefixFilterCountMap).length > 0) {
1781
+ this.prefixFilterCountMap = {};
1782
+ }
1783
+ this.updatePrefixFiltersForCurrentSort();
1784
+ }
1785
+ /**
1786
+ * Callback when a result is selected
1787
+ */
1788
+ resultSelected(event) {
1789
+ var _a, _b, _c;
1790
+ if (this.isManageView) {
1791
+ // Checked/unchecked state change -- rerender to ensure it propagates
1792
+ // this.mapDataSource(model => ({ ...model }));
1793
+ const cellIndex = Object.values(this.dataSource)
1794
+ .flat()
1795
+ .indexOf(event.detail);
1796
+ if (cellIndex >= 0)
1797
+ (_a = this.infiniteScroller) === null || _a === void 0 ? void 0 : _a.refreshCell(cellIndex - this.tileModelOffset);
1798
+ }
1799
+ (_b = this.analyticsHandler) === null || _b === void 0 ? void 0 : _b.sendEvent({
1800
+ category: this.searchContext,
1801
+ action: analyticsActions.resultSelected,
1802
+ label: event.detail.mediatype,
1803
+ });
1804
+ (_c = this.analyticsHandler) === null || _c === void 0 ? void 0 : _c.sendEvent({
1805
+ category: this.searchContext,
1806
+ action: analyticsActions.resultSelected,
1807
+ label: `page-${this.currentPage}`,
1808
+ });
1809
+ }
1810
+ cellForIndex(index) {
1811
+ const model = this.tileModelAtCellIndex(index);
1812
+ if (!model)
1813
+ return undefined;
1666
1814
  return html `
1667
1815
  <tile-dispatcher
1668
1816
  .collectionPagePath=${this.collectionPagePath}
@@ -1676,25 +1824,26 @@ let CollectionBrowser = class CollectionBrowser extends LitElement {
1676
1824
  .creatorFilter=${this.selectedCreatorFilter}
1677
1825
  .mobileBreakpoint=${this.mobileBreakpoint}
1678
1826
  .loggedIn=${this.loggedIn}
1827
+ .isManageView=${this.isManageView}
1679
1828
  ?enableHoverPane=${true}
1680
1829
  @resultSelected=${(e) => this.resultSelected(e)}
1681
1830
  >
1682
1831
  </tile-dispatcher>
1683
- `;
1684
- }
1685
- /**
1686
- * When the user scrolls near to the bottom of the page, fetch the next page
1687
- * increase the number of pages to render and start fetching data for the new page
1688
- */
1689
- scrollThresholdReached() {
1690
- if (!this.endOfDataReached) {
1691
- this.pagesToRender += 1;
1692
- this.fetchPage(this.pagesToRender);
1693
- }
1694
- }
1695
- static get styles() {
1696
- return [
1697
- srOnlyStyle,
1832
+ `;
1833
+ }
1834
+ /**
1835
+ * When the user scrolls near to the bottom of the page, fetch the next page
1836
+ * increase the number of pages to render and start fetching data for the new page
1837
+ */
1838
+ scrollThresholdReached() {
1839
+ if (!this.endOfDataReached) {
1840
+ this.pagesToRender += 1;
1841
+ this.fetchPage(this.pagesToRender);
1842
+ }
1843
+ }
1844
+ static get styles() {
1845
+ return [
1846
+ srOnlyStyle,
1698
1847
  css `
1699
1848
  :host {
1700
1849
  display: block;
@@ -2065,168 +2214,168 @@ let CollectionBrowser = class CollectionBrowser extends LitElement {
2065
2214
  infinite-scroller.hidden {
2066
2215
  display: none;
2067
2216
  }
2068
- `,
2069
- ];
2070
- }
2071
- };
2072
- __decorate([
2073
- property({ type: String })
2074
- ], CollectionBrowser.prototype, "baseNavigationUrl", void 0);
2075
- __decorate([
2076
- property({ type: String })
2077
- ], CollectionBrowser.prototype, "baseImageUrl", void 0);
2078
- __decorate([
2079
- property({ type: Object })
2080
- ], CollectionBrowser.prototype, "searchService", void 0);
2081
- __decorate([
2082
- property({ type: String })
2083
- ], CollectionBrowser.prototype, "searchType", void 0);
2084
- __decorate([
2085
- property({ type: String })
2086
- ], CollectionBrowser.prototype, "withinCollection", void 0);
2087
- __decorate([
2088
- property({ type: String })
2089
- ], CollectionBrowser.prototype, "baseQuery", void 0);
2090
- __decorate([
2091
- property({ type: String })
2092
- ], CollectionBrowser.prototype, "displayMode", void 0);
2093
- __decorate([
2094
- property({ type: Object })
2095
- ], CollectionBrowser.prototype, "sortParam", void 0);
2096
- __decorate([
2097
- property({ type: String })
2098
- ], CollectionBrowser.prototype, "selectedSort", void 0);
2099
- __decorate([
2100
- property({ type: String })
2101
- ], CollectionBrowser.prototype, "selectedTitleFilter", void 0);
2102
- __decorate([
2103
- property({ type: String })
2104
- ], CollectionBrowser.prototype, "selectedCreatorFilter", void 0);
2105
- __decorate([
2106
- property({ type: String })
2107
- ], CollectionBrowser.prototype, "sortDirection", void 0);
2108
- __decorate([
2109
- property({ type: Number })
2110
- ], CollectionBrowser.prototype, "pageSize", void 0);
2111
- __decorate([
2112
- property({ type: Object })
2113
- ], CollectionBrowser.prototype, "resizeObserver", void 0);
2114
- __decorate([
2115
- property({ type: Number })
2116
- ], CollectionBrowser.prototype, "currentPage", void 0);
2117
- __decorate([
2118
- property({ type: String })
2119
- ], CollectionBrowser.prototype, "minSelectedDate", void 0);
2120
- __decorate([
2121
- property({ type: String })
2122
- ], CollectionBrowser.prototype, "maxSelectedDate", void 0);
2123
- __decorate([
2124
- property({ type: Object })
2125
- ], CollectionBrowser.prototype, "selectedFacets", void 0);
2126
- __decorate([
2127
- property({ type: Boolean })
2128
- ], CollectionBrowser.prototype, "showHistogramDatePicker", void 0);
2129
- __decorate([
2130
- property({ type: String })
2131
- ], CollectionBrowser.prototype, "collectionPagePath", void 0);
2132
- __decorate([
2133
- property({ type: Object })
2134
- ], CollectionBrowser.prototype, "collectionInfo", void 0);
2135
- __decorate([
2136
- property({ type: Array })
2137
- ], CollectionBrowser.prototype, "parentCollections", void 0);
2138
- __decorate([
2139
- property({ type: String, reflect: true })
2140
- ], CollectionBrowser.prototype, "searchContext", void 0);
2141
- __decorate([
2142
- property({ type: Object })
2143
- ], CollectionBrowser.prototype, "collectionNameCache", void 0);
2144
- __decorate([
2145
- property({ type: String })
2146
- ], CollectionBrowser.prototype, "pageContext", void 0);
2147
- __decorate([
2148
- property({ type: Object })
2149
- ], CollectionBrowser.prototype, "restorationStateHandler", void 0);
2150
- __decorate([
2151
- property({ type: Number })
2152
- ], CollectionBrowser.prototype, "mobileBreakpoint", void 0);
2153
- __decorate([
2154
- property({ type: Boolean })
2155
- ], CollectionBrowser.prototype, "loggedIn", void 0);
2156
- __decorate([
2157
- property({ type: Object })
2158
- ], CollectionBrowser.prototype, "modalManager", void 0);
2159
- __decorate([
2160
- property({ type: Object })
2161
- ], CollectionBrowser.prototype, "featureFeedbackService", void 0);
2162
- __decorate([
2163
- property({ type: Object })
2164
- ], CollectionBrowser.prototype, "recaptchaManager", void 0);
2165
- __decorate([
2166
- property({ type: Boolean })
2167
- ], CollectionBrowser.prototype, "isManageView", void 0);
2168
- __decorate([
2169
- state()
2170
- ], CollectionBrowser.prototype, "pagesToRender", void 0);
2171
- __decorate([
2172
- state()
2173
- ], CollectionBrowser.prototype, "searchResultsLoading", void 0);
2174
- __decorate([
2175
- state()
2176
- ], CollectionBrowser.prototype, "facetsLoading", void 0);
2177
- __decorate([
2178
- state()
2179
- ], CollectionBrowser.prototype, "fullYearAggregationLoading", void 0);
2180
- __decorate([
2181
- state()
2182
- ], CollectionBrowser.prototype, "aggregations", void 0);
2183
- __decorate([
2184
- state()
2185
- ], CollectionBrowser.prototype, "fullYearsHistogramAggregation", void 0);
2186
- __decorate([
2187
- state()
2188
- ], CollectionBrowser.prototype, "totalResults", void 0);
2189
- __decorate([
2190
- state()
2191
- ], CollectionBrowser.prototype, "queryErrorMessage", void 0);
2192
- __decorate([
2193
- state()
2194
- ], CollectionBrowser.prototype, "mobileView", void 0);
2195
- __decorate([
2196
- state()
2197
- ], CollectionBrowser.prototype, "mobileFacetsVisible", void 0);
2198
- __decorate([
2199
- state()
2200
- ], CollectionBrowser.prototype, "contentWidth", void 0);
2201
- __decorate([
2202
- state()
2203
- ], CollectionBrowser.prototype, "defaultSortField", void 0);
2204
- __decorate([
2205
- state()
2206
- ], CollectionBrowser.prototype, "defaultSortDirection", void 0);
2207
- __decorate([
2208
- state()
2209
- ], CollectionBrowser.prototype, "placeholderType", void 0);
2210
- __decorate([
2211
- state()
2212
- ], CollectionBrowser.prototype, "prefixFilterCountMap", void 0);
2213
- __decorate([
2214
- query('#content-container')
2215
- ], CollectionBrowser.prototype, "contentContainer", void 0);
2216
- __decorate([
2217
- query('#left-column')
2218
- ], CollectionBrowser.prototype, "leftColumn", void 0);
2219
- __decorate([
2220
- query('collection-facets')
2221
- ], CollectionBrowser.prototype, "collectionFacets", void 0);
2222
- __decorate([
2223
- property({ type: Object, attribute: false })
2224
- ], CollectionBrowser.prototype, "analyticsHandler", void 0);
2225
- __decorate([
2226
- query('infinite-scroller')
2227
- ], CollectionBrowser.prototype, "infiniteScroller", void 0);
2228
- CollectionBrowser = __decorate([
2229
- customElement('collection-browser')
2230
- ], CollectionBrowser);
2231
- export { CollectionBrowser };
2217
+ `,
2218
+ ];
2219
+ }
2220
+ };
2221
+ __decorate([
2222
+ property({ type: String })
2223
+ ], CollectionBrowser.prototype, "baseNavigationUrl", void 0);
2224
+ __decorate([
2225
+ property({ type: String })
2226
+ ], CollectionBrowser.prototype, "baseImageUrl", void 0);
2227
+ __decorate([
2228
+ property({ type: Object })
2229
+ ], CollectionBrowser.prototype, "searchService", void 0);
2230
+ __decorate([
2231
+ property({ type: String })
2232
+ ], CollectionBrowser.prototype, "searchType", void 0);
2233
+ __decorate([
2234
+ property({ type: String })
2235
+ ], CollectionBrowser.prototype, "withinCollection", void 0);
2236
+ __decorate([
2237
+ property({ type: String })
2238
+ ], CollectionBrowser.prototype, "baseQuery", void 0);
2239
+ __decorate([
2240
+ property({ type: String })
2241
+ ], CollectionBrowser.prototype, "displayMode", void 0);
2242
+ __decorate([
2243
+ property({ type: Object })
2244
+ ], CollectionBrowser.prototype, "sortParam", void 0);
2245
+ __decorate([
2246
+ property({ type: String })
2247
+ ], CollectionBrowser.prototype, "selectedSort", void 0);
2248
+ __decorate([
2249
+ property({ type: String })
2250
+ ], CollectionBrowser.prototype, "selectedTitleFilter", void 0);
2251
+ __decorate([
2252
+ property({ type: String })
2253
+ ], CollectionBrowser.prototype, "selectedCreatorFilter", void 0);
2254
+ __decorate([
2255
+ property({ type: String })
2256
+ ], CollectionBrowser.prototype, "sortDirection", void 0);
2257
+ __decorate([
2258
+ property({ type: Number })
2259
+ ], CollectionBrowser.prototype, "pageSize", void 0);
2260
+ __decorate([
2261
+ property({ type: Object })
2262
+ ], CollectionBrowser.prototype, "resizeObserver", void 0);
2263
+ __decorate([
2264
+ property({ type: Number })
2265
+ ], CollectionBrowser.prototype, "currentPage", void 0);
2266
+ __decorate([
2267
+ property({ type: String })
2268
+ ], CollectionBrowser.prototype, "minSelectedDate", void 0);
2269
+ __decorate([
2270
+ property({ type: String })
2271
+ ], CollectionBrowser.prototype, "maxSelectedDate", void 0);
2272
+ __decorate([
2273
+ property({ type: Object })
2274
+ ], CollectionBrowser.prototype, "selectedFacets", void 0);
2275
+ __decorate([
2276
+ property({ type: Boolean })
2277
+ ], CollectionBrowser.prototype, "showHistogramDatePicker", void 0);
2278
+ __decorate([
2279
+ property({ type: String })
2280
+ ], CollectionBrowser.prototype, "collectionPagePath", void 0);
2281
+ __decorate([
2282
+ property({ type: Object })
2283
+ ], CollectionBrowser.prototype, "collectionInfo", void 0);
2284
+ __decorate([
2285
+ property({ type: Array })
2286
+ ], CollectionBrowser.prototype, "parentCollections", void 0);
2287
+ __decorate([
2288
+ property({ type: String, reflect: true })
2289
+ ], CollectionBrowser.prototype, "searchContext", void 0);
2290
+ __decorate([
2291
+ property({ type: Object })
2292
+ ], CollectionBrowser.prototype, "collectionNameCache", void 0);
2293
+ __decorate([
2294
+ property({ type: String })
2295
+ ], CollectionBrowser.prototype, "pageContext", void 0);
2296
+ __decorate([
2297
+ property({ type: Object })
2298
+ ], CollectionBrowser.prototype, "restorationStateHandler", void 0);
2299
+ __decorate([
2300
+ property({ type: Number })
2301
+ ], CollectionBrowser.prototype, "mobileBreakpoint", void 0);
2302
+ __decorate([
2303
+ property({ type: Boolean })
2304
+ ], CollectionBrowser.prototype, "loggedIn", void 0);
2305
+ __decorate([
2306
+ property({ type: Object })
2307
+ ], CollectionBrowser.prototype, "modalManager", void 0);
2308
+ __decorate([
2309
+ property({ type: Object })
2310
+ ], CollectionBrowser.prototype, "featureFeedbackService", void 0);
2311
+ __decorate([
2312
+ property({ type: Object })
2313
+ ], CollectionBrowser.prototype, "recaptchaManager", void 0);
2314
+ __decorate([
2315
+ property({ type: Boolean })
2316
+ ], CollectionBrowser.prototype, "isManageView", void 0);
2317
+ __decorate([
2318
+ state()
2319
+ ], CollectionBrowser.prototype, "pagesToRender", void 0);
2320
+ __decorate([
2321
+ state()
2322
+ ], CollectionBrowser.prototype, "searchResultsLoading", void 0);
2323
+ __decorate([
2324
+ state()
2325
+ ], CollectionBrowser.prototype, "facetsLoading", void 0);
2326
+ __decorate([
2327
+ state()
2328
+ ], CollectionBrowser.prototype, "fullYearAggregationLoading", void 0);
2329
+ __decorate([
2330
+ state()
2331
+ ], CollectionBrowser.prototype, "aggregations", void 0);
2332
+ __decorate([
2333
+ state()
2334
+ ], CollectionBrowser.prototype, "fullYearsHistogramAggregation", void 0);
2335
+ __decorate([
2336
+ state()
2337
+ ], CollectionBrowser.prototype, "totalResults", void 0);
2338
+ __decorate([
2339
+ state()
2340
+ ], CollectionBrowser.prototype, "queryErrorMessage", void 0);
2341
+ __decorate([
2342
+ state()
2343
+ ], CollectionBrowser.prototype, "mobileView", void 0);
2344
+ __decorate([
2345
+ state()
2346
+ ], CollectionBrowser.prototype, "mobileFacetsVisible", void 0);
2347
+ __decorate([
2348
+ state()
2349
+ ], CollectionBrowser.prototype, "contentWidth", void 0);
2350
+ __decorate([
2351
+ state()
2352
+ ], CollectionBrowser.prototype, "defaultSortField", void 0);
2353
+ __decorate([
2354
+ state()
2355
+ ], CollectionBrowser.prototype, "defaultSortDirection", void 0);
2356
+ __decorate([
2357
+ state()
2358
+ ], CollectionBrowser.prototype, "placeholderType", void 0);
2359
+ __decorate([
2360
+ state()
2361
+ ], CollectionBrowser.prototype, "prefixFilterCountMap", void 0);
2362
+ __decorate([
2363
+ query('#content-container')
2364
+ ], CollectionBrowser.prototype, "contentContainer", void 0);
2365
+ __decorate([
2366
+ query('#left-column')
2367
+ ], CollectionBrowser.prototype, "leftColumn", void 0);
2368
+ __decorate([
2369
+ query('collection-facets')
2370
+ ], CollectionBrowser.prototype, "collectionFacets", void 0);
2371
+ __decorate([
2372
+ property({ type: Object, attribute: false })
2373
+ ], CollectionBrowser.prototype, "analyticsHandler", void 0);
2374
+ __decorate([
2375
+ query('infinite-scroller')
2376
+ ], CollectionBrowser.prototype, "infiniteScroller", void 0);
2377
+ CollectionBrowser = __decorate([
2378
+ customElement('collection-browser')
2379
+ ], CollectionBrowser);
2380
+ export { CollectionBrowser };
2232
2381
  //# sourceMappingURL=collection-browser.js.map