@internetarchive/collection-browser 2.1.8-alpha2 → 2.1.9-alpha.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 (305) hide show
  1. package/.editorconfig +29 -29
  2. package/.husky/pre-commit +4 -4
  3. package/LICENSE +661 -661
  4. package/README.md +83 -83
  5. package/dist/index.d.ts +12 -12
  6. package/dist/index.js +12 -12
  7. package/dist/src/app-root.d.ts +88 -88
  8. package/dist/src/app-root.js +475 -475
  9. package/dist/src/assets/img/icons/arrow-left.d.ts +2 -2
  10. package/dist/src/assets/img/icons/arrow-left.js +2 -2
  11. package/dist/src/assets/img/icons/arrow-right.d.ts +2 -2
  12. package/dist/src/assets/img/icons/arrow-right.js +2 -2
  13. package/dist/src/assets/img/icons/chevron.d.ts +2 -2
  14. package/dist/src/assets/img/icons/chevron.js +2 -2
  15. package/dist/src/assets/img/icons/contract.d.ts +2 -2
  16. package/dist/src/assets/img/icons/contract.js +2 -2
  17. package/dist/src/assets/img/icons/empty-query.d.ts +2 -2
  18. package/dist/src/assets/img/icons/empty-query.js +2 -2
  19. package/dist/src/assets/img/icons/expand.d.ts +2 -2
  20. package/dist/src/assets/img/icons/expand.js +2 -2
  21. package/dist/src/assets/img/icons/eye-closed.d.ts +2 -2
  22. package/dist/src/assets/img/icons/eye-closed.js +2 -2
  23. package/dist/src/assets/img/icons/eye.d.ts +2 -2
  24. package/dist/src/assets/img/icons/eye.js +2 -2
  25. package/dist/src/assets/img/icons/favorite-filled.d.ts +1 -1
  26. package/dist/src/assets/img/icons/favorite-filled.js +2 -2
  27. package/dist/src/assets/img/icons/favorite-unfilled.d.ts +1 -1
  28. package/dist/src/assets/img/icons/favorite-unfilled.js +2 -2
  29. package/dist/src/assets/img/icons/login-required.d.ts +1 -1
  30. package/dist/src/assets/img/icons/login-required.js +2 -2
  31. package/dist/src/assets/img/icons/mediatype/account.d.ts +1 -1
  32. package/dist/src/assets/img/icons/mediatype/account.js +2 -2
  33. package/dist/src/assets/img/icons/mediatype/audio.d.ts +1 -1
  34. package/dist/src/assets/img/icons/mediatype/audio.js +2 -2
  35. package/dist/src/assets/img/icons/mediatype/collection.d.ts +1 -1
  36. package/dist/src/assets/img/icons/mediatype/collection.js +2 -2
  37. package/dist/src/assets/img/icons/mediatype/data.d.ts +1 -1
  38. package/dist/src/assets/img/icons/mediatype/data.js +2 -2
  39. package/dist/src/assets/img/icons/mediatype/etree.d.ts +1 -1
  40. package/dist/src/assets/img/icons/mediatype/etree.js +2 -2
  41. package/dist/src/assets/img/icons/mediatype/film.d.ts +1 -1
  42. package/dist/src/assets/img/icons/mediatype/film.js +2 -2
  43. package/dist/src/assets/img/icons/mediatype/images.d.ts +1 -1
  44. package/dist/src/assets/img/icons/mediatype/images.js +2 -2
  45. package/dist/src/assets/img/icons/mediatype/radio.d.ts +1 -1
  46. package/dist/src/assets/img/icons/mediatype/radio.js +2 -2
  47. package/dist/src/assets/img/icons/mediatype/search.d.ts +1 -1
  48. package/dist/src/assets/img/icons/mediatype/search.js +2 -2
  49. package/dist/src/assets/img/icons/mediatype/software.d.ts +1 -1
  50. package/dist/src/assets/img/icons/mediatype/software.js +2 -2
  51. package/dist/src/assets/img/icons/mediatype/texts.d.ts +1 -1
  52. package/dist/src/assets/img/icons/mediatype/texts.js +2 -2
  53. package/dist/src/assets/img/icons/mediatype/tv.d.ts +1 -1
  54. package/dist/src/assets/img/icons/mediatype/tv.js +2 -2
  55. package/dist/src/assets/img/icons/mediatype/video.d.ts +1 -1
  56. package/dist/src/assets/img/icons/mediatype/video.js +2 -2
  57. package/dist/src/assets/img/icons/mediatype/web.d.ts +1 -1
  58. package/dist/src/assets/img/icons/mediatype/web.js +2 -2
  59. package/dist/src/assets/img/icons/null-result.d.ts +2 -2
  60. package/dist/src/assets/img/icons/null-result.js +2 -2
  61. package/dist/src/assets/img/icons/restricted.d.ts +1 -1
  62. package/dist/src/assets/img/icons/restricted.js +2 -2
  63. package/dist/src/assets/img/icons/reviews.d.ts +1 -1
  64. package/dist/src/assets/img/icons/reviews.js +2 -2
  65. package/dist/src/assets/img/icons/upload.d.ts +1 -1
  66. package/dist/src/assets/img/icons/upload.js +2 -2
  67. package/dist/src/assets/img/icons/views.d.ts +1 -1
  68. package/dist/src/assets/img/icons/views.js +2 -2
  69. package/dist/src/circular-activity-indicator.d.ts +5 -5
  70. package/dist/src/circular-activity-indicator.js +17 -17
  71. package/dist/src/collection-browser.d.ts +446 -446
  72. package/dist/src/collection-browser.js +1409 -1411
  73. package/dist/src/collection-browser.js.map +1 -1
  74. package/dist/src/collection-facets/facet-row.d.ts +30 -30
  75. package/dist/src/collection-facets/facet-row.js +114 -114
  76. package/dist/src/collection-facets/facet-tombstone-row.d.ts +5 -5
  77. package/dist/src/collection-facets/facet-tombstone-row.js +15 -15
  78. package/dist/src/collection-facets/facets-template.d.ts +17 -17
  79. package/dist/src/collection-facets/facets-template.js +114 -114
  80. package/dist/src/collection-facets/more-facets-content.d.ts +74 -70
  81. package/dist/src/collection-facets/more-facets-content.js +360 -354
  82. package/dist/src/collection-facets/more-facets-content.js.map +1 -1
  83. package/dist/src/collection-facets/more-facets-pagination.d.ts +36 -36
  84. package/dist/src/collection-facets/more-facets-pagination.js +196 -196
  85. package/dist/src/collection-facets/toggle-switch.d.ts +41 -41
  86. package/dist/src/collection-facets/toggle-switch.js +94 -94
  87. package/dist/src/collection-facets.d.ts +103 -103
  88. package/dist/src/collection-facets.js +511 -510
  89. package/dist/src/collection-facets.js.map +1 -1
  90. package/dist/src/data-source/collection-browser-data-source-interface.d.ts +236 -236
  91. package/dist/src/data-source/collection-browser-data-source-interface.js +1 -1
  92. package/dist/src/data-source/collection-browser-data-source.d.ts +364 -364
  93. package/dist/src/data-source/collection-browser-data-source.js +946 -946
  94. package/dist/src/data-source/collection-browser-data-source.js.map +1 -1
  95. package/dist/src/data-source/collection-browser-query-state.d.ts +43 -43
  96. package/dist/src/data-source/collection-browser-query-state.js +1 -1
  97. package/dist/src/data-source/models.d.ts +28 -28
  98. package/dist/src/data-source/models.js +8 -8
  99. package/dist/src/empty-placeholder.d.ts +23 -23
  100. package/dist/src/empty-placeholder.js +74 -74
  101. package/dist/src/expanded-date-picker.d.ts +43 -43
  102. package/dist/src/expanded-date-picker.js +109 -109
  103. package/dist/src/language-code-handler/language-code-handler.d.ts +37 -37
  104. package/dist/src/language-code-handler/language-code-handler.js +26 -26
  105. package/dist/src/language-code-handler/language-code-mapping.d.ts +1 -1
  106. package/dist/src/language-code-handler/language-code-mapping.js +562 -562
  107. package/dist/src/manage/manage-bar.d.ts +30 -30
  108. package/dist/src/manage/manage-bar.js +61 -61
  109. package/dist/src/mediatype/mediatype-config.d.ts +3 -3
  110. package/dist/src/mediatype/mediatype-config.js +91 -91
  111. package/dist/src/models.d.ts +198 -198
  112. package/dist/src/models.js +381 -381
  113. package/dist/src/restoration-state-handler.d.ts +70 -70
  114. package/dist/src/restoration-state-handler.js +357 -357
  115. package/dist/src/sort-filter-bar/alpha-bar-tooltip.d.ts +6 -6
  116. package/dist/src/sort-filter-bar/alpha-bar-tooltip.js +24 -24
  117. package/dist/src/sort-filter-bar/alpha-bar.d.ts +21 -21
  118. package/dist/src/sort-filter-bar/alpha-bar.js +128 -128
  119. package/dist/src/sort-filter-bar/img/compact.d.ts +1 -1
  120. package/dist/src/sort-filter-bar/img/compact.js +2 -2
  121. package/dist/src/sort-filter-bar/img/list.d.ts +1 -1
  122. package/dist/src/sort-filter-bar/img/list.js +2 -2
  123. package/dist/src/sort-filter-bar/img/sort-toggle-disabled.d.ts +1 -1
  124. package/dist/src/sort-filter-bar/img/sort-toggle-disabled.js +2 -2
  125. package/dist/src/sort-filter-bar/img/sort-toggle-down.d.ts +1 -1
  126. package/dist/src/sort-filter-bar/img/sort-toggle-down.js +2 -2
  127. package/dist/src/sort-filter-bar/img/sort-toggle-up.d.ts +1 -1
  128. package/dist/src/sort-filter-bar/img/sort-toggle-up.js +2 -2
  129. package/dist/src/sort-filter-bar/img/sort-triangle.d.ts +1 -1
  130. package/dist/src/sort-filter-bar/img/sort-triangle.js +2 -2
  131. package/dist/src/sort-filter-bar/img/tile.d.ts +1 -1
  132. package/dist/src/sort-filter-bar/img/tile.js +2 -2
  133. package/dist/src/sort-filter-bar/sort-filter-bar.d.ts +221 -221
  134. package/dist/src/sort-filter-bar/sort-filter-bar.js +695 -691
  135. package/dist/src/sort-filter-bar/sort-filter-bar.js.map +1 -1
  136. package/dist/src/styles/ia-button.d.ts +2 -2
  137. package/dist/src/styles/ia-button.js +16 -16
  138. package/dist/src/styles/item-image-styles.d.ts +8 -8
  139. package/dist/src/styles/item-image-styles.js +9 -9
  140. package/dist/src/styles/sr-only.d.ts +1 -1
  141. package/dist/src/styles/sr-only.js +2 -2
  142. package/dist/src/tiles/base-tile-component.d.ts +19 -19
  143. package/dist/src/tiles/base-tile-component.js +63 -63
  144. package/dist/src/tiles/collection-browser-loading-tile.d.ts +5 -5
  145. package/dist/src/tiles/collection-browser-loading-tile.js +15 -15
  146. package/dist/src/tiles/grid/account-tile.d.ts +18 -18
  147. package/dist/src/tiles/grid/account-tile.js +72 -72
  148. package/dist/src/tiles/grid/collection-tile.d.ts +15 -15
  149. package/dist/src/tiles/grid/collection-tile.js +80 -80
  150. package/dist/src/tiles/grid/item-tile.d.ts +30 -30
  151. package/dist/src/tiles/grid/item-tile.js +149 -149
  152. package/dist/src/tiles/grid/search-tile.d.ts +10 -10
  153. package/dist/src/tiles/grid/search-tile.js +51 -51
  154. package/dist/src/tiles/grid/styles/tile-grid-shared-styles.d.ts +1 -1
  155. package/dist/src/tiles/grid/styles/tile-grid-shared-styles.js +8 -8
  156. package/dist/src/tiles/grid/tile-stats.d.ts +11 -11
  157. package/dist/src/tiles/grid/tile-stats.js +53 -53
  158. package/dist/src/tiles/hover/hover-pane-controller.d.ts +219 -219
  159. package/dist/src/tiles/hover/hover-pane-controller.js +352 -352
  160. package/dist/src/tiles/hover/tile-hover-pane.d.ts +15 -15
  161. package/dist/src/tiles/hover/tile-hover-pane.js +38 -38
  162. package/dist/src/tiles/image-block.d.ts +17 -17
  163. package/dist/src/tiles/image-block.js +73 -73
  164. package/dist/src/tiles/item-image.d.ts +39 -39
  165. package/dist/src/tiles/item-image.js +154 -154
  166. package/dist/src/tiles/list/tile-list-compact-header.d.ts +6 -6
  167. package/dist/src/tiles/list/tile-list-compact-header.js +38 -38
  168. package/dist/src/tiles/list/tile-list-compact.d.ts +15 -15
  169. package/dist/src/tiles/list/tile-list-compact.js +114 -114
  170. package/dist/src/tiles/list/tile-list.d.ts +50 -50
  171. package/dist/src/tiles/list/tile-list.js +315 -315
  172. package/dist/src/tiles/mediatype-icon.d.ts +9 -9
  173. package/dist/src/tiles/mediatype-icon.js +47 -47
  174. package/dist/src/tiles/overlay/icon-overlay.d.ts +10 -10
  175. package/dist/src/tiles/overlay/icon-overlay.js +40 -40
  176. package/dist/src/tiles/overlay/icon-text-overlay.d.ts +9 -9
  177. package/dist/src/tiles/overlay/icon-text-overlay.js +38 -38
  178. package/dist/src/tiles/overlay/text-overlay.d.ts +10 -10
  179. package/dist/src/tiles/overlay/text-overlay.js +42 -42
  180. package/dist/src/tiles/review-block.d.ts +12 -12
  181. package/dist/src/tiles/review-block.js +56 -56
  182. package/dist/src/tiles/text-snippet-block.d.ts +27 -27
  183. package/dist/src/tiles/text-snippet-block.js +73 -73
  184. package/dist/src/tiles/tile-dispatcher.d.ts +64 -64
  185. package/dist/src/tiles/tile-dispatcher.js +229 -229
  186. package/dist/src/tiles/tile-display-value-provider.d.ts +47 -47
  187. package/dist/src/tiles/tile-display-value-provider.js +94 -94
  188. package/dist/src/utils/analytics-events.d.ts +26 -26
  189. package/dist/src/utils/analytics-events.js +28 -28
  190. package/dist/src/utils/array-equals.d.ts +4 -4
  191. package/dist/src/utils/array-equals.js +10 -10
  192. package/dist/src/utils/collapse-repeated-quotes.d.ts +11 -11
  193. package/dist/src/utils/collapse-repeated-quotes.js +13 -13
  194. package/dist/src/utils/format-count.d.ts +7 -7
  195. package/dist/src/utils/format-count.js +76 -76
  196. package/dist/src/utils/format-date.d.ts +2 -2
  197. package/dist/src/utils/format-date.js +25 -25
  198. package/dist/src/utils/format-unit-size.d.ts +2 -2
  199. package/dist/src/utils/format-unit-size.js +33 -33
  200. package/dist/src/utils/local-date-from-utc.d.ts +9 -9
  201. package/dist/src/utils/local-date-from-utc.js +15 -15
  202. package/dist/src/utils/log.d.ts +7 -7
  203. package/dist/src/utils/log.js +15 -15
  204. package/dist/src/utils/resolve-mediatype.d.ts +8 -8
  205. package/dist/src/utils/resolve-mediatype.js +23 -23
  206. package/dist/src/utils/sha1.d.ts +2 -2
  207. package/dist/src/utils/sha1.js +8 -8
  208. package/dist/test/collection-browser.test.d.ts +1 -1
  209. package/dist/test/collection-browser.test.js +1283 -1283
  210. package/dist/test/collection-facets/facet-row.test.d.ts +1 -1
  211. package/dist/test/collection-facets/facet-row.test.js +203 -203
  212. package/dist/test/collection-facets/facets-template.test.d.ts +1 -1
  213. package/dist/test/collection-facets/facets-template.test.js +105 -105
  214. package/dist/test/collection-facets/more-facets-content.test.d.ts +1 -1
  215. package/dist/test/collection-facets/more-facets-content.test.js +141 -135
  216. package/dist/test/collection-facets/more-facets-content.test.js.map +1 -1
  217. package/dist/test/collection-facets/more-facets-pagination.test.d.ts +1 -1
  218. package/dist/test/collection-facets/more-facets-pagination.test.js +117 -117
  219. package/dist/test/collection-facets/toggle-switch.test.d.ts +1 -1
  220. package/dist/test/collection-facets/toggle-switch.test.js +73 -73
  221. package/dist/test/collection-facets.test.d.ts +2 -2
  222. package/dist/test/collection-facets.test.js +652 -654
  223. package/dist/test/collection-facets.test.js.map +1 -1
  224. package/dist/test/data-source/collection-browser-data-source.test.d.ts +1 -1
  225. package/dist/test/data-source/collection-browser-data-source.test.js +89 -89
  226. package/dist/test/empty-placeholder.test.d.ts +1 -1
  227. package/dist/test/empty-placeholder.test.js +63 -63
  228. package/dist/test/expanded-date-picker.test.d.ts +1 -1
  229. package/dist/test/expanded-date-picker.test.js +95 -95
  230. package/dist/test/icon-overlay.test.d.ts +1 -1
  231. package/dist/test/icon-overlay.test.js +24 -24
  232. package/dist/test/image-block.test.d.ts +1 -1
  233. package/dist/test/image-block.test.js +48 -48
  234. package/dist/test/item-image.test.d.ts +1 -1
  235. package/dist/test/item-image.test.js +85 -85
  236. package/dist/test/manage/manage-bar.test.d.ts +1 -1
  237. package/dist/test/manage/manage-bar.test.js +81 -81
  238. package/dist/test/mediatype-config.test.d.ts +1 -1
  239. package/dist/test/mediatype-config.test.js +16 -16
  240. package/dist/test/mocks/mock-analytics-handler.d.ts +10 -10
  241. package/dist/test/mocks/mock-analytics-handler.js +15 -15
  242. package/dist/test/mocks/mock-search-responses.d.ts +24 -24
  243. package/dist/test/mocks/mock-search-responses.js +860 -860
  244. package/dist/test/mocks/mock-search-service.d.ts +15 -15
  245. package/dist/test/mocks/mock-search-service.js +53 -53
  246. package/dist/test/restoration-state-handler.test.d.ts +1 -1
  247. package/dist/test/restoration-state-handler.test.js +270 -270
  248. package/dist/test/review-block.test.d.ts +1 -1
  249. package/dist/test/review-block.test.js +44 -44
  250. package/dist/test/sort-filter-bar/alpha-bar-tooltip.test.d.ts +1 -1
  251. package/dist/test/sort-filter-bar/alpha-bar-tooltip.test.js +12 -12
  252. package/dist/test/sort-filter-bar/alpha-bar.test.d.ts +1 -1
  253. package/dist/test/sort-filter-bar/alpha-bar.test.js +73 -73
  254. package/dist/test/sort-filter-bar/sort-filter-bar.test.d.ts +1 -1
  255. package/dist/test/sort-filter-bar/sort-filter-bar.test.js +426 -426
  256. package/dist/test/text-overlay.test.d.ts +1 -1
  257. package/dist/test/text-overlay.test.js +48 -48
  258. package/dist/test/text-snippet-block.test.d.ts +1 -1
  259. package/dist/test/text-snippet-block.test.js +57 -57
  260. package/dist/test/tile-stats.test.d.ts +1 -1
  261. package/dist/test/tile-stats.test.js +81 -81
  262. package/dist/test/tiles/grid/account-tile.test.d.ts +1 -1
  263. package/dist/test/tiles/grid/account-tile.test.js +76 -76
  264. package/dist/test/tiles/grid/collection-tile.test.d.ts +1 -1
  265. package/dist/test/tiles/grid/collection-tile.test.js +73 -73
  266. package/dist/test/tiles/grid/item-tile.test.d.ts +1 -1
  267. package/dist/test/tiles/grid/item-tile.test.js +312 -312
  268. package/dist/test/tiles/grid/search-tile.test.d.ts +1 -1
  269. package/dist/test/tiles/grid/search-tile.test.js +51 -51
  270. package/dist/test/tiles/hover/hover-pane-controller.test.d.ts +1 -1
  271. package/dist/test/tiles/hover/hover-pane-controller.test.js +259 -259
  272. package/dist/test/tiles/hover/tile-hover-pane.test.d.ts +1 -1
  273. package/dist/test/tiles/hover/tile-hover-pane.test.js +13 -13
  274. package/dist/test/tiles/list/tile-list-compact.test.d.ts +1 -1
  275. package/dist/test/tiles/list/tile-list-compact.test.js +143 -143
  276. package/dist/test/tiles/list/tile-list.test.d.ts +1 -1
  277. package/dist/test/tiles/list/tile-list.test.js +297 -297
  278. package/dist/test/tiles/tile-dispatcher.test.d.ts +1 -1
  279. package/dist/test/tiles/tile-dispatcher.test.js +100 -100
  280. package/dist/test/tiles/tile-display-value-provider.test.d.ts +1 -1
  281. package/dist/test/tiles/tile-display-value-provider.test.js +141 -141
  282. package/dist/test/utils/array-equals.test.d.ts +1 -1
  283. package/dist/test/utils/array-equals.test.js +26 -26
  284. package/dist/test/utils/format-count.test.d.ts +1 -1
  285. package/dist/test/utils/format-count.test.js +23 -23
  286. package/dist/test/utils/format-date.test.d.ts +1 -1
  287. package/dist/test/utils/format-date.test.js +17 -17
  288. package/dist/test/utils/format-unit-size.test.d.ts +1 -1
  289. package/dist/test/utils/format-unit-size.test.js +17 -17
  290. package/dist/test/utils/local-date-from-utc.test.d.ts +1 -1
  291. package/dist/test/utils/local-date-from-utc.test.js +26 -26
  292. package/local.archive.org.cert +86 -86
  293. package/local.archive.org.key +27 -27
  294. package/package.json +1 -1
  295. package/renovate.json +6 -6
  296. package/src/collection-browser.ts +2 -3
  297. package/src/collection-facets/more-facets-content.ts +21 -13
  298. package/src/collection-facets.ts +7 -5
  299. package/src/data-source/collection-browser-data-source.ts +1 -1
  300. package/src/sort-filter-bar/sort-filter-bar.ts +4 -0
  301. package/test/collection-facets/more-facets-content.test.ts +8 -2
  302. package/test/collection-facets.test.ts +3 -5
  303. package/tsconfig.json +21 -21
  304. package/web-dev-server.config.mjs +30 -30
  305. package/web-test-runner.config.mjs +41 -41
