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