@internetarchive/collection-browser 1.14.14-alpha.1 → 1.14.16-alpha.1

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 (69) hide show
  1. package/dist/index.d.ts +1 -0
  2. package/dist/index.js +1 -0
  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 +24 -169
  8. package/dist/src/collection-browser.js +68 -684
  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 +5 -9
  21. package/dist/src/collection-facets.js.map +1 -1
  22. package/dist/src/data-source/collection-browser-data-source.d.ts +402 -0
  23. package/dist/src/data-source/collection-browser-data-source.js +742 -0
  24. package/dist/src/data-source/collection-browser-data-source.js.map +1 -0
  25. package/dist/src/data-source/models.d.ts +35 -0
  26. package/dist/src/data-source/models.js +2 -0
  27. package/dist/src/data-source/models.js.map +1 -0
  28. package/dist/src/tiles/hover/hover-pane-controller.d.ts +2 -2
  29. package/dist/src/tiles/hover/hover-pane-controller.js +1 -1
  30. package/dist/src/tiles/hover/hover-pane-controller.js.map +1 -1
  31. package/dist/src/tiles/hover/tile-hover-pane.d.ts +2 -2
  32. package/dist/src/tiles/hover/tile-hover-pane.js +2 -2
  33. package/dist/src/tiles/hover/tile-hover-pane.js.map +1 -1
  34. package/dist/src/tiles/list/tile-list.d.ts +3 -3
  35. package/dist/src/tiles/list/tile-list.js +7 -13
  36. package/dist/src/tiles/list/tile-list.js.map +1 -1
  37. package/dist/src/tiles/tile-dispatcher.d.ts +2 -2
  38. package/dist/src/tiles/tile-dispatcher.js +2 -3
  39. package/dist/src/tiles/tile-dispatcher.js.map +1 -1
  40. package/dist/test/collection-browser.test.js +43 -67
  41. package/dist/test/collection-browser.test.js.map +1 -1
  42. package/dist/test/collection-facets/facet-row.test.js +6 -17
  43. package/dist/test/collection-facets/facet-row.test.js.map +1 -1
  44. package/dist/test/collection-facets.test.js +0 -5
  45. package/dist/test/collection-facets.test.js.map +1 -1
  46. package/dist/test/tiles/list/tile-list.test.js +0 -5
  47. package/dist/test/tiles/list/tile-list.test.js.map +1 -1
  48. package/index.ts +4 -0
  49. package/package.json +3 -3
  50. package/src/app-root.ts +0 -10
  51. package/src/collection-browser.ts +79 -841
  52. package/src/collection-facets/facet-row.ts +4 -9
  53. package/src/collection-facets/facets-template.ts +3 -3
  54. package/src/collection-facets/more-facets-content.ts +15 -20
  55. package/src/collection-facets.ts +5 -10
  56. package/src/data-source/collection-browser-data-source.ts +1133 -0
  57. package/src/data-source/models.ts +45 -0
  58. package/src/tiles/hover/hover-pane-controller.ts +3 -3
  59. package/src/tiles/hover/tile-hover-pane.ts +3 -3
  60. package/src/tiles/list/tile-list.ts +13 -18
  61. package/src/tiles/tile-dispatcher.ts +3 -4
  62. package/test/collection-browser.test.ts +57 -79
  63. package/test/collection-facets/facet-row.test.ts +5 -18
  64. package/test/collection-facets.test.ts +0 -5
  65. package/test/tiles/list/tile-list.test.ts +0 -5
  66. package/dist/test/mocks/mock-collection-name-cache.d.ts +0 -9
  67. package/dist/test/mocks/mock-collection-name-cache.js +0 -18
  68. package/dist/test/mocks/mock-collection-name-cache.js.map +0 -1
  69. package/test/mocks/mock-collection-name-cache.ts +0 -24
@@ -17,14 +17,7 @@ import type {
17
17
  InfiniteScrollerCellProviderInterface,
18
18
  } from '@internetarchive/infinite-scroller';