@@ -1,947 +1,947 @@
1
- import { FilterConstraint, FilterMapBuilder, SearchType, } from '@internetarchive/search-service';
2
- import { prefixFilterAggregationKeys, TileModel, SortField, SORT_OPTIONS, } from '../models';
3
- import { FACETLESS_PAGE_ELEMENTS } from './models';
4
- import { sha1 } from '../utils/sha1';
5
- import { log } from '../utils/log';
6
- export class CollectionBrowserDataSource {
7
- // eslint-disable-next-line no-useless-constructor
8
- constructor(
9
- /** The host element to which this controller should attach listeners */
10
- host,
11
- /** Default size of result pages */
12
- pageSize = 50) {
13
- this.host = host;
14
- this.pageSize = pageSize;
15
- /**
16
- * All pages of tile models that have been fetched so far, indexed by their page
17
- * number (with the first being page 1).
18
- */
19
- this.pages = {};
20
- /**
21
- * Tile offset to apply when looking up tiles in the pages, in order to maintain
22
- * page alignment after tiles are removed.
23
- */
24
- this.offset = 0;
25
- /**
26
- * Total number of tile models stored in this data source's pages
27
- */
28
- this.numTileModels = 0;
29
- /**
30
- * A set of fetch IDs that are valid for the current query state
31
- */
32
- this.fetchesInProgress = new Set();
33
- /**
34
- * A record of the query key used for the last search.
35
- * If this changes, we need to load new results.
36
- */
37
- this.previousQueryKey = '';
38
- /**
39
- * Whether the initial page of search results for the current query state
40
- * is presently being fetched.
41
- */
42
- this.searchResultsLoading = false;
43
- /**
44
- * Whether the facets (aggregations) for the current query state are
45
- * presently being fetched.
46
- */
47
- this.facetsLoading = false;
48
- /**
49
- * Whether further query changes should be ignored and not trigger fetches
50
- */
51
- this.suppressFetches = false;
52
- /**
53
- * @inheritdoc
54
- */
55
- this.totalResults = 0;
56
- /**
57
- * @inheritdoc
58
- */
59
- this.endOfDataReached = false;
60
- /**
61
- * @inheritdoc
62
- */
63
- this.queryInitialized = false;
64
- /**
65
- * @inheritdoc
66
- */
67
- this.collectionTitles = new Map();
68
- /**
69
- * @inheritdoc
70
- */
71
- this.parentCollections = [];
72
- /**
73
- * @inheritdoc
74
- */
75
- this.prefixFilterCountMap = {};
76
- /**
77
- * Internal property to store the private value backing the `initialSearchComplete` getter.
78
- */
79
- this._initialSearchCompletePromise = new Promise(res => {
80
- this._initialSearchCompleteResolver = res;
81
- });
82
- /**
83
- * @inheritdoc
84
- */
85
- this.checkAllTiles = () => {
86
- this.map(model => {
87
- const cloned = model.clone();
88
- cloned.checked = true;
89
- return cloned;
90
- });
91
- };
92
- /**
93
- * @inheritdoc
94
- */
95
- this.uncheckAllTiles = () => {
96
- this.map(model => {
97
- const cloned = model.clone();
98
- cloned.checked = false;
99
- return cloned;
100
- });
101
- };
102
- /**
103
- * @inheritdoc
104
- */
105
- this.removeCheckedTiles = () => {
106
- // To make sure our data source remains page-aligned, we will offset our data source by
107
- // the number of removed tiles, so that we can just add the offset when the infinite
108
- // scroller queries for cell contents.
109
- // This only matters while we're still viewing the same set of results. If the user changes
110
- // their query/filters/sort, then the data source is overwritten and the offset cleared.
111
- const { checkedTileModels, uncheckedTileModels } = this;
112
- const numChecked = checkedTileModels.length;
113
- if (numChecked === 0)
114
- return;
115
- this.offset += numChecked;
116
- const newPages = {};
117
- // Which page the remaining tile models start on, post-offset
118
- let offsetPageNumber = Math.floor(this.offset / this.pageSize) + 1;
119
- let indexOnPage = this.offset % this.pageSize;
120
- // Fill the pages up to that point with empty models
121
- for (let page = 1; page <= offsetPageNumber; page += 1) {
122
- const remainingHidden = this.offset - this.pageSize * (page - 1);
123
- const offsetCellsOnPage = Math.min(this.pageSize, remainingHidden);
124
- newPages[page] = Array(offsetCellsOnPage).fill(undefined);
125
- }
126
- // Shift all the remaining tiles into their new positions in the data source
127
- for (const model of uncheckedTileModels) {
128
- if (!newPages[offsetPageNumber])
129
- newPages[offsetPageNumber] = [];
130
- newPages[offsetPageNumber].push(model);
131
- indexOnPage += 1;
132
- if (indexOnPage >= this.pageSize) {
133
- offsetPageNumber += 1;
134
- indexOnPage = 0;
135
- }
136
- }
137
- // Swap in the new pages
138
- this.pages = newPages;
139
- this.numTileModels -= numChecked;
140
- this.host.setTileCount(this.size);
141
- this.requestHostUpdate();
142
- this.refreshVisibleResults();
143
- };
144
- // Just setting some property values
145
- }
146
- /**
147
- * @inheritdoc
148
- */
149
- get initialSearchComplete() {
150
- return this._initialSearchCompletePromise;
151
- }
152
- hostConnected() {
153
- this.setSearchResultsLoading(this.searchResultsLoading);
154
- this.setFacetsLoading(this.facetsLoading);
155
- }
156
- hostUpdate() {
157
- // This reactive controller hook is run whenever the host component (collection-browser) performs an update.
158
- // We check whether the host's state has changed in a way which should trigger a reset & new results fetch.
159
- // Only the currently-installed data source should react to the update
160
- if (!this.activeOnHost)
161
- return;
162
- // Copy loading states onto the host
163
- this.setSearchResultsLoading(this.searchResultsLoading);
164
- this.setFacetsLoading(this.facetsLoading);
165
- // Can't perform searches without a search service
166
- if (!this.host.searchService)
167
- return;
168
- // We should only reset if part of the full query state has changed
169
- const queryKeyChanged = this.pageFetchQueryKey !== this.previousQueryKey;
170
- if (!queryKeyChanged)
171
- return;
172
- // We should only reset if either:
173
- // (a) our state permits a valid search, or
174
- // (b) we have a blank query that we want to show empty results for
175
- const shouldShowEmptyQueryResults = this.host.clearResultsOnEmptyQuery && this.host.baseQuery === '';
176
- if (!(this.canPerformSearch || shouldShowEmptyQueryResults))
177
- return;
178
- if (this.activeOnHost)
179
- this.host.emitQueryStateChanged();
180
- this.handleQueryChange();
181
- }
182
- /**
183
- * Returns whether this data source is the one currently installed on the host component.
184
- */
185
- get activeOnHost() {
186
- return this.host.dataSource === this;
187
- }
188
- /**
189
- * @inheritdoc
190
- */
191
- get size() {
192
- return this.numTileModels;
193
- }
194
- /**
195
- * @inheritdoc
196
- */
197
- reset() {
198
- log('Resetting CB data source');
199
- this.pages = {};
200
- this.aggregations = {};
201
- this.yearHistogramAggregation = undefined;
202
- this.pageElements = undefined;
203
- this.parentCollections = [];
204
- this.queryErrorMessage = undefined;
205
- this.offset = 0;
206
- this.numTileModels = 0;
207
- this.endOfDataReached = false;
208
- this.queryInitialized = false;
209
- // Invalidate any fetches in progress
210
- this.fetchesInProgress.clear();
211
- this.setTotalResultCount(0);
212
- this.requestHostUpdate();
213
- }
214
- /**
215
- * @inheritdoc
216
- */
217
- addPage(pageNum, pageTiles) {
218
- this.pages[pageNum] = pageTiles;
219
- this.numTileModels += pageTiles.length;
220
- this.requestHostUpdate();
221
- }
222
- /**
223
- * @inheritdoc
224
- */
225
- addMultiplePages(firstPageNum, tiles) {
226
- const numPages = Math.ceil(tiles.length / this.pageSize);
227
- for (let i = 0; i < numPages; i += 1) {
228
- const pageStartIndex = this.pageSize * i;
229
- this.addPage(firstPageNum + i, tiles.slice(pageStartIndex, pageStartIndex + this.pageSize));
230
- }
231
- const visiblePages = this.host.currentVisiblePageNumbers;
232
- const needsReload = visiblePages.some(page => page >= firstPageNum && page <= firstPageNum + numPages);
233
- if (needsReload) {
234
- this.refreshVisibleResults();
235
- }
236
- }
237
- /**
238
- * @inheritdoc
239
- */
240
- getPage(pageNum) {
241
- return this.pages[pageNum];
242
- }
243
- /**
244
- * @inheritdoc
245
- */
246
- getAllPages() {
247
- return this.pages;
248
- }
249
- /**
250
- * @inheritdoc
251
- */
252
- hasPage(pageNum) {
253
- return !!this.pages[pageNum];
254
- }
255
- /**
256
- * @inheritdoc
257
- */
258
- getTileModelAt(index) {
259
- var _a, _b;
260
- const offsetIndex = index + this.offset;
261
- const expectedPageNum = Math.floor(offsetIndex / this.pageSize) + 1;
262
- const expectedIndexOnPage = offsetIndex % this.pageSize;
263
- let page = 1;
264
- let tilesSeen = 0;
265
- while (tilesSeen <= offsetIndex) {
266
- if (!this.pages[page]) {
267
- // If we encounter a missing page, either we're past all the results or the page data is sparse.
268
- // So just return the tile at the expected position if it exists.
269
- return (_a = this.pages[expectedPageNum]) === null || _a === void 0 ? void 0 : _a[expectedIndexOnPage];
270
- }
271
- if (tilesSeen + this.pages[page].length > offsetIndex) {
272
- return this.pages[page][offsetIndex - tilesSeen];
273
- }
274
- tilesSeen += this.pages[page].length;
275
- page += 1;
276
- }
277
- return (_b = this.pages[expectedPageNum]) === null || _b === void 0 ? void 0 : _b[expectedIndexOnPage];
278
- }
279
- /**
280
- * @inheritdoc
281
- */
282
- indexOf(tile) {
283
- return Object.values(this.pages).flat().indexOf(tile) - this.offset;
284
- }
285
- /**
286
- * @inheritdoc
287
- */
288
- getPageSize() {
289
- return this.pageSize;
290
- }
291
- /**
292
- * @inheritdoc
293
- */
294
- setPageSize(pageSize) {
295
- this.reset();
296
- this.pageSize = pageSize;
297
- }
298
- /**
299
- * @inheritdoc
300
- */
301
- setTotalResultCount(count) {
302
- this.totalResults = count;
303
- if (this.activeOnHost) {
304
- this.host.setTotalResultCount(count);
305
- }
306
- }
307
- /**
308
- * @inheritdoc
309
- */
310
- setFetchesSuppressed(suppressed) {
311
- this.suppressFetches = suppressed;
312
- }
313
- /**
314
- * @inheritdoc
315
- */
316
- async handleQueryChange() {
317
- // Don't react to the change if fetches are suppressed for this data source
318
- if (this.suppressFetches)
319
- return;
320
- this.reset();
321
- // Reset the `initialSearchComplete` promise with a new value for the imminent search
322
- this._initialSearchCompletePromise = new Promise(res => {
323
- this._initialSearchCompleteResolver = res;
324
- });
325
- const shouldFetchFacets = !this.host.suppressFacets &&
326
- !FACETLESS_PAGE_ELEMENTS.includes(this.host.profileElement);
327
- // Fire the initial page & facet requests
328
- this.queryInitialized = true;
329
- await Promise.all([
330
- this.doInitialPageFetch(),
331
- shouldFetchFacets ? this.fetchFacets() : null,
332
- ]);
333
- // Resolve the `initialSearchComplete` promise for this search
334
- this._initialSearchCompleteResolver(true);
335
- }
336
- /**
337
- * @inheritdoc
338
- */
339
- map(callback) {
340
- this.pages = Object.fromEntries(Object.entries(this.pages).map(([page, tileModels]) => [
341
- page,
342
- tileModels.map((model, index, array) => model ? callback(model, index, array) : model),
343
- ]));
344
- this.requestHostUpdate();
345
- this.refreshVisibleResults();
346
- }
347
- /**
348
- * @inheritdoc
349
- */
350
- get checkedTileModels() {
351
- return this.getFilteredTileModels(model => model.checked);
352
- }
353
- /**
354
- * @inheritdoc
355
- */
356
- get uncheckedTileModels() {
357
- return this.getFilteredTileModels(model => !model.checked);
358
- }
359
- /**
360
- * Returns a flattened, filtered array of all the tile models in the data source
361
- * for which the given predicate returns a truthy value.
362
- *
363
- * @param predicate A callback function to apply on each tile model, as with Array.filter
364
- * @returns A filtered array of tile models satisfying the predicate
365
- */
366
- getFilteredTileModels(predicate) {
367
- return Object.values(this.pages)
368
- .flat()
369
- .filter((model, index, array) => model ? predicate(model, index, array) : false);
370
- }
371
- /**
372
- * @inheritdoc
373
- */
374
- get canPerformSearch() {
375
- var _a;
376
- if (!this.host.searchService)
377
- return false;
378
- const trimmedQuery = (_a = this.host.baseQuery) === null || _a === void 0 ? void 0 : _a.trim();
379
- const hasNonEmptyQuery = !!trimmedQuery;
380
- const isCollectionSearch = !!this.host.withinCollection;
381
- const isProfileSearch = !!this.host.withinProfile;
382
- const hasProfileElement = !!this.host.profileElement;
383
- const isMetadataSearch = this.host.searchType === SearchType.METADATA;
384
- // Metadata searches within a collection/profile are allowed to have no query.
385
- // Otherwise, a non-empty query must be set.
386
- return (hasNonEmptyQuery ||
387
- (isCollectionSearch && isMetadataSearch) ||
388
- (isProfileSearch && hasProfileElement && isMetadataSearch));
389
- }
390
- /**
391
- * Sets the state for whether the initial set of search results for the
392
- * current query is loading
393
- */
394
- setSearchResultsLoading(loading) {
395
- this.searchResultsLoading = loading;
396
- if (this.activeOnHost) {
397
- this.host.setSearchResultsLoading(loading);
398
- }
399
- }
400
- /**
401
- * Sets the state for whether the facets for a query is loading
402
- */
403
- setFacetsLoading(loading) {
404
- this.facetsLoading = loading;
405
- if (this.activeOnHost) {
406
- this.host.setFacetsLoading(loading);
407
- }
408
- }
409
- /**
410
- * Requests that the host perform an update, provided this data
411
- * source is actively installed on it.
412
- */
413
- requestHostUpdate() {
414
- if (this.activeOnHost) {
415
- this.host.requestUpdate();
416
- }
417
- }
418
- /**
419
- * Requests that the host refresh its visible tiles, provided this
420
- * data source is actively installed on it.
421
- */
422
- refreshVisibleResults() {
423
- if (this.activeOnHost) {
424
- this.host.refreshVisibleResults();
425
- }
426
- }
427
- /**
428
- * The query key is a string that uniquely identifies the current search.
429
- * It consists of:
430
- * - The current base query
431
- * - The current collection/profile target & page element
432
- * - The current search type
433
- * - Any currently-applied facets
434
- * - Any currently-applied date range
435
- * - Any currently-applied prefix filters
436
- * - The current sort options
437
- *
438
- * This lets us internally keep track of queries so we don't persist data that's
439
- * no longer relevant. Not meant to be human-readable.
440
- */
441
- get pageFetchQueryKey() {
442
- var _a, _b, _c;
443
- const profileKey = `pf;${this.host.withinProfile}--pe;${this.host.profileElement}`;
444
- const pageTarget = (_a = this.host.withinCollection) !== null && _a !== void 0 ? _a : profileKey;
445
- const sortField = (_b = this.host.selectedSort) !== null && _b !== void 0 ? _b : 'none';
446
- const sortDirection = (_c = this.host.sortDirection) !== null && _c !== void 0 ? _c : 'none';
447
- return `fq:${this.fullQuery}-pt:${pageTarget}-st:${this.host.searchType}-sf:${sortField}-sd:${sortDirection}`;
448
- }
449
- /**
450
- * Similar to `pageFetchQueryKey` above, but excludes sort fields since they
451
- * are not relevant in determining aggregation queries.
452
- */
453
- get facetFetchQueryKey() {
454
- var _a;
455
- const profileKey = `pf;${this.host.withinProfile}--pe;${this.host.profileElement}`;
456
- const pageTarget = (_a = this.host.withinCollection) !== null && _a !== void 0 ? _a : profileKey;
457
- return `fq:${this.fullQuery}-pt:${pageTarget}-st:${this.host.searchType}`;
458
- }
459
- /**
460
- * Constructs a search service FilterMap object from the combination of
461
- * all the currently-applied filters. This includes any facets, letter
462
- * filters, and date range.
463
- */
464
- get filterMap() {
465
- const builder = new FilterMapBuilder();
466
- // Add the date range, if applicable
467
- if (this.host.minSelectedDate) {
468
- builder.addFilter('year', this.host.minSelectedDate, FilterConstraint.GREATER_OR_EQUAL);
469
- }
470
- if (this.host.maxSelectedDate) {
471
- builder.addFilter('year', this.host.maxSelectedDate, FilterConstraint.LESS_OR_EQUAL);
472
- }
473
- // Add any selected facets
474
- if (this.host.selectedFacets) {
475
- for (const [facetName, facetValues] of Object.entries(this.host.selectedFacets)) {
476
- const { name, values } = this.prepareFacetForFetch(facetName, facetValues);
477
- for (const [value, bucket] of Object.entries(values)) {
478
- let constraint;
479
- if (bucket.state === 'selected') {
480
- constraint = FilterConstraint.INCLUDE;
481
- }
482
- else if (bucket.state === 'hidden') {
483
- constraint = FilterConstraint.EXCLUDE;
484
- }
485
- if (constraint) {
486
- builder.addFilter(name, value, constraint);
487
- }
488
- }
489
- }
490
- }
491
- // Add any letter filters
492
- if (this.host.selectedTitleFilter) {
493
- builder.addFilter('firstTitle', this.host.selectedTitleFilter, FilterConstraint.INCLUDE);
494
- }
495
- if (this.host.selectedCreatorFilter) {
496
- builder.addFilter('firstCreator', this.host.selectedCreatorFilter, FilterConstraint.INCLUDE);
497
- }
498
- const filterMap = builder.build();
499
- return filterMap;
500
- }
501
- /**
502
- * Produces a compact unique ID for a search request that can help with debugging
503
- * on the backend by making related requests easier to trace through different services.
504
- * (e.g., tying the hits/aggregations requests for the same page back to a single hash).
505
- *
506
- * @param params The search service parameters for the request
507
- * @param kind The kind of request (hits-only, aggregations-only, or both)
508
- * @returns A Promise resolving to the uid to apply to the request
509
- */
510
- async requestUID(params, kind) {
511
- var _a;
512
- const paramsToHash = JSON.stringify({
513
- pageType: params.pageType,
514
- pageTarget: params.pageTarget,
515
- query: params.query,
516
- fields: params.fields,
517
- filters: params.filters,
518
- sort: params.sort,
519
- searchType: this.host.searchType,
520
- });
521
- const fullQueryHash = (await sha1(paramsToHash)).slice(0, 20); // First 80 bits of SHA-1 are plenty for this
522
- const sessionId = (await this.host.getSessionId()).slice(0, 20); // Likewise
523
- const page = (_a = params.page) !== null && _a !== void 0 ? _a : 0;
524
- const kindPrefix = kind.charAt(0); // f = full, h = hits, a = aggregations
525
- const currentTime = Date.now();
526
- return `R:${fullQueryHash}-S:${sessionId}-P:${page}-K:${kindPrefix}-T:${currentTime}`;
527
- }
528
- /**
529
- * @inheritdoc
530
- */
531
- get pageSpecifierParams() {
532
- if (this.host.withinCollection) {
533
- return {
534
- pageType: 'collection_details',
535
- pageTarget: this.host.withinCollection,
536
- };
537
- }
538
- if (this.host.withinProfile) {
539
- return {
540
- pageType: 'account_details',
541
- pageTarget: this.host.withinProfile,
542
- pageElements: this.host.profileElement
543
- ? [this.host.profileElement]
544
- : [],
545
- };
546
- }
547
- return null;
548
- }
549
- /**
550
- * The full query, including year facets and date range clauses
551
- */
552
- get fullQuery() {
553
- var _a, _b;
554
- let fullQuery = (_b = (_a = this.host.baseQuery) === null || _a === void 0 ? void 0 : _a.trim()) !== null && _b !== void 0 ? _b : '';
555
- const { facetQuery, dateRangeQueryClause, sortFilterQueries } = this;
556
- if (facetQuery) {
557
- fullQuery += ` AND ${facetQuery}`;
558
- }
559
- if (dateRangeQueryClause) {
560
- fullQuery += ` AND ${dateRangeQueryClause}`;
561
- }
562
- if (sortFilterQueries) {
563
- fullQuery += ` AND ${sortFilterQueries}`;
564
- }
565
- return fullQuery.trim();
566
- }
567
- /**
568
- * Generates a query string representing the current set of applied facets
569
- *
570
- * Example: `mediatype:("collection" OR "audio" OR -"etree") AND year:("2000" OR "2001")`
571
- */
572
- get facetQuery() {
573
- var _a;
574
- if (!this.host.selectedFacets)
575
- return undefined;
576
- const facetClauses = [];
577
- for (const [facetName, facetValues] of Object.entries(this.host.selectedFacets)) {
578
- facetClauses.push(this.buildFacetClause(facetName, facetValues));
579
- }
580
- return (_a = this.joinFacetClauses(facetClauses)) === null || _a === void 0 ? void 0 : _a.trim();
581
- }
582
- get dateRangeQueryClause() {
583
- if (!this.host.minSelectedDate || !this.host.maxSelectedDate) {
584
- return undefined;
585
- }
586
- return `year:[${this.host.minSelectedDate} TO ${this.host.maxSelectedDate}]`;
587
- }
588
- get sortFilterQueries() {
589
- const queries = [this.titleQuery, this.creatorQuery];
590
- return queries.filter(q => q).join(' AND ');
591
- }
592
- /**
593
- * Returns a query clause identifying the currently selected title filter,
594
- * e.g., `firstTitle:X`.
595
- */
596
- get titleQuery() {
597
- return this.host.selectedTitleFilter
598
- ? `firstTitle:${this.host.selectedTitleFilter}`
599
- : undefined;
600
- }
601
- /**
602
- * Returns a query clause identifying the currently selected creator filter,
603
- * e.g., `firstCreator:X`.
604
- */
605
- get creatorQuery() {
606
- return this.host.selectedCreatorFilter
607
- ? `firstCreator:${this.host.selectedCreatorFilter}`
608
- : undefined;
609
- }
610
- /**
611
- * Builds an OR-joined facet clause for the given facet name and values.
612
- *
613
- * E.g., for name `subject` and values
614
- * `{ foo: { state: 'selected' }, bar: { state: 'hidden' } }`
615
- * this will produce the clause
616
- * `subject:("foo" OR -"bar")`.
617
- *
618
- * @param facetName The facet type (e.g., 'collection')
619
- * @param facetValues The facet buckets, mapped by their keys
620
- */
621
- buildFacetClause(facetName, facetValues) {
622
- const { name: facetQueryName, values } = this.prepareFacetForFetch(facetName, facetValues);
623
- const facetEntries = Object.entries(values);
624
- if (facetEntries.length === 0)
625
- return '';
626
- const facetValuesArray = [];
627
- for (const [key, facetData] of facetEntries) {
628
- const plusMinusPrefix = facetData.state === 'hidden' ? '-' : '';
629
- facetValuesArray.push(`${plusMinusPrefix}"${key}"`);
630
- }
631
- const valueQuery = facetValuesArray.join(` OR `);
632
- return `${facetQueryName}:(${valueQuery})`;
633
- }
634
- /**
635
- * Handles some special pre-request normalization steps for certain facet types
636
- * that require them.
637
- *
638
- * @param facetName The name of the facet type (e.g., 'language')
639
- * @param facetValues An array of values for that facet type
640
- */
641
- prepareFacetForFetch(facetName, facetValues) {
642
- // eslint-disable-next-line prefer-const
643
- let [normalizedName, normalizedValues] = [facetName, facetValues];
644
- // The full "search engine" name of the lending field is "lending___status"
645
- if (facetName === 'lending') {
646
- normalizedName = 'lending___status';
647
- }
648
- return {
649
- name: normalizedName,
650
- values: normalizedValues,
651
- };
652
- }
653
- /**
654
- * Takes an array of facet clauses, and combines them into a
655
- * full AND-joined facet query string. Empty clauses are ignored.
656
- */
657
- joinFacetClauses(facetClauses) {
658
- const nonEmptyFacetClauses = facetClauses.filter(clause => clause.length > 0);
659
- return nonEmptyFacetClauses.length > 0
660
- ? `(${nonEmptyFacetClauses.join(' AND ')})`
661
- : undefined;
662
- }
663
- /**
664
- * Fires a backend request to fetch a set of aggregations (representing UI facets) for
665
- * the current search state.
666
- */
667
- async fetchFacets() {
668
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
669
- const trimmedQuery = (_a = this.host.baseQuery) === null || _a === void 0 ? void 0 : _a.trim();
670
- if (!this.canPerformSearch)
671
- return;
672
- const { facetFetchQueryKey } = this;
673
- if (this.fetchesInProgress.has(facetFetchQueryKey))
674
- return;
675
- this.fetchesInProgress.add(facetFetchQueryKey);
676
- const sortParams = this.host.sortParam ? [this.host.sortParam] : [];
677
- const params = {
678
- ...this.pageSpecifierParams,
679
- query: trimmedQuery || '',
680
- rows: 0,
681
- filters: this.filterMap,
682
- // Fetch a few extra buckets beyond the 6 we show, in case some get suppressed
683
- aggregationsSize: 10,
684
- // Note: we don't need an aggregations param to fetch the default aggregations from the PPS.
685
- // The default aggregations for the search_results page type should be what we need here.
686
- };
687
- params.uid = await this.requestUID({ ...params, sort: sortParams }, 'aggregations');
688
- this.setFacetsLoading(true);
689
- const searchResponse = await ((_b = this.host.searchService) === null || _b === void 0 ? void 0 : _b.search(params, this.host.searchType));
690
- const success = searchResponse === null || searchResponse === void 0 ? void 0 : searchResponse.success;
691
- // This is checking to see if the query has changed since the data was fetched.
692
- // If so, we just want to discard this set of aggregations because they are
693
- // likely no longer valid for the newer query.
694
- const queryChangedSinceFetch = !this.fetchesInProgress.has(facetFetchQueryKey);
695
- this.fetchesInProgress.delete(facetFetchQueryKey);
696
- if (queryChangedSinceFetch)
697
- return;
698
- if (!success) {
699
- const errorMsg = (_c = searchResponse === null || searchResponse === void 0 ? void 0 : searchResponse.error) === null || _c === void 0 ? void 0 : _c.message;
700
- 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;
701
- if (!errorMsg && !detailMsg) {
702
- // @ts-ignore: Property 'Sentry' does not exist on type 'Window & typeof globalThis'
703
- (_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');
704
- }
705
- this.setFacetsLoading(false);
706
- return;
707
- }
708
- const { aggregations, collectionTitles } = success.response;
709
- this.aggregations = aggregations;
710
- if (collectionTitles) {
711
- for (const [id, title] of Object.entries(collectionTitles)) {
712
- this.collectionTitles.set(id, title);
713
- }
714
- }
715
- this.yearHistogramAggregation =
716
- (_j = (_h = success === null || success === void 0 ? void 0 : success.response) === null || _h === void 0 ? void 0 : _h.aggregations) === null || _j === void 0 ? void 0 : _j.year_histogram;
717
- this.setFacetsLoading(false);
718
- this.requestHostUpdate();
719
- }
720
- /**
721
- * Performs the initial page fetch(es) for the current search state.
722
- */
723
- async doInitialPageFetch() {
724
- this.setSearchResultsLoading(true);
725
- // Try to batch 2 initial page requests when possible
726
- await this.fetchPage(this.host.initialPageNumber, 2);
727
- }
728
- /**
729
- * Fetches one or more pages of results and updates the data source.
730
- *
731
- * @param pageNumber The page number to fetch
732
- * @param numInitialPages If this is an initial page fetch (`pageNumber = 1`),
733
- * specifies how many pages to batch together in one request. Ignored
734
- * if `pageNumber != 1`, defaulting to a single page.
735
- */
736
- async fetchPage(pageNumber, numInitialPages = 1) {
737
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
738
- const trimmedQuery = (_a = this.host.baseQuery) === null || _a === void 0 ? void 0 : _a.trim();
739
- if (!this.canPerformSearch)
740
- return;
741
- // if we already have data, don't fetch again
742
- if (this.hasPage(pageNumber))
743
- return;
744
- if (this.endOfDataReached)
745
- return;
746
- // Batch multiple initial page requests together if needed (e.g., can request
747
- // pages 1 and 2 together in a single request).
748
- let numPages = pageNumber === 1 ? numInitialPages : 1;
749
- const numRows = this.pageSize * numPages;
750
- // if a fetch is already in progress for this query and page, don't fetch again
751
- const { pageFetchQueryKey } = this;
752
- const currentPageKey = `${pageFetchQueryKey}-p:${pageNumber}`;
753
- if (this.fetchesInProgress.has(currentPageKey))
754
- return;
755
- for (let i = 0; i < numPages; i += 1) {
756
- this.fetchesInProgress.add(`${pageFetchQueryKey}-p:${pageNumber + i}`);
757
- }
758
- this.previousQueryKey = pageFetchQueryKey;
759
- let sortParams = this.host.sortParam ? [this.host.sortParam] : [];
760
- // TODO eventually the PPS should handle these defaults natively
761
- const isDefaultProfileSort = this.host.withinProfile && this.host.selectedSort === SortField.default;
762
- if (isDefaultProfileSort && this.host.defaultSortParam) {
763
- const sortOption = SORT_OPTIONS[this.host.defaultSortParam.field];
764
- if (sortOption.searchServiceKey) {
765
- sortParams = [
766
- {
767
- field: sortOption.searchServiceKey,
768
- direction: 'desc',
769
- },
770
- ];
771
- }
772
- }
773
- const params = {
774
- ...this.pageSpecifierParams,
775
- query: trimmedQuery || '',
776
- page: pageNumber,
777
- rows: numRows,
778
- sort: sortParams,
779
- filters: this.filterMap,
780
- aggregations: { omit: true },
781
- };
782
- params.uid = await this.requestUID(params, 'hits');
783
- log('=== FIRING PAGE REQUEST ===', params);
784
- const searchResponse = await ((_b = this.host.searchService) === null || _b === void 0 ? void 0 : _b.search(params, this.host.searchType));
785
- log('=== RECEIVED PAGE RESPONSE IN CB ===', searchResponse);
786
- const success = searchResponse === null || searchResponse === void 0 ? void 0 : searchResponse.success;
787
- // This is checking to see if the fetch has been invalidated since it was fired off.
788
- // If so, we just want to discard the response since it is for an obsolete query state.
789
- if (!this.fetchesInProgress.has(currentPageKey))
790
- return;
791
- for (let i = 0; i < numPages; i += 1) {
792
- this.fetchesInProgress.delete(`${pageFetchQueryKey}-p:${pageNumber + i}`);
793
- }
794
- if (!success) {
795
- const errorMsg = (_c = searchResponse === null || searchResponse === void 0 ? void 0 : searchResponse.error) === null || _c === void 0 ? void 0 : _c.message;
796
- 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;
797
- this.queryErrorMessage = `${errorMsg !== null && errorMsg !== void 0 ? errorMsg : ''}${detailMsg ? `; ${detailMsg}` : ''}`;
798
- if (!this.queryErrorMessage) {
799
- this.queryErrorMessage = 'Missing or malformed response from backend';
800
- // @ts-ignore: Property 'Sentry' does not exist on type 'Window & typeof globalThis'
801
- (_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, this.queryErrorMessage, 'error');
802
- }
803
- this.setSearchResultsLoading(false);
804
- this.requestHostUpdate();
805
- return;
806
- }
807
- this.setTotalResultCount(success.response.totalResults - this.offset);
808
- if (this.activeOnHost && this.totalResults === 0) {
809
- // display event to offshoot when result count is zero.
810
- this.host.emitEmptyResults();
811
- }
812
- this.sessionContext = success.sessionContext;
813
- if (this.host.withinCollection) {
814
- this.collectionExtraInfo = success.response.collectionExtraInfo;
815
- // For collections, we want the UI to respect the default sort option
816
- // which can be specified in metadata, or otherwise assumed to be week:desc
817
- if (this.activeOnHost) {
818
- this.host.applyDefaultCollectionSort(this.collectionExtraInfo);
819
- }
820
- if (this.collectionExtraInfo) {
821
- this.parentCollections = [].concat((_j = (_h = this.collectionExtraInfo.public_metadata) === null || _h === void 0 ? void 0 : _h.collection) !== null && _j !== void 0 ? _j : []);
822
- }
823
- }
824
- else if (this.host.withinProfile) {
825
- this.accountExtraInfo = success.response.accountExtraInfo;
826
- this.pageElements = success.response.pageElements;
827
- }
828
- const { results, collectionTitles } = success.response;
829
- if (results && results.length > 0) {
830
- // Load any collection titles present on the response into the cache,
831
- // or queue up preload fetches for them if none were present.
832
- if (collectionTitles) {
833
- for (const [id, title] of Object.entries(collectionTitles)) {
834
- this.collectionTitles.set(id, title);
835
- }
836
- }
837
- // Update the data source for each returned page.
838
- // For loans and web archives, we must account for receiving more pages than we asked for.
839
- if (this.host.profileElement === 'lending' ||
840
- this.host.profileElement === 'web_archives') {
841
- numPages = Math.ceil(results.length / this.pageSize);
842
- this.endOfDataReached = true;
843
- if (this.activeOnHost)
844
- this.host.setTileCount(this.totalResults);
845
- }
846
- for (let i = 0; i < numPages; i += 1) {
847
- const pageStartIndex = this.pageSize * i;
848
- this.addFetchedResultsToDataSource(pageNumber + i, results.slice(pageStartIndex, pageStartIndex + this.pageSize));
849
- }
850
- }
851
- // When we reach the end of the data, we can set the infinite scroller's
852
- // item count to the real total number of results (rather than the
853
- // temporary estimates based on pages rendered so far).
854
- if (results.length === 0) {
855
- this.endOfDataReached = true;
856
- if (this.activeOnHost)
857
- this.host.setTileCount(this.size);
858
- }
859
- this.setSearchResultsLoading(false);
860
- this.requestHostUpdate();
861
- }
862
- /**
863
- * Update the datasource from the fetch response
864
- *
865
- * @param pageNumber
866
- * @param results
867
- */
868
- addFetchedResultsToDataSource(pageNumber, results) {
869
- const tiles = [];
870
- results === null || results === void 0 ? void 0 : results.forEach(result => {
871
- if (!result.identifier)
872
- return;
873
- tiles.push(new TileModel(result));
874
- });
875
- this.addPage(pageNumber, tiles);
876
- const visiblePages = this.host.currentVisiblePageNumbers;
877
- const needsReload = visiblePages.includes(pageNumber);
878
- if (needsReload) {
879
- this.refreshVisibleResults();
880
- }
881
- }
882
- /**
883
- * Fetches the aggregation buckets for the given prefix filter type.
884
- */
885
- async fetchPrefixFilterBuckets(filterType) {
886
- var _a, _b, _c, _d, _e, _f, _g;
887
- const trimmedQuery = (_a = this.host.baseQuery) === null || _a === void 0 ? void 0 : _a.trim();
888
- if (!this.canPerformSearch)
889
- return [];
890
- const filterAggregationKey = prefixFilterAggregationKeys[filterType];
891
- const sortParams = this.host.sortParam ? [this.host.sortParam] : [];
892
- const params = {
893
- ...this.pageSpecifierParams,
894
- query: trimmedQuery || '',
895
- rows: 0,
896
- filters: this.filterMap,
897
- // Only fetch the firstTitle or firstCreator aggregation
898
- aggregations: { simpleParams: [filterAggregationKey] },
899
- // Fetch all 26 letter buckets
900
- aggregationsSize: 26,
901
- };
902
- params.uid = await this.requestUID({ ...params, sort: sortParams }, 'aggregations');
903
- const searchResponse = await ((_b = this.host.searchService) === null || _b === void 0 ? void 0 : _b.search(params, this.host.searchType));
904
- 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 : []);
905
- }
906
- /**
907
- * Fetches and caches the prefix filter counts for the given filter type.
908
- */
909
- async updatePrefixFilterCounts(filterType) {
910
- const { facetFetchQueryKey } = this;
911
- const buckets = await this.fetchPrefixFilterBuckets(filterType);
912
- // Don't update the filter counts for an outdated query (if it has been changed
913
- // since we sent the request)
914
- const queryChangedSinceFetch = facetFetchQueryKey !== this.facetFetchQueryKey;
915
- if (queryChangedSinceFetch)
916
- return;
917
- // Unpack the aggregation buckets into a simple map like { 'A': 50, 'B': 25, ... }
918
- this.prefixFilterCountMap = { ...this.prefixFilterCountMap }; // Clone the object to trigger an update
919
- this.prefixFilterCountMap[filterType] = buckets.reduce((acc, bucket) => {
920
- acc[bucket.key.toUpperCase()] = bucket.doc_count;
921
- return acc;
922
- }, {});
923
- this.requestHostUpdate();
924
- }
925
- /**
926
- * @inheritdoc
927
- */
928
- async updatePrefixFiltersForCurrentSort() {
929
- if (['title', 'creator'].includes(this.host.selectedSort)) {
930
- const filterType = this.host.selectedSort;
931
- if (!this.prefixFilterCountMap[filterType]) {
932
- this.updatePrefixFilterCounts(filterType);
933
- }
934
- }
935
- }
936
- /**
937
- * @inheritdoc
938
- */
939
- refreshLetterCounts() {
940
- if (Object.keys(this.prefixFilterCountMap).length > 0) {
941
- this.prefixFilterCountMap = {};
942
- }
943
- this.updatePrefixFiltersForCurrentSort();
944
- this.requestHostUpdate();
945
- }
946
- }
1
+ import { FilterConstraint, FilterMapBuilder, SearchType, } from '@internetarchive/search-service';
2
+ import { prefixFilterAggregationKeys, TileModel, SortField, SORT_OPTIONS, } from '../models';
3
+ import { FACETLESS_PAGE_ELEMENTS } from './models';
4
+ import { sha1 } from '../utils/sha1';
5
+ import { log } from '../utils/log';
6
+ export class CollectionBrowserDataSource {
7
+ // eslint-disable-next-line no-useless-constructor
8
+ constructor(
9
+ /** The host element to which this controller should attach listeners */
10
+ host,
11
+ /** Default size of result pages */
12
+ pageSize = 50) {
13
+ this.host = host;
14
+ this.pageSize = pageSize;
15
+ /**
16
+ * All pages of tile models that have been fetched so far, indexed by their page
17
+ * number (with the first being page 1).
18
+ */
19
+ this.pages = {};
20
+ /**
21
+ * Tile offset to apply when looking up tiles in the pages, in order to maintain
22
+ * page alignment after tiles are removed.
23
+ */
24
+ this.offset = 0;
25
+ /**
26
+ * Total number of tile models stored in this data source's pages
27
+ */
28
+ this.numTileModels = 0;
29
+ /**
30
+ * A set of fetch IDs that are valid for the current query state
31
+ */
32
+ this.fetchesInProgress = new Set();
33
+ /**
34
+ * A record of the query key used for the last search.
35
+ * If this changes, we need to load new results.
36
+ */
37
+ this.previousQueryKey = '';
38
+ /**
39
+ * Whether the initial page of search results for the current query state
40
+ * is presently being fetched.
41
+ */
42
+ this.searchResultsLoading = false;
43
+ /**
44
+ * Whether the facets (aggregations) for the current query state are
45
+ * presently being fetched.
46
+ */
47
+ this.facetsLoading = false;
48
+ /**
49
+ * Whether further query changes should be ignored and not trigger fetches
50
+ */
51
+ this.suppressFetches = false;
52
+ /**
53
+ * @inheritdoc
54
+ */
55
+ this.totalResults = 0;
56
+ /**
57
+ * @inheritdoc
58
+ */
59
+ this.endOfDataReached = false;
60
+ /**
61
+ * @inheritdoc
62
+ */
63
+ this.queryInitialized = false;
64
+ /**
65
+ * @inheritdoc
66
+ */
67
+ this.collectionTitles = new Map();
68
+ /**
69
+ * @inheritdoc
70
+ */
71
+ this.parentCollections = [];
72
+ /**
73
+ * @inheritdoc
74
+ */
75
+ this.prefixFilterCountMap = {};
76
+ /**
77
+ * Internal property to store the private value backing the `initialSearchComplete` getter.
78
+ */
79
+ this._initialSearchCompletePromise = new Promise(res => {
80
+ this._initialSearchCompleteResolver = res;
81
+ });
82
+ /**
83
+ * @inheritdoc
84
+ */
85
+ this.checkAllTiles = () => {
86
+ this.map(model => {
87
+ const cloned = model.clone();
88
+ cloned.checked = true;
89
+ return cloned;
90
+ });
91
+ };
92
+ /**
93
+ * @inheritdoc
94
+ */
95
+ this.uncheckAllTiles = () => {
96
+ this.map(model => {
97
+ const cloned = model.clone();
98
+ cloned.checked = false;
99
+ return cloned;
100
+ });
101
+ };
102
+ /**
103
+ * @inheritdoc
104
+ */
105
+ this.removeCheckedTiles = () => {
106
+ // To make sure our data source remains page-aligned, we will offset our data source by
107
+ // the number of removed tiles, so that we can just add the offset when the infinite
108
+ // scroller queries for cell contents.
109
+ // This only matters while we're still viewing the same set of results. If the user changes
110
+ // their query/filters/sort, then the data source is overwritten and the offset cleared.
111
+ const { checkedTileModels, uncheckedTileModels } = this;
112
+ const numChecked = checkedTileModels.length;
113
+ if (numChecked === 0)
114
+ return;
115
+ this.offset += numChecked;
116
+ const newPages = {};
117
+ // Which page the remaining tile models start on, post-offset
118
+ let offsetPageNumber = Math.floor(this.offset / this.pageSize) + 1;
119
+ let indexOnPage = this.offset % this.pageSize;
120
+ // Fill the pages up to that point with empty models
121
+ for (let page = 1; page <= offsetPageNumber; page += 1) {
122
+ const remainingHidden = this.offset - this.pageSize * (page - 1);
123
+ const offsetCellsOnPage = Math.min(this.pageSize, remainingHidden);
124
+ newPages[page] = Array(offsetCellsOnPage).fill(undefined);
125
+ }
126
+ // Shift all the remaining tiles into their new positions in the data source
127
+ for (const model of uncheckedTileModels) {
128
+ if (!newPages[offsetPageNumber])
129
+ newPages[offsetPageNumber] = [];
130
+ newPages[offsetPageNumber].push(model);
131
+ indexOnPage += 1;
132
+ if (indexOnPage >= this.pageSize) {
133
+ offsetPageNumber += 1;
134
+ indexOnPage = 0;
135
+ }
136
+ }
137
+ // Swap in the new pages
138
+ this.pages = newPages;
139
+ this.numTileModels -= numChecked;
140
+ this.host.setTileCount(this.size);
141
+ this.requestHostUpdate();
142
+ this.refreshVisibleResults();
143
+ };
144
+ // Just setting some property values
145
+ }
146
+ /**
147
+ * @inheritdoc
148
+ */
149
+ get initialSearchComplete() {
150
+ return this._initialSearchCompletePromise;
151
+ }
152
+ hostConnected() {
153
+ this.setSearchResultsLoading(this.searchResultsLoading);
154
+ this.setFacetsLoading(this.facetsLoading);
155
+ }
156
+ hostUpdate() {
157
+ // This reactive controller hook is run whenever the host component (collection-browser) performs an update.
158
+ // We check whether the host's state has changed in a way which should trigger a reset & new results fetch.
159
+ // Only the currently-installed data source should react to the update
160
+ if (!this.activeOnHost)
161
+ return;
162
+ // Copy loading states onto the host
163
+ this.setSearchResultsLoading(this.searchResultsLoading);
164
+ this.setFacetsLoading(this.facetsLoading);
165
+ // Can't perform searches without a search service
166
+ if (!this.host.searchService)
167
+ return;
168
+ // We should only reset if part of the full query state has changed
169
+ const queryKeyChanged = this.pageFetchQueryKey !== this.previousQueryKey;
170
+ if (!queryKeyChanged)
171
+ return;
172
+ // We should only reset if either:
173
+ // (a) our state permits a valid search, or
174
+ // (b) we have a blank query that we want to show empty results for
175
+ const shouldShowEmptyQueryResults = this.host.clearResultsOnEmptyQuery && this.host.baseQuery === '';
176
+ if (!(this.canPerformSearch || shouldShowEmptyQueryResults))
177
+ return;
178
+ if (this.activeOnHost)
179
+ this.host.emitQueryStateChanged();
180
+ this.handleQueryChange();
181
+ }
182
+ /**
183
+ * Returns whether this data source is the one currently installed on the host component.
184
+ */
185
+ get activeOnHost() {
186
+ return this.host.dataSource === this;
187
+ }
188
+ /**
189
+ * @inheritdoc
190
+ */
191
+ get size() {
192
+ return this.numTileModels;
193
+ }
194
+ /**
195
+ * @inheritdoc
196
+ */
197
+ reset() {
198
+ log('Resetting CB data source');
199
+ this.pages = {};
200
+ this.aggregations = {};
201
+ this.yearHistogramAggregation = undefined;
202
+ this.pageElements = undefined;
203
+ this.parentCollections = [];
204
+ this.queryErrorMessage = undefined;
205
+ this.offset = 0;
206
+ this.numTileModels = 0;
207
+ this.endOfDataReached = false;
208
+ this.queryInitialized = false;
209
+ // Invalidate any fetches in progress
210
+ this.fetchesInProgress.clear();
211
+ this.setTotalResultCount(0);
212
+ this.requestHostUpdate();
213
+ }
214
+ /**
215
+ * @inheritdoc
216
+ */
217
+ addPage(pageNum, pageTiles) {
218
+ this.pages[pageNum] = pageTiles;
219
+ this.numTileModels += pageTiles.length;
220
+ this.requestHostUpdate();
221
+ }
222
+ /**
223
+ * @inheritdoc
224
+ */
225
+ addMultiplePages(firstPageNum, tiles) {
226
+ const numPages = Math.ceil(tiles.length / this.pageSize);
227
+ for (let i = 0; i < numPages; i += 1) {
228
+ const pageStartIndex = this.pageSize * i;
229
+ this.addPage(firstPageNum + i, tiles.slice(pageStartIndex, pageStartIndex + this.pageSize));
230
+ }
231
+ const visiblePages = this.host.currentVisiblePageNumbers;
232
+ const needsReload = visiblePages.some(page => page >= firstPageNum && page <= firstPageNum + numPages);
233
+ if (needsReload) {
234
+ this.refreshVisibleResults();
235
+ }
236
+ }
237
+ /**
238
+ * @inheritdoc
239
+ */
240
+ getPage(pageNum) {
241
+ return this.pages[pageNum];
242
+ }
243
+ /**
244
+ * @inheritdoc
245
+ */
246
+ getAllPages() {
247
+ return this.pages;
248
+ }
249
+ /**
250
+ * @inheritdoc
251
+ */
252
+ hasPage(pageNum) {
253
+ return !!this.pages[pageNum];
254
+ }
255
+ /**
256
+ * @inheritdoc
257
+ */
258
+ getTileModelAt(index) {
259
+ var _a, _b;
260
+ const offsetIndex = index + this.offset;
261
+ const expectedPageNum = Math.floor(offsetIndex / this.pageSize) + 1;
262
+ const expectedIndexOnPage = offsetIndex % this.pageSize;
263
+ let page = 1;
264
+ let tilesSeen = 0;
265
+ while (tilesSeen <= offsetIndex) {
266
+ if (!this.pages[page]) {
267
+ // If we encounter a missing page, either we're past all the results or the page data is sparse.
268
+ // So just return the tile at the expected position if it exists.
269
+ return (_a = this.pages[expectedPageNum]) === null || _a === void 0 ? void 0 : _a[expectedIndexOnPage];
270
+ }
271
+ if (tilesSeen + this.pages[page].length > offsetIndex) {
272
+ return this.pages[page][offsetIndex - tilesSeen];
273
+ }
274
+ tilesSeen += this.pages[page].length;
275
+ page += 1;
276
+ }
277
+ return (_b = this.pages[expectedPageNum]) === null || _b === void 0 ? void 0 : _b[expectedIndexOnPage];
278
+ }
279
+ /**
280
+ * @inheritdoc
281
+ */
282
+ indexOf(tile) {
283
+ return Object.values(this.pages).flat().indexOf(tile) - this.offset;
284
+ }
285
+ /**
286
+ * @inheritdoc
287
+ */
288
+ getPageSize() {
289
+ return this.pageSize;
290
+ }
291
+ /**
292
+ * @inheritdoc
293
+ */
294
+ setPageSize(pageSize) {
295
+ this.reset();
296
+ this.pageSize = pageSize;
297
+ }
298
+ /**
299
+ * @inheritdoc
300
+ */
301
+ setTotalResultCount(count) {
302
+ this.totalResults = count;
303
+ if (this.activeOnHost) {
304
+ this.host.setTotalResultCount(count);
305
+ }
306
+ }
307
+ /**
308
+ * @inheritdoc
309
+ */
310
+ setFetchesSuppressed(suppressed) {
311
+ this.suppressFetches = suppressed;
312
+ }
313
+ /**
314
+ * @inheritdoc
315
+ */
316
+ async handleQueryChange() {
317
+ // Don't react to the change if fetches are suppressed for this data source
318
+ if (this.suppressFetches)
319
+ return;
320
+ this.reset();
321
+ // Reset the `initialSearchComplete` promise with a new value for the imminent search
322
+ this._initialSearchCompletePromise = new Promise(res => {
323
+ this._initialSearchCompleteResolver = res;
324
+ });
325
+ const shouldFetchFacets = !this.host.suppressFacets &&
326
+ !FACETLESS_PAGE_ELEMENTS.includes(this.host.profileElement);
327
+ // Fire the initial page & facet requests
328
+ this.queryInitialized = true;
329
+ await Promise.all([
330
+ this.doInitialPageFetch(),
331
+ shouldFetchFacets ? this.fetchFacets() : null,
332
+ ]);
333
+ // Resolve the `initialSearchComplete` promise for this search
334
+ this._initialSearchCompleteResolver(true);
335
+ }
336
+ /**
337
+ * @inheritdoc
338
+ */
339
+ map(callback) {
340
+ this.pages = Object.fromEntries(Object.entries(this.pages).map(([page, tileModels]) => [
341
+ page,
342
+ tileModels.map((model, index, array) => model ? callback(model, index, array) : model),
343
+ ]));
344
+ this.requestHostUpdate();
345
+ this.refreshVisibleResults();
346
+ }
347
+ /**
348
+ * @inheritdoc
349
+ */
350
+ get checkedTileModels() {
351
+ return this.getFilteredTileModels(model => model.checked);
352
+ }
353
+ /**
354
+ * @inheritdoc
355
+ */
356
+ get uncheckedTileModels() {
357
+ return this.getFilteredTileModels(model => !model.checked);
358
+ }
359
+ /**
360
+ * Returns a flattened, filtered array of all the tile models in the data source
361
+ * for which the given predicate returns a truthy value.
362
+ *
363
+ * @param predicate A callback function to apply on each tile model, as with Array.filter
364
+ * @returns A filtered array of tile models satisfying the predicate
365
+ */
366
+ getFilteredTileModels(predicate) {
367
+ return Object.values(this.pages)
368
+ .flat()
369
+ .filter((model, index, array) => model ? predicate(model, index, array) : false);
370
+ }
371
+ /**
372
+ * @inheritdoc
373
+ */
374
+ get canPerformSearch() {
375
+ var _a;
376
+ if (!this.host.searchService)
377
+ return false;
378
+ const trimmedQuery = (_a = this.host.baseQuery) === null || _a === void 0 ? void 0 : _a.trim();
379
+ const hasNonEmptyQuery = !!trimmedQuery;
380
+ const isCollectionSearch = !!this.host.withinCollection;
381
+ const isProfileSearch = !!this.host.withinProfile;
382
+ const hasProfileElement = !!this.host.profileElement;
383
+ const isMetadataSearch = this.host.searchType === SearchType.METADATA;
384
+ // Metadata searches within a collection/profile are allowed to have no query.
385
+ // Otherwise, a non-empty query must be set.
386
+ return (hasNonEmptyQuery ||
387
+ (isCollectionSearch && isMetadataSearch) ||
388
+ (isProfileSearch && hasProfileElement && isMetadataSearch));
389
+ }
390
+ /**
391
+ * Sets the state for whether the initial set of search results for the
392
+ * current query is loading
393
+ */
394
+ setSearchResultsLoading(loading) {
395
+ this.searchResultsLoading = loading;
396
+ if (this.activeOnHost) {
397
+ this.host.setSearchResultsLoading(loading);
398
+ }
399
+ }
400
+ /**
401
+ * Sets the state for whether the facets for a query is loading
402
+ */
403
+ setFacetsLoading(loading) {
404
+ this.facetsLoading = loading;
405
+ if (this.activeOnHost) {
406
+ this.host.setFacetsLoading(loading);
407
+ }
408
+ }
409
+ /**
410
+ * Requests that the host perform an update, provided this data
411
+ * source is actively installed on it.
412
+ */
413
+ requestHostUpdate() {
414
+ if (this.activeOnHost) {
415
+ this.host.requestUpdate();
416
+ }
417
+ }
418
+ /**
419
+ * Requests that the host refresh its visible tiles, provided this
420
+ * data source is actively installed on it.
421
+ */
422
+ refreshVisibleResults() {
423
+ if (this.activeOnHost) {
424
+ this.host.refreshVisibleResults();
425
+ }
426
+ }
427
+ /**
428
+ * The query key is a string that uniquely identifies the current search.
429
+ * It consists of:
430
+ * - The current base query
431
+ * - The current collection/profile target & page element
432
+ * - The current search type
433
+ * - Any currently-applied facets
434
+ * - Any currently-applied date range
435
+ * - Any currently-applied prefix filters
436
+ * - The current sort options
437
+ *
438
+ * This lets us internally keep track of queries so we don't persist data that's
439
+ * no longer relevant. Not meant to be human-readable.
440
+ */
441
+ get pageFetchQueryKey() {
442
+ var _a, _b, _c;
443
+ const profileKey = `pf;${this.host.withinProfile}--pe;${this.host.profileElement}`;
444
+ const pageTarget = (_a = this.host.withinCollection) !== null && _a !== void 0 ? _a : profileKey;
445
+ const sortField = (_b = this.host.selectedSort) !== null && _b !== void 0 ? _b : 'none';
446
+ const sortDirection = (_c = this.host.sortDirection) !== null && _c !== void 0 ? _c : 'none';
447
+ return `fq:${this.fullQuery}-pt:${pageTarget}-st:${this.host.searchType}-sf:${sortField}-sd:${sortDirection}`;
448
+ }
449
+ /**
450
+ * Similar to `pageFetchQueryKey` above, but excludes sort fields since they
451
+ * are not relevant in determining aggregation queries.
452
+ */
453
+ get facetFetchQueryKey() {
454
+ var _a;
455
+ const profileKey = `pf;${this.host.withinProfile}--pe;${this.host.profileElement}`;
456
+ const pageTarget = (_a = this.host.withinCollection) !== null && _a !== void 0 ? _a : profileKey;
457
+ return `fq:${this.fullQuery}-pt:${pageTarget}-st:${this.host.searchType}`;
458
+ }
459
+ /**
460
+ * Constructs a search service FilterMap object from the combination of
461
+ * all the currently-applied filters. This includes any facets, letter
462
+ * filters, and date range.
463
+ */
464
+ get filterMap() {
465
+ const builder = new FilterMapBuilder();
466
+ // Add the date range, if applicable
467
+ if (this.host.minSelectedDate) {
468
+ builder.addFilter('year', this.host.minSelectedDate, FilterConstraint.GREATER_OR_EQUAL);
469
+ }
470
+ if (this.host.maxSelectedDate) {
471
+ builder.addFilter('year', this.host.maxSelectedDate, FilterConstraint.LESS_OR_EQUAL);
472
+ }
473
+ // Add any selected facets
474
+ if (this.host.selectedFacets) {
475
+ for (const [facetName, facetValues] of Object.entries(this.host.selectedFacets)) {
476
+ const { name, values } = this.prepareFacetForFetch(facetName, facetValues);
477
+ for (const [value, bucket] of Object.entries(values)) {
478
+ let constraint;
479
+ if (bucket.state === 'selected') {
480
+ constraint = FilterConstraint.INCLUDE;
481
+ }
482
+ else if (bucket.state === 'hidden') {
483
+ constraint = FilterConstraint.EXCLUDE;
484
+ }
485
+ if (constraint) {
486
+ builder.addFilter(name, value, constraint);
487
+ }
488
+ }
489
+ }
490
+ }
491
+ // Add any letter filters
492
+ if (this.host.selectedTitleFilter) {
493
+ builder.addFilter('firstTitle', this.host.selectedTitleFilter, FilterConstraint.INCLUDE);
494
+ }
495
+ if (this.host.selectedCreatorFilter) {
496
+ builder.addFilter('firstCreator', this.host.selectedCreatorFilter, FilterConstraint.INCLUDE);
497
+ }
498
+ const filterMap = builder.build();
499
+ return filterMap;
500
+ }
501
+ /**
502
+ * Produces a compact unique ID for a search request that can help with debugging
503
+ * on the backend by making related requests easier to trace through different services.
504
+ * (e.g., tying the hits/aggregations requests for the same page back to a single hash).
505
+ *
506
+ * @param params The search service parameters for the request
507
+ * @param kind The kind of request (hits-only, aggregations-only, or both)
508
+ * @returns A Promise resolving to the uid to apply to the request
509
+ */
510
+ async requestUID(params, kind) {
511
+ var _a;
512
+ const paramsToHash = JSON.stringify({
513
+ pageType: params.pageType,
514
+ pageTarget: params.pageTarget,
515
+ query: params.query,
516
+ fields: params.fields,
517
+ filters: params.filters,
518
+ sort: params.sort,
519
+ searchType: this.host.searchType,
520
+ });
521
+ const fullQueryHash = (await sha1(paramsToHash)).slice(0, 20); // First 80 bits of SHA-1 are plenty for this
522
+ const sessionId = (await this.host.getSessionId()).slice(0, 20); // Likewise
523
+ const page = (_a = params.page) !== null && _a !== void 0 ? _a : 0;
524
+ const kindPrefix = kind.charAt(0); // f = full, h = hits, a = aggregations
525
+ const currentTime = Date.now();
526
+ return `R:${fullQueryHash}-S:${sessionId}-P:${page}-K:${kindPrefix}-T:${currentTime}`;
527
+ }
528
+ /**
529
+ * @inheritdoc
530
+ */
531
+ get pageSpecifierParams() {
532
+ if (this.host.withinCollection) {
533
+ return {
534
+ pageType: 'collection_details',
535
+ pageTarget: this.host.withinCollection,
536
+ };
537
+ }
538
+ if (this.host.withinProfile) {
539
+ return {
540
+ pageType: 'account_details',
541
+ pageTarget: this.host.withinProfile,
542
+ pageElements: this.host.profileElement
543
+ ? [this.host.profileElement]
544
+ : [],
545
+ };
546
+ }
547
+ return null;
548
+ }
549
+ /**
550
+ * The full query, including year facets and date range clauses
551
+ */
552
+ get fullQuery() {
553
+ var _a, _b;
554
+ let fullQuery = (_b = (_a = this.host.baseQuery) === null || _a === void 0 ? void 0 : _a.trim()) !== null && _b !== void 0 ? _b : '';
555
+ const { facetQuery, dateRangeQueryClause, sortFilterQueries } = this;
556
+ if (facetQuery) {
557
+ fullQuery += ` AND ${facetQuery}`;
558
+ }
559
+ if (dateRangeQueryClause) {
560
+ fullQuery += ` AND ${dateRangeQueryClause}`;
561
+ }
562
+ if (sortFilterQueries) {
563
+ fullQuery += ` AND ${sortFilterQueries}`;
564
+ }
565
+ return fullQuery.trim();
566
+ }
567
+ /**
568
+ * Generates a query string representing the current set of applied facets
569
+ *
570
+ * Example: `mediatype:("collection" OR "audio" OR -"etree") AND year:("2000" OR "2001")`
571
+ */
572
+ get facetQuery() {
573
+ var _a;
574
+ if (!this.host.selectedFacets)
575
+ return undefined;
576
+ const facetClauses = [];
577
+ for (const [facetName, facetValues] of Object.entries(this.host.selectedFacets)) {
578
+ facetClauses.push(this.buildFacetClause(facetName, facetValues));
579
+ }
580
+ return (_a = this.joinFacetClauses(facetClauses)) === null || _a === void 0 ? void 0 : _a.trim();
581
+ }
582
+ get dateRangeQueryClause() {
583
+ if (!this.host.minSelectedDate || !this.host.maxSelectedDate) {
584
+ return undefined;
585
+ }
586
+ return `year:[${this.host.minSelectedDate} TO ${this.host.maxSelectedDate}]`;
587
+ }
588
+ get sortFilterQueries() {
589
+ const queries = [this.titleQuery, this.creatorQuery];
590
+ return queries.filter(q => q).join(' AND ');
591
+ }
592
+ /**
593
+ * Returns a query clause identifying the currently selected title filter,
594
+ * e.g., `firstTitle:X`.
595
+ */
596
+ get titleQuery() {
597
+ return this.host.selectedTitleFilter
598
+ ? `firstTitle:${this.host.selectedTitleFilter}`
599
+ : undefined;
600
+ }
601
+ /**
602
+ * Returns a query clause identifying the currently selected creator filter,
603
+ * e.g., `firstCreator:X`.
604
+ */
605
+ get creatorQuery() {
606
+ return this.host.selectedCreatorFilter
607
+ ? `firstCreator:${this.host.selectedCreatorFilter}`
608
+ : undefined;
609
+ }
610
+ /**
611
+ * Builds an OR-joined facet clause for the given facet name and values.
612
+ *
613
+ * E.g., for name `subject` and values
614
+ * `{ foo: { state: 'selected' }, bar: { state: 'hidden' } }`
615
+ * this will produce the clause
616
+ * `subject:("foo" OR -"bar")`.
617
+ *
618
+ * @param facetName The facet type (e.g., 'collection')
619
+ * @param facetValues The facet buckets, mapped by their keys
620
+ */
621
+ buildFacetClause(facetName, facetValues) {
622
+ const { name: facetQueryName, values } = this.prepareFacetForFetch(facetName, facetValues);
623
+ const facetEntries = Object.entries(values);
624
+ if (facetEntries.length === 0)
625
+ return '';
626
+ const facetValuesArray = [];
627
+ for (const [key, facetData] of facetEntries) {
628
+ const plusMinusPrefix = facetData.state === 'hidden' ? '-' : '';
629
+ facetValuesArray.push(`${plusMinusPrefix}"${key}"`);
630
+ }
631
+ const valueQuery = facetValuesArray.join(` OR `);
632
+ return `${facetQueryName}:(${valueQuery})`;
633
+ }
634
+ /**
635
+ * Handles some special pre-request normalization steps for certain facet types
636
+ * that require them.
637
+ *
638
+ * @param facetName The name of the facet type (e.g., 'language')
639
+ * @param facetValues An array of values for that facet type
640
+ */
641
+ prepareFacetForFetch(facetName, facetValues) {
642
+ // eslint-disable-next-line prefer-const
643
+ let [normalizedName, normalizedValues] = [facetName, facetValues];
644
+ // The full "search engine" name of the lending field is "lending___status"
645
+ if (facetName === 'lending') {
646
+ normalizedName = 'lending___status';
647
+ }
648
+ return {
649
+ name: normalizedName,
650
+ values: normalizedValues,
651
+ };
652
+ }
653
+ /**
654
+ * Takes an array of facet clauses, and combines them into a
655
+ * full AND-joined facet query string. Empty clauses are ignored.
656
+ */
657
+ joinFacetClauses(facetClauses) {
658
+ const nonEmptyFacetClauses = facetClauses.filter(clause => clause.length > 0);
659
+ return nonEmptyFacetClauses.length > 0
660
+ ? `(${nonEmptyFacetClauses.join(' AND ')})`
661
+ : undefined;
662
+ }
663
+ /**
664
+ * Fires a backend request to fetch a set of aggregations (representing UI facets) for
665
+ * the current search state.
666
+ */
667
+ async fetchFacets() {
668
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
669
+ const trimmedQuery = (_a = this.host.baseQuery) === null || _a === void 0 ? void 0 : _a.trim();
670
+ if (!this.canPerformSearch)
671
+ return;
672
+ const { facetFetchQueryKey } = this;
673
+ if (this.fetchesInProgress.has(facetFetchQueryKey))
674
+ return;
675
+ this.fetchesInProgress.add(facetFetchQueryKey);
676
+ const sortParams = this.host.sortParam ? [this.host.sortParam] : [];
677
+ const params = {
678
+ ...this.pageSpecifierParams,
679
+ query: trimmedQuery || '',
680
+ rows: 0,
681
+ filters: this.filterMap,
682
+ // Fetch a few extra buckets beyond the 6 we show, in case some get suppressed
683
+ aggregationsSize: 10,
684
+ // Note: we don't need an aggregations param to fetch the default aggregations from the PPS.
685
+ // The default aggregations for the search_results page type should be what we need here.
686
+ };
687
+ params.uid = await this.requestUID({ ...params, sort: sortParams }, 'aggregations');
688
+ this.setFacetsLoading(true);
689
+ const searchResponse = await ((_b = this.host.searchService) === null || _b === void 0 ? void 0 : _b.search(params, this.host.searchType));
690
+ const success = searchResponse === null || searchResponse === void 0 ? void 0 : searchResponse.success;
691
+ // This is checking to see if the query has changed since the data was fetched.
692
+ // If so, we just want to discard this set of aggregations because they are
693
+ // likely no longer valid for the newer query.
694
+ const queryChangedSinceFetch = !this.fetchesInProgress.has(facetFetchQueryKey);
695
+ this.fetchesInProgress.delete(facetFetchQueryKey);
696
+ if (queryChangedSinceFetch)
697
+ return;
698
+ if (!success) {
699
+ const errorMsg = (_c = searchResponse === null || searchResponse === void 0 ? void 0 : searchResponse.error) === null || _c === void 0 ? void 0 : _c.message;
700
+ 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;
701
+ if (!errorMsg && !detailMsg) {
702
+ // @ts-ignore: Property 'Sentry' does not exist on type 'Window & typeof globalThis'
703
+ (_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');
704
+ }
705
+ this.setFacetsLoading(false);
706
+ return;
707
+ }
708
+ const { aggregations, collectionTitles } = success.response;
709
+ this.aggregations = aggregations;
710
+ if (collectionTitles) {
711
+ for (const [id, title] of Object.entries(collectionTitles)) {
712
+ this.collectionTitles.set(id, title);
713
+ }
714
+ }
715
+ this.yearHistogramAggregation =
716
+ (_j = (_h = success === null || success === void 0 ? void 0 : success.response) === null || _h === void 0 ? void 0 : _h.aggregations) === null || _j === void 0 ? void 0 : _j.year_histogram;
717
+ this.setFacetsLoading(false);
718
+ this.requestHostUpdate();
719
+ }
720
+ /**
721
+ * Performs the initial page fetch(es) for the current search state.
722
+ */
723
+ async doInitialPageFetch() {
724
+ this.setSearchResultsLoading(true);
725
+ // Try to batch 2 initial page requests when possible
726
+ await this.fetchPage(this.host.initialPageNumber, 2);
727
+ }
728
+ /**
729
+ * Fetches one or more pages of results and updates the data source.
730
+ *
731
+ * @param pageNumber The page number to fetch
732
+ * @param numInitialPages If this is an initial page fetch (`pageNumber = 1`),
733
+ * specifies how many pages to batch together in one request. Ignored
734
+ * if `pageNumber != 1`, defaulting to a single page.
735
+ */
736
+ async fetchPage(pageNumber, numInitialPages = 1) {
737
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
738
+ const trimmedQuery = (_a = this.host.baseQuery) === null || _a === void 0 ? void 0 : _a.trim();
739
+ if (!this.canPerformSearch)
740
+ return;
741
+ // if we already have data, don't fetch again
742
+ if (this.hasPage(pageNumber))
743
+ return;
744
+ if (this.endOfDataReached)
745
+ return;
746
+ // Batch multiple initial page requests together if needed (e.g., can request
747
+ // pages 1 and 2 together in a single request).
748
+ let numPages = pageNumber === 1 ? numInitialPages : 1;
749
+ const numRows = this.pageSize * numPages;
750
+ // if a fetch is already in progress for this query and page, don't fetch again
751
+ const { pageFetchQueryKey } = this;
752
+ const currentPageKey = `${pageFetchQueryKey}-p:${pageNumber}`;
753
+ if (this.fetchesInProgress.has(currentPageKey))
754
+ return;
755
+ for (let i = 0; i < numPages; i += 1) {
756
+ this.fetchesInProgress.add(`${pageFetchQueryKey}-p:${pageNumber + i}`);
757
+ }
758
+ this.previousQueryKey = pageFetchQueryKey;
759
+ let sortParams = this.host.sortParam ? [this.host.sortParam] : [];
760
+ // TODO eventually the PPS should handle these defaults natively
761
+ const isDefaultProfileSort = this.host.withinProfile && this.host.selectedSort === SortField.default;
762
+ if (isDefaultProfileSort && this.host.defaultSortParam) {
763
+ const sortOption = SORT_OPTIONS[this.host.defaultSortParam.field];
764
+ if (sortOption.searchServiceKey) {
765
+ sortParams = [
766
+ {
767
+ field: sortOption.searchServiceKey,
768
+ direction: 'desc',
769
+ },
770
+ ];
771
+ }
772
+ }
773
+ const params = {
774
+ ...this.pageSpecifierParams,
775
+ query: trimmedQuery || '',
776
+ page: pageNumber,
777
+ rows: numRows,
778
+ sort: sortParams,
779
+ filters: this.filterMap,
780
+ aggregations: { omit: true },
781
+ };
782
+ params.uid = await this.requestUID(params, 'hits');
783
+ log('=== FIRING PAGE REQUEST ===', params);
784
+ const searchResponse = await ((_b = this.host.searchService) === null || _b === void 0 ? void 0 : _b.search(params, this.host.searchType));
785
+ log('=== RECEIVED PAGE RESPONSE IN CB ===', searchResponse);
786
+ const success = searchResponse === null || searchResponse === void 0 ? void 0 : searchResponse.success;
787
+ // This is checking to see if the fetch has been invalidated since it was fired off.
788
+ // If so, we just want to discard the response since it is for an obsolete query state.
789
+ if (!this.fetchesInProgress.has(currentPageKey))
790
+ return;
791
+ for (let i = 0; i < numPages; i += 1) {
792
+ this.fetchesInProgress.delete(`${pageFetchQueryKey}-p:${pageNumber + i}`);
793
+ }
794
+ if (!success) {
795
+ const errorMsg = (_c = searchResponse === null || searchResponse === void 0 ? void 0 : searchResponse.error) === null || _c === void 0 ? void 0 : _c.message;
796
+ 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;
797
+ this.queryErrorMessage = `${errorMsg !== null && errorMsg !== void 0 ? errorMsg : ''}${detailMsg ? `; ${detailMsg}` : ''}`;
798
+ if (!this.queryErrorMessage) {
799
+ this.queryErrorMessage = 'Missing or malformed response from backend';
800
+ // @ts-ignore: Property 'Sentry' does not exist on type 'Window & typeof globalThis'
801
+ (_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, this.queryErrorMessage, 'error');
802
+ }
803
+ this.setSearchResultsLoading(false);
804
+ this.requestHostUpdate();
805
+ return;
806
+ }
807
+ this.setTotalResultCount(success.response.totalResults - this.offset);
808
+ if (this.activeOnHost && this.totalResults === 0) {
809
+ // display event to offshoot when result count is zero.
810
+ this.host.emitEmptyResults();
811
+ }
812
+ this.sessionContext = success.sessionContext;
813
+ if (this.host.withinCollection) {
814
+ this.collectionExtraInfo = success.response.collectionExtraInfo;
815
+ // For collections, we want the UI to respect the default sort option
816
+ // which can be specified in metadata, or otherwise assumed to be week:desc
817
+ if (this.activeOnHost) {
818
+ this.host.applyDefaultCollectionSort(this.collectionExtraInfo);
819
+ }
820
+ if (this.collectionExtraInfo) {
821
+ this.parentCollections = [].concat((_j = (_h = this.collectionExtraInfo.public_metadata) === null || _h === void 0 ? void 0 : _h.collection) !== null && _j !== void 0 ? _j : []);
822
+ }
823
+ }
824
+ else if (this.host.withinProfile) {
825
+ this.accountExtraInfo = success.response.accountExtraInfo;
826
+ this.pageElements = success.response.pageElements;
827
+ }
828
+ const { results, collectionTitles } = success.response;
829
+ if (results && results.length > 0) {
830
+ // Load any collection titles present on the response into the cache,
831
+ // or queue up preload fetches for them if none were present.
832
+ if (collectionTitles) {
833
+ for (const [id, title] of Object.entries(collectionTitles)) {
834
+ this.collectionTitles.set(id, title);
835
+ }
836
+ }
837
+ // Update the data source for each returned page.
838
+ // For loans and web archives, we must account for receiving more pages than we asked for.
839
+ if (this.host.profileElement === 'lending' ||
840
+ this.host.profileElement === 'web_archives') {
841
+ numPages = Math.ceil(results.length / this.pageSize);
842
+ this.endOfDataReached = true;
843
+ if (this.activeOnHost)
844
+ this.host.setTileCount(this.totalResults);
845
+ }
846
+ for (let i = 0; i < numPages; i += 1) {
847
+ const pageStartIndex = this.pageSize * i;
848
+ this.addFetchedResultsToDataSource(pageNumber + i, results.slice(pageStartIndex, pageStartIndex + this.pageSize));
849
+ }
850
+ }
851
+ // When we reach the end of the data, we can set the infinite scroller's
852
+ // item count to the real total number of results (rather than the
853
+ // temporary estimates based on pages rendered so far).
854
+ if (this.size >= this.totalResults || results.length === 0) {
855
+ this.endOfDataReached = true;
856
+ if (this.activeOnHost)
857
+ this.host.setTileCount(this.size);
858
+ }
859
+ this.setSearchResultsLoading(false);
860
+ this.requestHostUpdate();
861
+ }
862
+ /**
863
+ * Update the datasource from the fetch response
864
+ *
865
+ * @param pageNumber
866
+ * @param results
867
+ */
868
+ addFetchedResultsToDataSource(pageNumber, results) {
869
+ const tiles = [];
870
+ results === null || results === void 0 ? void 0 : results.forEach(result => {
871
+ if (!result.identifier)
872
+ return;
873
+ tiles.push(new TileModel(result));
874
+ });
875
+ this.addPage(pageNumber, tiles);
876
+ const visiblePages = this.host.currentVisiblePageNumbers;
877
+ const needsReload = visiblePages.includes(pageNumber);
878
+ if (needsReload) {
879
+ this.refreshVisibleResults();
880
+ }
881
+ }
882
+ /**
883
+ * Fetches the aggregation buckets for the given prefix filter type.
884
+ */
885
+ async fetchPrefixFilterBuckets(filterType) {
886
+ var _a, _b, _c, _d, _e, _f, _g;
887
+ const trimmedQuery = (_a = this.host.baseQuery) === null || _a === void 0 ? void 0 : _a.trim();
888
+ if (!this.canPerformSearch)
889
+ return [];
890
+ const filterAggregationKey = prefixFilterAggregationKeys[filterType];
891
+ const sortParams = this.host.sortParam ? [this.host.sortParam] : [];
892
+ const params = {
893
+ ...this.pageSpecifierParams,
894
+ query: trimmedQuery || '',
895
+ rows: 0,
896
+ filters: this.filterMap,
897
+ // Only fetch the firstTitle or firstCreator aggregation
898
+ aggregations: { simpleParams: [filterAggregationKey] },
899
+ // Fetch all 26 letter buckets
900
+ aggregationsSize: 26,
901
+ };
902
+ params.uid = await this.requestUID({ ...params, sort: sortParams }, 'aggregations');
903
+ const searchResponse = await ((_b = this.host.searchService) === null || _b === void 0 ? void 0 : _b.search(params, this.host.searchType));
904
+ 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 : []);
905
+ }
906
+ /**
907
+ * Fetches and caches the prefix filter counts for the given filter type.
908
+ */
909
+ async updatePrefixFilterCounts(filterType) {
910
+ const { facetFetchQueryKey } = this;
911
+ const buckets = await this.fetchPrefixFilterBuckets(filterType);
912
+ // Don't update the filter counts for an outdated query (if it has been changed
913
+ // since we sent the request)
914
+ const queryChangedSinceFetch = facetFetchQueryKey !== this.facetFetchQueryKey;
915
+ if (queryChangedSinceFetch)
916
+ return;
917
+ // Unpack the aggregation buckets into a simple map like { 'A': 50, 'B': 25, ... }
918
+ this.prefixFilterCountMap = { ...this.prefixFilterCountMap }; // Clone the object to trigger an update
919
+ this.prefixFilterCountMap[filterType] = buckets.reduce((acc, bucket) => {
920
+ acc[bucket.key.toUpperCase()] = bucket.doc_count;
921
+ return acc;
922
+ }, {});
923
+ this.requestHostUpdate();
924
+ }
925
+ /**
926
+ * @inheritdoc
927
+ */
928
+ async updatePrefixFiltersForCurrentSort() {
929
+ if (['title', 'creator'].includes(this.host.selectedSort)) {
930
+ const filterType = this.host.selectedSort;
931
+ if (!this.prefixFilterCountMap[filterType]) {
932
+ this.updatePrefixFilterCounts(filterType);
933
+ }
934
+ }
935
+ }
936
+ /**
937
+ * @inheritdoc
938
+ */
939
+ refreshLetterCounts() {
940
+ if (Object.keys(this.prefixFilterCountMap).length > 0) {
941
+ this.prefixFilterCountMap = {};
942
+ }
943
+ this.updatePrefixFiltersForCurrentSort();
944
+ this.requestHostUpdate();
945
+ }
946
+ }
947
947
  //# sourceMappingURL=collection-browser-data-source.js.map