19
19
  import {
20
- Aggregation,
21
- Bucket,
22
20
  CollectionExtraInfo,
23
- FilterConstraint,
24
- FilterMap,
25
- FilterMapBuilder,
26
- SearchParams,
27
- SearchResult,
28
21
  SearchServiceInterface,
29
22
  SearchType,
30
23
  SortDirection,
@@ -35,7 +28,6 @@ import type {
35
28
  SharedResizeObserverResizeHandlerInterface,
36
29
  } from '@internetarchive/shared-resize-observer';
37
30
  import '@internetarchive/infinite-scroller';
38
- import type { CollectionNameCacheInterface } from '@internetarchive/collection-name-cache';
39
31
  import type { ModalManagerInterface } from '@internetarchive/modal-manager';
40
32
  import type { FeatureFeedbackServiceInterface } from '@internetarchive/feature-feedback';
41
33
  import type { RecaptchaManagerInterface } from '@internetarchive/recaptcha-manager';
@@ -52,10 +44,8 @@ import {
52
44
  getDefaultSelectedFacets,
53
45
  TileModel,
54
46
  CollectionDisplayMode,
55
- FacetBucket,
56
47
  PrefixFilterType,
57
48
  PrefixFilterCounts,
58
- prefixFilterAggregationKeys,
59
49
  FacetEventDetails,
60
50
  sortOptionFromAPIString,
61
51
  SORT_OPTIONS,
@@ -65,6 +55,11 @@ import {
65
55
  RestorationStateHandler,
66
56
  RestorationState,
67
57
  } from './restoration-state-handler';
58
+ import {
59
+ CollectionBrowserDataSource,
60
+ CollectionBrowserDataSourceInterface,
61
+ } from './data-source/collection-browser-data-source';
62
+ import type { CollectionBrowserSearchState } from './data-source/models';
68
63
  import chevronIcon from './assets/img/icons/chevron';
69
64
  import type { PlaceholderType } from './empty-placeholder';
70
65
  import './empty-placeholder';
@@ -79,14 +74,13 @@ import type { CollectionFacets } from './collection-facets';
79
74
  import type { ManageableItem } from './manage/manage-bar';
80
75
  import { formatDate } from './utils/format-date';
81
76
 
82
- type RequestKind = 'full' | 'hits' | 'aggregations';
83
-
84
77
  @customElement('collection-browser')
85
78
  export class CollectionBrowser
86
79
  extends LitElement
87
80
  implements
88
81
  InfiniteScrollerCellProviderInterface,
89
- SharedResizeObserverResizeHandlerInterface
82
+ SharedResizeObserverResizeHandlerInterface,
83
+ CollectionBrowserSearchState
90
84
  {
91
85
  @property({ type: String }) baseNavigationUrl?: string;
92
86
 
@@ -102,8 +96,6 @@ export class CollectionBrowser
102
96
 
103
97
  @property({ type: String }) displayMode?: CollectionDisplayMode;
104
98
 
105
- @property({ type: Object }) sortParam: SortParam | null = null;
106
-
107
99
  @property({ type: Object }) defaultSortParam: SortParam | null = null;
108
100
 
109
101
  @property({ type: String }) selectedSort: SortField = SortField.default;
@@ -116,8 +108,6 @@ export class CollectionBrowser
116
108
 
117
109
  @property({ type: Number }) pageSize = 50;
118
110
 
119
- @property({ type: Object }) resizeObserver?: SharedResizeObserverInterface;
120
-
121
111
  @property({ type: Number }) currentPage?: number;
122
112
 
123
113
  @property({ type: String }) minSelectedDate?: string;
@@ -146,9 +136,6 @@ export class CollectionBrowser
146
136
  @property({ type: String, reflect: true }) searchContext: string =
147
137
  analyticsCategories.default;
148
138
 
149
- @property({ type: Object })
150
- collectionNameCache?: CollectionNameCacheInterface;
151
-
152
139
  @property({ type: String }) pageContext: CollectionBrowserContext = 'search';
153
140
 
154
141
  @property({ type: Object })
@@ -162,6 +149,8 @@ export class CollectionBrowser
162
149
 
163
150
  @property({ type: Boolean }) loggedIn = false;
164
151
 
152
+ @property({ type: Object }) resizeObserver?: SharedResizeObserverInterface;
153
+
165
154
  @property({ type: Object }) modalManager?: ModalManagerInterface = undefined;
166
155
 
167
156
  @property({ type: Object })
@@ -176,10 +165,22 @@ export class CollectionBrowser
176
165
 
177
166
  @property({ type: Boolean }) isLoansTab = false;
178
167
 
168
+ @property({ type: String }) queryErrorMessage?: string;
169
+
170
+ /**
171
+ * The results per page so we can paginate.
172
+ *
173
+ * This allows us to start in the middle of the search results and
174
+ * fetch data before or after the current page. If we don't have a key
175
+ * for the previous/next page, we'll fetch the next/previous page to populate it
176
+ */
177
+ @property({ type: Object }) dataSource: CollectionBrowserDataSourceInterface =
178
+ new CollectionBrowserDataSource(this, this.pageSize);
179
+
179
180
  /**
180
181
  * The page that the consumer wants to load.
181
182
  */
182
- private initialPageNumber = 1;
183
+ initialPageNumber = 1;
183
184
 
184
185
  /**
185
186
  * This the the number of pages that we want to show.
@@ -196,16 +197,8 @@ export class CollectionBrowser
196
197
 
197
198
  @state() private facetsLoading = false;
198
199
 
199
- @state() private fullYearAggregationLoading = false;
200
-
201
- @state() private aggregations?: Record<string, Aggregation>;
202
-
203
- @state() private fullYearsHistogramAggregation: Aggregation | undefined;
204
-
205
200
  @state() private totalResults?: number;
206
201
 
207
- @state() private queryErrorMessage?: string;
208
-
209
202
  @state() private mobileView = false;
210
203
 
211
204
  @state() private mobileFacetsVisible = false;
@@ -257,28 +250,22 @@ export class CollectionBrowser
257
250
 
258
251
  private tileModelAtCellIndex(index: number): TileModel | undefined {
259
252
  const offsetIndex = index + this.tileModelOffset;
260
- const pageNumber = Math.floor(offsetIndex / this.pageSize) + 1;
261
- const itemIndex = offsetIndex % this.pageSize;
262
- const model = this.dataSource[pageNumber]?.[itemIndex];
253
+ const model = this.dataSource.getTileModelAt(offsetIndex);
263
254
  /**
264
255
  * If we encounter a model we don't have yet and we're not in the middle of an
265
256
  * automated scroll, fetch the page and just return undefined.
266
257
  * The datasource will be updated once the page is loaded and the cell will be rendered.
267
258
  *
268
- * We disable it during the automated scroll since we may fetch pages for cells the
259
+ * We disable it during the automated scroll since we don't want to fetch pages for intervening cells the
269
260
  * user may never see.
270
261
  */
271
262
  if (!model && !this.isScrollingToCell) {
272
- this.fetchPage(pageNumber);
263
+ const pageNumber = Math.floor(offsetIndex / this.pageSize) + 1;
264
+ this.dataSource.fetchPage(pageNumber);
273
265
  }
274
266
  return model;
275
267
  }
276
268
 
277
- private get sortFilterQueries(): string {
278
- const queries = [this.titleQuery, this.creatorQuery];
279
- return queries.filter(q => q).join(' AND ');
280
- }
281
-
282
269
  // this is the total number of tiles we expect if
283
270
  // the data returned is a full page worth
284
271
  // this is useful for putting in placeholders for the expected number of tiles
@@ -286,15 +273,6 @@ export class CollectionBrowser
286
273
  return this.pagesToRender * this.pageSize;
287
274
  }
288
275
 
289
- /**
290
- * The results per page so we can paginate.
291
- *
292
- * This allows us to start in the middle of the search results and
293
- * fetch data before or after the current page. If we don't have a key
294
- * for the previous/next page, we'll fetch the next/previous page to populate it
295
- */
296
- private dataSource: Record<string, TileModel[]> = {};
297
-
298
276
  /**
299
277
  * How many tiles to offset the data source by, to account for any removed tiles.
300
278
  */
@@ -310,7 +288,7 @@ export class CollectionBrowser
310
288
  * Used in generating unique IDs for search requests, so that multiple requests coming from the
311
289
  * same browser session can be identified.
312
290
  */
313
- private async getSessionId(): Promise<string> {
291
+ async getSessionId(): Promise<string> {
314
292
  try {
315
293
  const storedSessionId = sessionStorage?.getItem('cb-session');
316
294
  if (storedSessionId) {
@@ -345,6 +323,14 @@ export class CollectionBrowser
345
323
  return this.scrollToPage(pageNumber);
346
324
  }
347
325
 
326
+ setSearchResultsLoading(loading: boolean) {
327
+ this.searchResultsLoading = loading;
328
+ }
329
+
330
+ setFacetsLoading(loading: boolean) {
331
+ this.facetsLoading = loading;
332
+ }
333
+
348
334
  /**
349
335
  * Clears all selected/negated facets, date ranges, and letter filters.
350
336
  *
@@ -378,7 +364,6 @@ export class CollectionBrowser
378
364
  }
379
365
 
380
366
  if (sort) {
381
- this.sortParam = null;
382
367
  this.sortDirection = null;
383
368
  this.selectedSort = SortField.default;
384
369
  }
@@ -616,7 +601,7 @@ export class CollectionBrowser
616
601
  .displayMode=${this.displayMode}
617
602
  .selectedTitleFilter=${this.selectedTitleFilter}
618
603
  .selectedCreatorFilter=${this.selectedCreatorFilter}
619
- .prefixFilterCountMap=${this.prefixFilterCountMap}
604
+ .prefixFilterCountMap=${this.dataSource.prefixFilterCountMap}
620
605
  .resizeObserver=${this.resizeObserver}
621
606
  @sortChanged=${this.userChangedSort}
622
607
  @displayModeChanged=${this.displayModeChanged}
@@ -641,11 +626,11 @@ export class CollectionBrowser
641
626
  showSelectAll
642
627
  showUnselectAll
643
628
  @removeItems=${this.handleRemoveItems}
644
- @selectAll=${this.checkAllTiles}
645
- @unselectAll=${this.uncheckAllTiles}
629
+ @selectAll=${this.dataSource.checkAllTiles}
630
+ @unselectAll=${this.dataSource.uncheckAllTiles}
646
631
  @cancel=${() => {
647
632
  this.isManageView = false;
648
- this.uncheckAllTiles();
633
+ this.dataSource.uncheckAllTiles();
649
634
  }}
650
635
  ></manage-bar>
651
636
  `;
@@ -659,7 +644,7 @@ export class CollectionBrowser
659
644
  this.dispatchEvent(
660
645
  new CustomEvent<{ items: ManageableItem[] }>('itemRemovalRequested', {
661
646
  detail: {
662
- items: this.checkedTileModels.map(model => ({
647
+ items: this.dataSource.checkedTileModels.map(model => ({
663
648
  ...model,
664
649
  date: formatDate(model.datePublished, 'long'),
665
650
  })),
@@ -673,113 +658,7 @@ export class CollectionBrowser
673
658
  * of the data source to account for any new gaps in the data.
674
659
  */
675
660
  removeCheckedTiles(): void {
676
- // To make sure our data source remains page-aligned, we will offset our data source by
677
- // the number of removed tiles, so that we can just add the offset when the infinite
678
- // scroller queries for cell contents.
679
- // This only matters while we're still viewing the same set of results. If the user changes
680
- // their query/filters/sort, then the data source is overwritten and the offset cleared.
681
- const { checkedTileModels, uncheckedTileModels } = this;
682
- const numChecked = checkedTileModels.length;
683
- if (numChecked === 0) return;
684
- this.tileModelOffset += numChecked;
685
-
686
- const newDataSource: typeof this.dataSource = {};
687
-
688
- // Which page the remaining tile models start on, post-offset
689
- let offsetPageNumber = Math.floor(this.tileModelOffset / this.pageSize) + 1;
690
- let indexOnPage = this.tileModelOffset % this.pageSize;
691
-
692
- // Fill the pages up to that point with empty models
693
- for (let page = 1; page <= offsetPageNumber; page += 1) {
694
- const remainingHidden = this.tileModelOffset - this.pageSize * (page - 1);
695
- const offsetCellsOnPage = Math.min(this.pageSize, remainingHidden);
696
- newDataSource[page] = Array(offsetCellsOnPage).fill(undefined);
697
- }
698
-
699
- // Shift all the remaining tiles into their new positions in the data source
700
- for (const model of uncheckedTileModels) {
701
- if (!newDataSource[offsetPageNumber])
702
- newDataSource[offsetPageNumber] = [];
703
- newDataSource[offsetPageNumber].push(model);
704
- indexOnPage += 1;
705
- if (indexOnPage >= this.pageSize) {
706
- offsetPageNumber += 1;
707
- indexOnPage = 0;
708
- }
709
- }
710
-
711
- // Swap in the new data source and update the infinite scroller
712
- this.dataSource = newDataSource;
713
- if (this.totalResults) this.totalResults -= numChecked;
714
- if (this.infiniteScroller) {
715
- this.infiniteScroller.itemCount -= numChecked;
716
- this.infiniteScroller.refreshAllVisibleCells();
717
- }
718
- }
719
-
720
- /**
721
- * Checks every tile's management checkbox
722
- */
723
- checkAllTiles(): void {
724
- this.mapDataSource(model => ({ ...model, checked: true }));
725
- }
726
-
727
- /**
728
- * Unchecks every tile's management checkbox
729
- */
730
- uncheckAllTiles(): void {
731
- this.mapDataSource(model => ({ ...model, checked: false }));
732
- }
733
-
734
- /**
735
- * Applies the given map function to all of the tile models in every page of the data
736
- * source. This method updates the data source object in immutable fashion.
737
- *
738
- * @param mapFn A callback function to apply on each tile model, as with Array.map
739
- */
740
- private mapDataSource(
741
- mapFn: (model: TileModel, index: number, array: TileModel[]) => TileModel
742
- ): void {
743
- this.dataSource = Object.fromEntries(
744
- Object.entries(this.dataSource).map(([page, tileModels]) => [
745
- page,
746
- tileModels.map((model, index, array) =>
747
- model ? mapFn(model, index, array) : model
748
- ),
749
- ])
750
- );
751
- this.infiniteScroller?.refreshAllVisibleCells();
752
- }
753
-
754
- /**
755
- * An array of all the tile models whose management checkboxes are checked
756
- */
757
- get checkedTileModels(): TileModel[] {
758
- return this.getFilteredTileModels(model => model.checked);
759
- }
760
-
761
- /**
762
- * An array of all the tile models whose management checkboxes are unchecked
763
- */
764
- get uncheckedTileModels(): TileModel[] {
765
- return this.getFilteredTileModels(model => !model.checked);
766
- }
767
-
768
- /**
769
- * Returns a flattened, filtered array of all the tile models in the data source
770
- * for which the given predicate returns a truthy value.
771
- *
772
- * @param predicate A callback function to apply on each tile model, as with Array.filter
773
- * @returns A filtered array of tile models satisfying the predicate
774
- */
775
- private getFilteredTileModels(
776
- predicate: (model: TileModel, index: number, array: TileModel[]) => unknown
777
- ): TileModel[] {
778
- return Object.values(this.dataSource)
779
- .flat()
780
- .filter((model, index, array) =>
781
- model ? predicate(model, index, array) : false
782
- );
661
+ this.dataSource.removeCheckedTiles();
783
662
  }
784
663
 
785
664
  private userChangedSort(
@@ -811,10 +690,14 @@ export class CollectionBrowser
811
690
  }
812
691
 
813
692
  private selectedSortChanged(): void {
693
+ // Lazy-load the alphabet counts for title/creator sort bar as needed
694
+ this.updatePrefixFiltersForCurrentSort();
695
+ }
696
+
697
+ get sortParam(): SortParam | null {
814
698
  const sortOption = SORT_OPTIONS[this.selectedSort];
815
- if (!sortOption.handledBySearchService) {
816
- this.sortParam = null;
817
- return;
699
+ if (!sortOption?.handledBySearchService) {
700
+ return null;
818
701
  }
819
702
 
820
703
  // If the sort option specified in the URL is unrecognized, we just use it as-is
@@ -826,11 +709,8 @@ export class CollectionBrowser
826
709
  // (i.e., it was unrecognized and had no directional flag)
827
710
  if (!this.sortDirection) this.sortDirection = 'asc';
828
711
 
829
- if (!sortField) return;
830
- this.sortParam = { field: sortField, direction: this.sortDirection };
831
-
832
- // Lazy-load the alphabet counts for title/creator sort bar as needed
833
- this.updatePrefixFiltersForCurrentSort();
712
+ if (!sortField) return null;
713
+ return { field: sortField, direction: this.sortDirection };
834
714
  }
835
715
 
836
716
  private displayModeChanged(
@@ -957,12 +837,13 @@ export class CollectionBrowser
957
837
  * The template for the facets component alone, without any surrounding wrappers.
958
838
  */
959
839
  private get facetsTemplate() {
960
- if (this.suppressFacets)
840
+ if (this.suppressFacets) {
961
841
  return html`
962
842
  <p class="facets-message">
963
843
  ${msg('Facets are temporarily unavailable.')}
964
844
  </p>
965
845
  `;
846
+ }
966
847
 
967
848
  return html`
968
849
  <collection-facets
@@ -976,18 +857,19 @@ export class CollectionBrowser
976
857
  .recaptchaManager=${this.recaptchaManager}
977
858
  .resizeObserver=${this.resizeObserver}
978
859
  .searchType=${this.searchType}
979
- .aggregations=${this.aggregations}
980
- .fullYearsHistogramAggregation=${this.fullYearsHistogramAggregation}
860
+ .aggregations=${this.dataSource.aggregations}
861
+ .fullYearsHistogramAggregation=${this.dataSource
862
+ .yearHistogramAggregation}
981
863
  .minSelectedDate=${this.minSelectedDate}
982
864
  .maxSelectedDate=${this.maxSelectedDate}
983
865
  .selectedFacets=${this.selectedFacets}
984
866
  .baseNavigationUrl=${this.baseNavigationUrl}
985
- .collectionNameCache=${this.collectionNameCache}
867
+ .collectionTitles=${this.dataSource.collectionTitles}
986
868
  .showHistogramDatePicker=${this.showHistogramDatePicker}
987
869
  .allowExpandingDatePicker=${!this.mobileView}
988
870
  .contentWidth=${this.contentWidth}
989
871
  .query=${this.baseQuery}
990
- .filterMap=${this.filterMap}
872
+ .filterMap=${this.dataSource.filterMap}
991
873
  .isManageView=${this.isManageView}
992
874
  .modalManager=${this.modalManager}
993
875
  ?collapsableFacets=${this.mobileView}
@@ -1193,7 +1075,8 @@ export class CollectionBrowser
1193
1075
  changed.has('selectedCreatorFilter') ||
1194
1076
  changed.has('minSelectedDate') ||
1195
1077
  changed.has('maxSelectedDate') ||
1196
- changed.has('sortParam') ||
1078
+ changed.has('selectedSort') ||
1079
+ changed.has('sortDirection') ||
1197
1080
  changed.has('selectedFacets') ||
1198
1081
  changed.has('searchService') ||
1199
1082
  changed.has('withinCollection')
@@ -1351,7 +1234,7 @@ export class CollectionBrowser
1351
1234
  );
1352
1235
  }
1353
1236
 
1354
- private emitEmptyResults() {
1237
+ emitEmptyResults() {
1355
1238
  this.dispatchEvent(new Event('emptyResults'));
1356
1239
  }
1357
1240
 
@@ -1435,24 +1318,23 @@ export class CollectionBrowser
1435
1318
 
1436
1319
  private async handleQueryChange() {
1437
1320
  // only reset if the query has actually changed
1438
- if (!this.searchService || this.pageFetchQueryKey === this.previousQueryKey)
1321
+ if (
1322
+ !this.searchService ||
1323
+ this.dataSource.pageFetchQueryKey === this.previousQueryKey
1324
+ )
1439
1325
  return;
1440
1326
 
1441
1327
  // If the new state prevents us from updating the search results, don't reset
1442
1328
  if (
1443
- !this.canPerformSearch &&
1329
+ !this.dataSource.canPerformSearch &&
1444
1330
  !(this.clearResultsOnEmptyQuery && this.baseQuery === '')
1445
1331
  )
1446
1332
  return;
1447
1333
 
1448
- this.previousQueryKey = this.pageFetchQueryKey;
1334
+ this.previousQueryKey = this.dataSource.pageFetchQueryKey;
1449
1335
 
1450
- this.dataSource = {};
1451
1336
  this.tileModelOffset = 0;
1452
1337
  this.totalResults = undefined;
1453
- this.aggregations = undefined;
1454
- this.fullYearsHistogramAggregation = undefined;
1455
- this.pageFetchesInProgress = {};
1456
1338
  this.endOfDataReached = false;
1457
1339
  this.pagesToRender =
1458
1340
  this.initialPageNumber === 1
@@ -1490,10 +1372,7 @@ export class CollectionBrowser
1490
1372
  });
1491
1373
 
1492
1374
  // Fire the initial page and facets requests
1493
- await Promise.all([
1494
- this.doInitialPageFetch(),
1495
- this.suppressFacets ? null : this.fetchFacets(),
1496
- ]);
1375
+ await this.dataSource.handleQueryChange();
1497
1376
 
1498
1377
  // Resolve the `initialSearchComplete` promise for this search
1499
1378
  this._initialSearchCompleteResolver(true);
@@ -1551,13 +1430,6 @@ export class CollectionBrowser
1551
1430
  this.restorationStateHandler.persistState(restorationState);
1552
1431
  }
1553
1432
 
1554
- private async doInitialPageFetch(): Promise<void> {
1555
- this.searchResultsLoading = true;
1556
- // Try to batch 2 initial page requests when possible
1557
- await this.fetchPage(this.initialPageNumber, 2);
1558
- this.searchResultsLoading = false;
1559
- }
1560
-
1561
1433
  private emitSearchResultsLoadingChanged(): void {
1562
1434
  this.dispatchEvent(
1563
1435
  new CustomEvent<{ loading: boolean }>('searchResultsLoadingChanged', {
@@ -1568,210 +1440,6 @@ export class CollectionBrowser
1568
1440
  );
1569
1441
  }
1570
1442
 
1571
- /**
1572
- * Produces a compact unique ID for a search request that can help with debugging
1573
- * on the backend by making related requests easier to trace through different services.
1574
- * (e.g., tying the hits/aggregations requests for the same page back to a single hash).
1575
- *
1576
- * @param params The search service parameters for the request
1577
- * @param kind The kind of request (hits-only, aggregations-only, or both)
1578
- * @returns A Promise resolving to the uid to apply to the request
1579
- */
1580
- private async requestUID(
1581
- params: SearchParams,
1582
- kind: RequestKind
1583
- ): Promise<string> {
1584
- const paramsToHash = JSON.stringify({
1585
- pageType: params.pageType,
1586
- pageTarget: params.pageTarget,
1587
- query: params.query,
1588
- fields: params.fields,
1589
- filters: params.filters,
1590
- sort: params.sort,
1591
- searchType: this.searchType,
1592
- });
1593
-
1594
- const fullQueryHash = (await sha1(paramsToHash)).slice(0, 20); // First 80 bits of SHA-1 are plenty for this
1595
- const sessionId = (await this.getSessionId()).slice(0, 20); // Likewise
1596
- const page = params.page ?? 0;
1597
- const kindPrefix = kind.charAt(0); // f = full, h = hits, a = aggregations
1598
- const currentTime = Date.now();
1599
-
1600
- return `R:${fullQueryHash}-S:${sessionId}-P:${page}-K:${kindPrefix}-T:${currentTime}`;
1601
- }
1602
-
1603
- /**
1604
- * Constructs a search service FilterMap object from the combination of
1605
- * all the currently-applied filters. This includes any facets, letter
1606
- * filters, and date range.
1607
- */
1608
- private get filterMap(): FilterMap {
1609
- const builder = new FilterMapBuilder();
1610
-
1611
- // Add the date range, if applicable
1612
- if (this.minSelectedDate) {
1613
- builder.addFilter(
1614
- 'year',
1615
- this.minSelectedDate,
1616
- FilterConstraint.GREATER_OR_EQUAL
1617
- );
1618
- }
1619
- if (this.maxSelectedDate) {
1620
- builder.addFilter(
1621
- 'year',
1622
- this.maxSelectedDate,
1623
- FilterConstraint.LESS_OR_EQUAL
1624
- );
1625
- }
1626
-
1627
- // Add any selected facets
1628
- if (this.selectedFacets) {
1629
- for (const [facetName, facetValues] of Object.entries(
1630
- this.selectedFacets
1631
- )) {
1632
- const { name, values } = this.prepareFacetForFetch(
1633
- facetName,
1634
- facetValues
1635
- );
1636
- for (const [value, bucket] of Object.entries(values)) {
1637
- let constraint;
1638
- if (bucket.state === 'selected') {
1639
- constraint = FilterConstraint.INCLUDE;
1640
- } else if (bucket.state === 'hidden') {
1641
- constraint = FilterConstraint.EXCLUDE;
1642
- }
1643
-
1644
- if (constraint) {
1645
- builder.addFilter(name, value, constraint);
1646
- }
1647
- }
1648
- }
1649
- }
1650
-
1651
- // Add any letter filters
1652
- if (this.selectedTitleFilter) {
1653
- builder.addFilter(
1654
- 'firstTitle',
1655
- this.selectedTitleFilter,
1656
- FilterConstraint.INCLUDE
1657
- );
1658
- }
1659
- if (this.selectedCreatorFilter) {
1660
- builder.addFilter(
1661
- 'firstCreator',
1662
- this.selectedCreatorFilter,
1663
- FilterConstraint.INCLUDE
1664
- );
1665
- }
1666
-
1667
- const filterMap = builder.build();
1668
- return filterMap;
1669
- }
1670
-
1671
- /** The full query, including year facets and date range clauses */
1672
- private get fullQuery(): string | undefined {
1673
- let fullQuery = this.baseQuery?.trim() ?? '';
1674
-
1675
- const { facetQuery, dateRangeQueryClause, sortFilterQueries } = this;
1676
-
1677
- if (facetQuery) {
1678
- fullQuery += ` AND ${facetQuery}`;
1679
- }
1680
- if (dateRangeQueryClause) {
1681
- fullQuery += ` AND ${dateRangeQueryClause}`;
1682
- }
1683
- if (sortFilterQueries) {
1684
- fullQuery += ` AND ${sortFilterQueries}`;
1685
- }
1686
- return fullQuery.trim();
1687
- }
1688
-
1689
- /**
1690
- * Generates a query string for the given facets
1691
- *
1692
- * Example: `mediatype:("collection" OR "audio" OR -"etree") AND year:("2000" OR "2001")`
1693
- */
1694
- private get facetQuery(): string | undefined {
1695
- if (!this.selectedFacets) return undefined;
1696
- const facetClauses = [];
1697
- for (const [facetName, facetValues] of Object.entries(
1698
- this.selectedFacets
1699
- )) {
1700
- facetClauses.push(this.buildFacetClause(facetName, facetValues));
1701
- }
1702
- return this.joinFacetClauses(facetClauses)?.trim();
1703
- }
1704
-
1705
- /**
1706
- * Builds an OR-joined facet clause for the given facet name and values.
1707
- *
1708
- * E.g., for name `subject` and values
1709
- * `{ foo: { state: 'selected' }, bar: { state: 'hidden' } }`
1710
- * this will produce the clause
1711
- * `subject:("foo" OR -"bar")`.
1712
- *
1713
- * @param facetName The facet type (e.g., 'collection')
1714
- * @param facetValues The facet buckets, mapped by their keys
1715
- */
1716
- private buildFacetClause(
1717
- facetName: string,
1718
- facetValues: Record<string, FacetBucket>
1719
- ): string {
1720
- const { name: facetQueryName, values } = this.prepareFacetForFetch(
1721
- facetName,
1722
- facetValues
1723
- );
1724
- const facetEntries = Object.entries(values);
1725
- if (facetEntries.length === 0) return '';
1726
-
1727
- const facetValuesArray: string[] = [];
1728
- for (const [key, facetData] of facetEntries) {
1729
- const plusMinusPrefix = facetData.state === 'hidden' ? '-' : '';
1730
- facetValuesArray.push(`${plusMinusPrefix}"${key}"`);
1731
- }
1732
-
1733
- const valueQuery = facetValuesArray.join(` OR `);
1734
- return `${facetQueryName}:(${valueQuery})`;
1735
- }
1736
-
1737
- /**
1738
- * Handles some special pre-request normalization steps for certain facet types
1739
- * that require them.
1740
- *
1741
- * @param facetName The name of the facet type (e.g., 'language')
1742
- * @param facetValues An array of values for that facet type
1743
- */
1744
- private prepareFacetForFetch(
1745
- facetName: string,
1746
- facetValues: Record<string, FacetBucket>
1747
- ): { name: string; values: Record<string, FacetBucket> } {
1748
- // eslint-disable-next-line prefer-const
1749
- let [normalizedName, normalizedValues] = [facetName, facetValues];
1750
-
1751
- // The full "search engine" name of the lending field is "lending___status"
1752
- if (facetName === 'lending') {
1753
- normalizedName = 'lending___status';
1754
- }
1755
-
1756
- return {
1757
- name: normalizedName,
1758
- values: normalizedValues,
1759
- };
1760
- }
1761
-
1762
- /**
1763
- * Takes an array of facet clauses, and combines them into a
1764
- * full AND-joined facet query string. Empty clauses are ignored.
1765
- */
1766
- private joinFacetClauses(facetClauses: string[]): string | undefined {
1767
- const nonEmptyFacetClauses = facetClauses.filter(
1768
- clause => clause.length > 0
1769
- );
1770
- return nonEmptyFacetClauses.length > 0
1771
- ? `(${nonEmptyFacetClauses.join(' AND ')})`
1772
- : undefined;
1773
- }
1774
-
1775
1443
  facetsChanged(e: CustomEvent<SelectedFacets>) {
1776
1444
  this.selectedFacets = e.detail;
1777
1445
  }
@@ -1799,76 +1467,6 @@ export class CollectionBrowser
1799
1467
  });
1800
1468
  }
1801
1469
 
1802
- private async fetchFacets() {
1803
- const trimmedQuery = this.baseQuery?.trim();
1804
- if (!this.canPerformSearch) return;
1805
-
1806
- const { facetFetchQueryKey } = this;
1807
-
1808
- const sortParams = this.sortParam ? [this.sortParam] : [];
1809
- const params: SearchParams = {
1810
- ...this.collectionParams,
1811
- query: trimmedQuery || '',
1812
- rows: 0,
1813
- filters: this.filterMap,
1814
- // Fetch a few extra buckets beyond the 6 we show, in case some get suppressed
1815
- aggregationsSize: 10,
1816
- // Note: we don't need an aggregations param to fetch the default aggregations from the PPS.
1817
- // The default aggregations for the search_results page type should be what we need here.
1818
- };
1819
- params.uid = await this.requestUID(
1820
- { ...params, sort: sortParams },
1821
- 'aggregations'
1822
- );
1823
-
1824
- this.facetsLoading = true;
1825
- const searchResponse = await this.searchService?.search(
1826
- params,
1827
- this.searchType
1828
- );
1829
- const success = searchResponse?.success;
1830
-
1831
- // This is checking to see if the query has changed since the data was fetched.
1832
- // If so, we just want to discard this set of aggregations because they are
1833
- // likely no longer valid for the newer query.
1834
- const queryChangedSinceFetch =
1835
- facetFetchQueryKey !== this.facetFetchQueryKey;
1836
- if (queryChangedSinceFetch) return;
1837
-
1838
- if (!success) {
1839
- const errorMsg = searchResponse?.error?.message;
1840
- const detailMsg = searchResponse?.error?.details?.message;
1841
-
1842
- if (!errorMsg && !detailMsg) {
1843
- // @ts-ignore: Property 'Sentry' does not exist on type 'Window & typeof globalThis'
1844
- window?.Sentry?.captureMessage?.(
1845
- 'Missing or malformed facet response from backend',
1846
- 'error'
1847
- );
1848
- }
1849
-
1850
- return;
1851
- }
1852
-
1853
- const { aggregations, collectionTitles } = success.response;
1854
- this.aggregations = aggregations;
1855
-
1856
- if (collectionTitles) {
1857
- this.collectionNameCache?.addKnownTitles(collectionTitles);
1858
- } else if (this.aggregations?.collection) {
1859
- this.collectionNameCache?.preloadIdentifiers(
1860
- (this.aggregations.collection.buckets as Bucket[]).map(bucket =>
1861
- bucket.key?.toString()
1862
- )
1863
- );
1864
- }
1865
-
1866
- this.fullYearsHistogramAggregation =
1867
- success?.response?.aggregations?.year_histogram;
1868
-
1869
- this.facetsLoading = false;
1870
- }
1871
-
1872
1470
  private scrollToPage(pageNumber: number): Promise<void> {
1873
1471
  return new Promise(resolve => {
1874
1472
  const cellIndexToScrollTo = this.pageSize * (pageNumber - 1);
@@ -1898,212 +1496,12 @@ export class CollectionBrowser
1898
1496
  return !!this.baseQuery?.trim();
1899
1497
  }
1900
1498
 
1901
- /**
1902
- * Whether a search may be performed in the current state of the component.
1903
- * This is only true if the search service is defined, and either
1904
- * (a) a non-empty query is set, or
1905
- * (b) we are on a collection page in metadata search mode.
1906
- */
1907
- private get canPerformSearch(): boolean {
1908
- if (!this.searchService) return false;
1909
-
1910
- const trimmedQuery = this.baseQuery?.trim();
1911
- const hasNonEmptyQuery = !!trimmedQuery;
1912
- const isCollectionSearch = !!this.withinCollection;
1913
- const isMetadataSearch = this.searchType === SearchType.METADATA;
1914
-
1915
- // Metadata searches within a collection are allowed to have no query.
1916
- // Otherwise, a non-empty query must be set.
1917
- return hasNonEmptyQuery || (isCollectionSearch && isMetadataSearch);
1918
- }
1919
-
1920
- /**
1921
- * Additional params to pass to the search service if targeting a collection page,
1922
- * or null otherwise.
1923
- */
1924
- private get collectionParams(): {
1925
- pageType: string;
1926
- pageTarget: string;
1927
- } | null {
1928
- return this.withinCollection
1929
- ? { pageType: 'collection_details', pageTarget: this.withinCollection }
1930
- : null;
1931
- }
1932
-
1933
- /**
1934
- * The query key is a string that uniquely identifies the current search.
1935
- * It consists of:
1936
- * - The current base query
1937
- * - The current collection
1938
- * - The current search type
1939
- * - Any currently-applied facets
1940
- * - Any currently-applied date range
1941
- * - Any currently-applied prefix filters
1942
- * - The current sort options
1943
- *
1944
- * This lets us keep track of queries so we don't persist data that's
1945
- * no longer relevant.
1946
- */
1947
- private get pageFetchQueryKey(): string {
1948
- const sortField = this.sortParam?.field ?? 'none';
1949
- const sortDirection = this.sortParam?.direction ?? 'none';
1950
- return `${this.fullQuery}-${this.withinCollection}-${this.searchType}-${sortField}-${sortDirection}`;
1951
- }
1952
-
1953
- /**
1954
- * Similar to `pageFetchQueryKey` above, but excludes sort fields since they
1955
- * are not relevant in determining aggregation queries.
1956
- */
1957
- private get facetFetchQueryKey(): string {
1958
- return `${this.fullQuery}-${this.withinCollection}-${this.searchType}`;
1959
- }
1960
-
1961
- // this maps the query to the pages being fetched for that query
1962
- private pageFetchesInProgress: Record<string, Set<number>> = {};
1963
-
1964
- /**
1965
- * Fetches one or more pages of results and updates the data source.
1966
- *
1967
- * @param pageNumber The page number to fetch
1968
- * @param numInitialPages If this is an initial page fetch (`pageNumber = 1`),
1969
- * specifies how many pages to batch together in one request. Ignored
1970
- * if `pageNumber != 1`, defaulting to a single page.
1971
- */
1972
- async fetchPage(pageNumber: number, numInitialPages = 1) {
1973
- const trimmedQuery = this.baseQuery?.trim();
1974
- if (!this.canPerformSearch) return;
1975
-
1976
- // if we already have data, don't fetch again
1977
- if (this.dataSource[pageNumber]) return;
1978
-
1979
- if (this.endOfDataReached) return;
1980
-
1981
- // Batch multiple initial page requests together if needed (e.g., can request
1982
- // pages 1 and 2 together in a single request).
1983
- const numPages = pageNumber === 1 ? numInitialPages : 1;
1984
- const numRows = this.pageSize * numPages;
1985
-
1986
- // if a fetch is already in progress for this query and page, don't fetch again
1987
- const { pageFetchQueryKey } = this;
1988
- const pageFetches =
1989
- this.pageFetchesInProgress[pageFetchQueryKey] ?? new Set();
1990
- if (pageFetches.has(pageNumber)) return;
1991
- for (let i = 0; i < numPages; i += 1) {
1992
- pageFetches.add(pageNumber + i);
1993
- }
1994
- this.pageFetchesInProgress[pageFetchQueryKey] = pageFetches;
1995
-
1996
- const sortParams = this.sortParam ? [this.sortParam] : [];
1997
- const params: SearchParams = {
1998
- ...this.collectionParams,
1999
- query: trimmedQuery || '',
2000
- page: pageNumber,
2001
- rows: numRows,
2002
- sort: sortParams,
2003
- filters: this.filterMap,
2004
- aggregations: { omit: true },
2005
- };
2006
- params.uid = await this.requestUID(params, 'hits');
2007
-
2008
- const searchResponse = await this.searchService?.search(
2009
- params,
2010
- this.searchType
2011
- );
2012
- const success = searchResponse?.success;
2013
-
2014
- // This is checking to see if the query has changed since the data was fetched.
2015
- // If so, we just want to discard the data since there should be a new query
2016
- // right behind it.
2017
- const queryChangedSinceFetch = pageFetchQueryKey !== this.pageFetchQueryKey;
2018
- if (queryChangedSinceFetch) return;
2019
-
2020
- if (!success) {
2021
- const errorMsg = searchResponse?.error?.message;
2022
- const detailMsg = searchResponse?.error?.details?.message;
2023
-
2024
- this.queryErrorMessage = `${errorMsg ?? ''}${
2025
- detailMsg ? `; ${detailMsg}` : ''
2026
- }`;
2027
-
2028
- if (!this.queryErrorMessage) {
2029
- this.queryErrorMessage = 'Missing or malformed response from backend';
2030
- // @ts-ignore: Property 'Sentry' does not exist on type 'Window & typeof globalThis'
2031
- window?.Sentry?.captureMessage?.(this.queryErrorMessage, 'error');
2032
- }
2033
-
2034
- for (let i = 0; i < numPages; i += 1) {
2035
- this.pageFetchesInProgress[pageFetchQueryKey]?.delete(pageNumber + i);
2036
- }
2037
-
2038
- this.searchResultsLoading = false;
2039
- return;
2040
- }
2041
-
2042
- this.totalResults = success.response.totalResults - this.tileModelOffset;
2043
-
2044
- // display event to offshoot when result count is zero.
2045
- if (this.totalResults === 0) {
2046
- this.emitEmptyResults();
2047
- }
2048
-
2049
- if (this.withinCollection) {
2050
- this.collectionInfo = success.response.collectionExtraInfo;
2051
-
2052
- // For collections, we want the UI to respect the default sort option
2053
- // which can be specified in metadata, or otherwise assumed to be week:desc
2054
- this.applyDefaultCollectionSort(this.collectionInfo);
2055
-
2056
- if (this.collectionInfo) {
2057
- this.parentCollections = [].concat(
2058
- this.collectionInfo.public_metadata?.collection ?? []
2059
- );
2060
- }
2061
- }
2062
-
2063
- const { results, collectionTitles } = success.response;
2064
- if (results && results.length > 0) {
2065
- // Load any collection titles present on the response into the cache,
2066
- // or queue up preload fetches for them if none were present.
2067
- if (collectionTitles) {
2068
- this.collectionNameCache?.addKnownTitles(collectionTitles);
2069
- } else {
2070
- this.preloadCollectionNames(results);
2071
- }
2072
-
2073
- // Update the data source for each returned page
2074
- for (let i = 0; i < numPages; i += 1) {
2075
- const pageStartIndex = this.pageSize * i;
2076
- this.updateDataSource(
2077
- pageNumber + i,
2078
- results.slice(pageStartIndex, pageStartIndex + this.pageSize)
2079
- );
2080
- }
2081
- }
2082
-
2083
- // When we reach the end of the data, we can set the infinite scroller's
2084
- // item count to the real total number of results (rather than the
2085
- // temporary estimates based on pages rendered so far).
2086
- const resultCountDiscrepancy = numRows - results.length;
2087
- if (resultCountDiscrepancy > 0) {
2088
- this.endOfDataReached = true;
2089
- if (this.infiniteScroller) {
2090
- this.infiniteScroller.itemCount = this.totalResults;
2091
- }
2092
- }
2093
-
2094
- for (let i = 0; i < numPages; i += 1) {
2095
- this.pageFetchesInProgress[pageFetchQueryKey]?.delete(pageNumber + i);
1499
+ setTotalResultCount(count: number): void {
1500
+ if (this.infiniteScroller) {
1501
+ this.infiniteScroller.itemCount = count;
2096
1502
  }
2097
1503
  }
2098
1504
 
2099
- private preloadCollectionNames(results: SearchResult[]) {
2100
- const collectionIds = results
2101
- .map(result => result.collection?.values)
2102
- .flat();
2103
- const collectionIdsArray = Array.from(new Set(collectionIds)) as string[];
2104
- this.collectionNameCache?.preloadIdentifiers(collectionIdsArray);
2105
- }
2106
-
2107
1505
  /**
2108
1506
  * Applies any default sort option for the current collection, by checking
2109
1507
  * for one in the collection's metadata. If none is found, defaults to sorting
@@ -2111,7 +1509,7 @@ export class CollectionBrowser
2111
1509
  * - Date Favorited for fav-* collections
2112
1510
  * - Weekly views for all other collections
2113
1511
  */
2114
- private applyDefaultCollectionSort(collectionInfo?: CollectionExtraInfo) {
1512
+ applyDefaultCollectionSort(collectionInfo?: CollectionExtraInfo) {
2115
1513
  if (this.baseQuery) {
2116
1514
  // If there's a query set, then we default to relevance sorting regardless of
2117
1515
  // the collection metadata-specified sort.
@@ -2161,7 +1559,7 @@ export class CollectionBrowser
2161
1559
  * When the fetch completes, we need to reload the scroller if the cells for that
2162
1560
  * page are visible, but if the page is not currenlty visible, we don't need to reload
2163
1561
  */
2164
- private get currentVisiblePageNumbers(): number[] {
1562
+ get currentVisiblePageNumbers(): number[] {
2165
1563
  const visibleCells = this.infiniteScroller?.getVisibleCellIndices() ?? [];
2166
1564
  const visiblePages = new Set<number>();
2167
1565
  visibleCells.forEach(cellIndex => {
@@ -2172,169 +1570,10 @@ export class CollectionBrowser
2172
1570
  }
2173
1571
 
2174
1572
  /**
2175
- * Update the datasource from the fetch response
2176
- *
2177
- * @param pageNumber
2178
- * @param results
2179
- */
2180
- private updateDataSource(pageNumber: number, results: SearchResult[]) {
2181
- // copy our existing datasource so when we set it below, it gets set
2182
- // instead of modifying the existing dataSource since object changes
2183
- // don't trigger a re-render
2184
- const datasource = { ...this.dataSource };
2185
- const tiles: TileModel[] = [];
2186
- results?.forEach(result => {
2187
- if (!result.identifier) return;
2188
-
2189
- let loginRequired = false;
2190
- let contentWarning = false;
2191
- // Check if item and item in "modifying" collection, setting above flags
2192
- if (
2193
- result.collection?.values.length &&
2194
- result.mediatype?.value !== 'collection'
2195
- ) {
2196
- for (const collection of result.collection?.values ?? []) {
2197
- if (collection === 'loggedin') {
2198
- loginRequired = true;
2199
- if (contentWarning) break;
2200
- }
2201
- if (collection === 'no-preview') {
2202
- contentWarning = true;
2203
- if (loginRequired) break;
2204
- }
2205
- }
2206
- }
2207
-
2208
- tiles.push({
2209
- averageRating: result.avg_rating?.value,
2210
- checked: false,
2211
- collections: result.collection?.values ?? [],
2212
- collectionFilesCount: result.collection_files_count?.value ?? 0,
2213
- collectionSize: result.collection_size?.value ?? 0,
2214
- commentCount: result.num_reviews?.value ?? 0,
2215
- creator: result.creator?.value,
2216
- creators: result.creator?.values ?? [],
2217
- dateAdded: result.addeddate?.value,
2218
- dateArchived: result.publicdate?.value,
2219
- datePublished: result.date?.value,
2220
- dateReviewed: result.reviewdate?.value,
2221
- description: result.description?.values.join('\n'),
2222
- favCount: result.num_favorites?.value ?? 0,
2223
- href: this.collapseRepeatedQuotes(result.__href__?.value),
2224
- identifier: result.identifier,
2225
- issue: result.issue?.value,
2226
- itemCount: result.item_count?.value ?? 0,
2227
- mediatype: this.getMediatype(result),
2228
- snippets: result.highlight?.values ?? [],
2229
- source: result.source?.value,
2230
- subjects: result.subject?.values ?? [],
2231
- title: result.title?.value ?? '',
2232
- volume: result.volume?.value,
2233
- viewCount: result.downloads?.value ?? 0,
2234
- weeklyViewCount: result.week?.value,
2235
- loginRequired,
2236
- contentWarning,
2237
- });
2238
- });
2239
- datasource[pageNumber] = tiles;
2240
- this.dataSource = datasource;
2241
- const visiblePages = this.currentVisiblePageNumbers;
2242
- const needsReload = visiblePages.includes(pageNumber);
2243
- if (needsReload) {
2244
- this.infiniteScroller?.refreshAllVisibleCells();
2245
- }
2246
- }
2247
-
2248
- private getMediatype(result: SearchResult) {
2249
- /**
2250
- * hit_type == 'favorited_search' is basically a new hit_type
2251
- * - we are getting from PPS.
2252
- * - which gives response for fav- collection
2253
- * - having favorited items like account/collection/item etc..
2254
- * - as user can also favorite a search result (a search page)
2255
- * - so we need to have response (having fav- items and fav- search results)
2256
- *
2257
- * if backend hit_type == 'favorited_search'
2258
- * - let's assume a "search" as new mediatype
2259
- */
2260
- if (result?.rawMetadata?.hit_type === 'favorited_search') {
2261
- return 'search';
2262
- }
2263
-
2264
- return result.mediatype?.value ?? 'data';
2265
- }
2266
-
2267
- /**
2268
- * Returns the input string, but removing one set of quotes from all instances of
2269
- * ""clauses wrapped in two sets of quotes"". This assumes the quotes are already
2270
- * URL-encoded.
2271
- *
2272
- * This should be a temporary measure to address the fact that the __href__ field
2273
- * sometimes acquires extra quotation marks during query rewriting. Once there is a
2274
- * full Lucene parser in place that handles quoted queries correctly, this can likely
2275
- * be removed.
1573
+ * Refreshes all visible result cells in the infinite scroller.
2276
1574
  */
2277
- private collapseRepeatedQuotes(str?: string): string | undefined {
2278
- return str?.replace(/%22%22(?!%22%22)(.+?)%22%22/g, '%22$1%22');
2279
- }
2280
-
2281
- /** Fetches the aggregation buckets for the given prefix filter type. */
2282
- private async fetchPrefixFilterBuckets(
2283
- filterType: PrefixFilterType
2284
- ): Promise<Bucket[]> {
2285
- const trimmedQuery = this.baseQuery?.trim();
2286
- if (!this.canPerformSearch) return [];
2287
-
2288
- const filterAggregationKey = prefixFilterAggregationKeys[filterType];
2289
- const sortParams = this.sortParam ? [this.sortParam] : [];
2290
-
2291
- const params: SearchParams = {
2292
- ...this.collectionParams,
2293
- query: trimmedQuery || '',
2294
- rows: 0,
2295
- filters: this.filterMap,
2296
- // Only fetch the firstTitle or firstCreator aggregation
2297
- aggregations: { simpleParams: [filterAggregationKey] },
2298
- // Fetch all 26 letter buckets
2299
- aggregationsSize: 26,
2300
- };
2301
- params.uid = await this.requestUID(
2302
- { ...params, sort: sortParams },
2303
- 'aggregations'
2304
- );
2305
-
2306
- const searchResponse = await this.searchService?.search(
2307
- params,
2308
- this.searchType
2309
- );
2310
-
2311
- return (searchResponse?.success?.response?.aggregations?.[
2312
- filterAggregationKey
2313
- ]?.buckets ?? []) as Bucket[];
2314
- }
2315
-
2316
- /** Fetches and caches the prefix filter counts for the given filter type. */
2317
- private async updatePrefixFilterCounts(
2318
- filterType: PrefixFilterType
2319
- ): Promise<void> {
2320
- const { facetFetchQueryKey } = this;
2321
- const buckets = await this.fetchPrefixFilterBuckets(filterType);
2322
-
2323
- // Don't update the filter counts for an outdated query (if it has been changed
2324
- // since we sent the request)
2325
- const queryChangedSinceFetch =
2326
- facetFetchQueryKey !== this.facetFetchQueryKey;
2327
- if (queryChangedSinceFetch) return;
2328
-
2329
- // Unpack the aggregation buckets into a simple map like { 'A': 50, 'B': 25, ... }
2330
- this.prefixFilterCountMap = { ...this.prefixFilterCountMap }; // Clone the object to trigger an update
2331
- this.prefixFilterCountMap[filterType] = buckets.reduce(
2332
- (acc: Record<string, number>, bucket: Bucket) => {
2333
- acc[(bucket.key as string).toUpperCase()] = bucket.doc_count;
2334
- return acc;
2335
- },
2336
- {}
2337
- );
1575
+ refreshVisibleResults(): void {
1576
+ this.infiniteScroller?.refreshAllVisibleCells();
2338
1577
  }
2339
1578
 
2340
1579
  /**
@@ -2345,7 +1584,7 @@ export class CollectionBrowser
2345
1584
  if (['title', 'creator'].includes(this.selectedSort)) {
2346
1585
  const filterType = this.selectedSort as PrefixFilterType;
2347
1586
  if (!this.prefixFilterCountMap[filterType]) {
2348
- this.updatePrefixFilterCounts(filterType);
1587
+ this.dataSource.updatePrefixFilterCounts(filterType);
2349
1588
  }
2350
1589
  }
2351
1590
  }
@@ -2403,7 +1642,7 @@ export class CollectionBrowser
2403
1642
  .model=${model}
2404
1643
  .tileDisplayMode=${this.displayMode}
2405
1644
  .resizeObserver=${this.resizeObserver}
2406
- .collectionNameCache=${this.collectionNameCache}
1645
+ .collectionTitles=${this.dataSource.collectionTitles}
2407
1646
  .sortParam=${this.sortParam}
2408
1647
  .defaultSortParam=${this.defaultSortParam}
2409
1648
  .creatorFilter=${this.selectedCreatorFilter}
@@ -2424,7 +1663,7 @@ export class CollectionBrowser
2424
1663
  private scrollThresholdReached() {
2425
1664
  if (!this.endOfDataReached) {
2426
1665
  this.pagesToRender += 1;
2427
- this.fetchPage(this.pagesToRender);
1666
+ this.dataSource.fetchPage(this.pagesToRender);
2428
1667
  }
2429
1668
  }
2430
1669
 
@@ -2596,8 +1835,7 @@ export class CollectionBrowser
2596
1835
  }
2597
1836
 
2598
1837
  .facets-message {
2599
- text-align: center;
2600
- font-size: 1.2rem;
1838
+ font-size: 1.4rem;
2601
1839
  }
2602
1840
 
2603
1841
  .desktop #left-column-scroll-sentinel {