@internetarchive/collection-browser 3.0.0 → 3.0.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 (60) hide show
  1. package/dist/src/collection-browser.js +680 -680
  2. package/dist/src/collection-browser.js.map +1 -1
  3. package/dist/src/collection-facets/facet-row.js +130 -130
  4. package/dist/src/collection-facets/facet-row.js.map +1 -1
  5. package/dist/src/collection-facets/models.d.ts +9 -0
  6. package/dist/src/collection-facets/models.js +10 -0
  7. package/dist/src/collection-facets/models.js.map +1 -0
  8. package/dist/src/collection-facets/more-facets-content.js +121 -120
  9. package/dist/src/collection-facets/more-facets-content.js.map +1 -1
  10. package/dist/src/collection-facets/smart-facets/smart-facet-bar.js +75 -75
  11. package/dist/src/collection-facets/smart-facets/smart-facet-bar.js.map +1 -1
  12. package/dist/src/collection-facets.js +263 -263
  13. package/dist/src/collection-facets.js.map +1 -1
  14. package/dist/src/data-source/collection-browser-data-source.js.map +1 -1
  15. package/dist/src/data-source/collection-browser-query-state.js.map +1 -1
  16. package/dist/src/data-source/models.js.map +1 -1
  17. package/dist/src/models.js.map +1 -1
  18. package/dist/src/restoration-state-handler.js.map +1 -1
  19. package/dist/src/tiles/base-tile-component.js.map +1 -1
  20. package/dist/src/tiles/grid/item-tile.js +139 -139
  21. package/dist/src/tiles/grid/item-tile.js.map +1 -1
  22. package/dist/src/tiles/hover/hover-pane-controller.js +21 -21
  23. package/dist/src/tiles/hover/hover-pane-controller.js.map +1 -1
  24. package/dist/src/tiles/hover/tile-hover-pane.js +108 -108
  25. package/dist/src/tiles/hover/tile-hover-pane.js.map +1 -1
  26. package/dist/src/tiles/list/tile-list-compact-header.js +45 -45
  27. package/dist/src/tiles/list/tile-list-compact-header.js.map +1 -1
  28. package/dist/src/tiles/list/tile-list-compact.js +97 -97
  29. package/dist/src/tiles/list/tile-list-compact.js.map +1 -1
  30. package/dist/src/tiles/list/tile-list.js +289 -289
  31. package/dist/src/tiles/list/tile-list.js.map +1 -1
  32. package/dist/src/tiles/tile-dispatcher.js +200 -200
  33. package/dist/src/tiles/tile-dispatcher.js.map +1 -1
  34. package/dist/src/tiles/tile-display-value-provider.js.map +1 -1
  35. package/dist/test/collection-browser.test.js +183 -183
  36. package/dist/test/collection-browser.test.js.map +1 -1
  37. package/dist/test/restoration-state-handler.test.js.map +1 -1
  38. package/package.json +1 -1
  39. package/src/collection-browser.ts +2775 -2775
  40. package/src/collection-facets/facet-row.ts +282 -282
  41. package/src/collection-facets/models.ts +10 -0
  42. package/src/collection-facets/more-facets-content.ts +636 -632
  43. package/src/collection-facets/smart-facets/smart-facet-bar.ts +437 -437
  44. package/src/collection-facets.ts +990 -990
  45. package/src/data-source/collection-browser-data-source.ts +1390 -1390
  46. package/src/data-source/collection-browser-query-state.ts +63 -63
  47. package/src/data-source/models.ts +43 -43
  48. package/src/models.ts +870 -870
  49. package/src/restoration-state-handler.ts +544 -544
  50. package/src/tiles/base-tile-component.ts +53 -53
  51. package/src/tiles/grid/item-tile.ts +339 -339
  52. package/src/tiles/hover/hover-pane-controller.ts +517 -517
  53. package/src/tiles/hover/tile-hover-pane.ts +180 -180
  54. package/src/tiles/list/tile-list-compact-header.ts +86 -86
  55. package/src/tiles/list/tile-list-compact.ts +236 -236
  56. package/src/tiles/list/tile-list.ts +688 -688
  57. package/src/tiles/tile-dispatcher.ts +486 -486
  58. package/src/tiles/tile-display-value-provider.ts +124 -124
  59. package/test/collection-browser.test.ts +2340 -2340
  60. package/test/restoration-state-handler.test.ts +510 -510
@@ -1,632 +1,636 @@
1
- import {
2
- css,
3
- CSSResultGroup,
4
- html,
5
- LitElement,
6
- nothing,
7
- PropertyValues,
8
- TemplateResult,
9
- } from 'lit';
10
- import { customElement, property, state } from 'lit/decorators.js';
11
- import {
12
- Aggregation,
13
- Bucket,
14
- SearchServiceInterface,
15
- SearchParams,
16
- SearchType,
17
- AggregationSortType,
18
- FilterMap,
19
- PageType,
20
- } from '@internetarchive/search-service';
21
- import type { ModalManagerInterface } from '@internetarchive/modal-manager';
22
- import type { AnalyticsManagerInterface } from '@internetarchive/analytics-manager';
23
- import { msg } from '@lit/localize';
24
- import {
25
- SelectedFacets,
26
- FacetGroup,
27
- FacetBucket,
28
- FacetOption,
29
- facetTitles,
30
- suppressedCollections,
31
- valueFacetSort,
32
- defaultFacetSort,
33
- getDefaultSelectedFacets,
34
- FacetEventDetails,
35
- } from '../models';
36
- import type {
37
- CollectionTitles,
38
- PageSpecifierParams,
39
- TVChannelAliases,
40
- } from '../data-source/models';
41
- import '@internetarchive/ia-activity-indicator';
42
- import './more-facets-pagination';
43
- import './facets-template';
44
- import {
45
- analyticsActions,
46
- analyticsCategories,
47
- } from '../utils/analytics-events';
48
- import './toggle-switch';
49
- import { srOnlyStyle } from '../styles/sr-only';
50
- import {
51
- mergeSelectedFacets,
52
- sortBucketsBySelectionState,
53
- updateSelectedFacetBucket,
54
- } from '../utils/facet-utils';
55
-
56
- @customElement('more-facets-content')
57
- export class MoreFacetsContent extends LitElement {
58
- @property({ type: String }) facetKey?: FacetOption;
59
-
60
- @property({ type: String }) query?: string;
61
-
62
- @property({ type: Object }) filterMap?: FilterMap;
63
-
64
- @property({ type: Number }) searchType?: SearchType;
65
-
66
- @property({ type: Object }) pageSpecifierParams?: PageSpecifierParams;
67
-
68
- @property({ type: Object })
69
- collectionTitles?: CollectionTitles;
70
-
71
- @property({ type: Object })
72
- tvChannelAliases?: TVChannelAliases;
73
-
74
- /**
75
- * Maximum number of facets to show per page within the modal.
76
- */
77
- @property({ type: Number }) facetsPerPage = 35;
78
-
79
- /**
80
- * Whether we are waiting for facet data to load.
81
- * We begin with this set to true so that we show an initial loading indicator.
82
- */
83
- @property({ type: Boolean }) facetsLoading = true;
84
-
85
- /**
86
- * The set of pre-existing facet selections (including both selected & negated facets).
87
- */
88
- @property({ type: Object }) selectedFacets?: SelectedFacets;
89
-
90
- @property({ type: Number }) sortedBy: AggregationSortType =
91
- AggregationSortType.COUNT;
92
-
93
- @property({ type: Boolean }) isTvSearch = false;
94
-
95
- @property({ type: Object }) modalManager?: ModalManagerInterface;
96
-
97
- @property({ type: Object }) searchService?: SearchServiceInterface;
98
-
99
- @property({ type: Object, attribute: false })
100
- analyticsHandler?: AnalyticsManagerInterface;
101
-
102
- /**
103
- * The full set of aggregations received from the search service
104
- */
105
- @state() private aggregations?: Record<string, Aggregation>;
106
-
107
- /**
108
- * A FacetGroup storing the full set of facet buckets to be shown on the dialog.
109
- */
110
- @state() private facetGroup?: FacetGroup;
111
-
112
- /**
113
- * An object holding any changes the patron has made to their facet selections
114
- * within the modal dialog but which they have not yet applied. These are
115
- * eventually merged into the existing `selectedFacets` when the patron applies
116
- * their changes, or discarded if they cancel/close the dialog.
117
- */
118
- @state() private unappliedFacetChanges: SelectedFacets =
119
- getDefaultSelectedFacets();
120
-
121
- /**
122
- * Which page of facets we are showing.
123
- */
124
- @state() private pageNumber = 1;
125
-
126
- willUpdate(changed: PropertyValues): void {
127
- if (
128
- changed.has('aggregations') ||
129
- changed.has('facetsPerPage') ||
130
- changed.has('sortedBy') ||
131
- changed.has('selectedFacets') ||
132
- changed.has('unappliedFacetChanges')
133
- ) {
134
- // Convert the merged selected facets & aggregations into a facet group, and
135
- // store it for reuse across pages.
136
- this.facetGroup = this.mergedFacets;
137
- }
138
- }
139
-
140
- updated(changed: PropertyValues): void {
141
- // If any of the search properties change, it triggers a facet fetch
142
- if (
143
- changed.has('facetKey') ||
144
- changed.has('query') ||
145
- changed.has('searchType') ||
146
- changed.has('filterMap')
147
- ) {
148
- this.facetsLoading = true;
149
- this.pageNumber = 1;
150
- this.sortedBy = defaultFacetSort[this.facetKey as FacetOption];
151
-
152
- this.updateSpecificFacets();
153
- }
154
- }
155
-
156
- firstUpdated(): void {
157
- this.setupEscapeListeners();
158
- }
159
-
160
- /**
161
- * Close more facets modal on Escape click
162
- */
163
- private setupEscapeListeners() {
164
- if (this.modalManager) {
165
- document.addEventListener('keydown', (e: KeyboardEvent) => {
166
- if (e.key === 'Escape') {
167
- this.modalManager?.closeModal();
168
- }
169
- });
170
- } else {
171
- document.removeEventListener('keydown', () => {});
172
- }
173
- }
174
-
175
- /**
176
- * Whether facet requests are for the search_results page type (either defaulted or explicitly).
177
- */
178
- private get isSearchResultsPage(): boolean {
179
- // Default page type is search_results when none is specified, so we check
180
- // for undefined as well.
181
- const pageType: PageType | undefined = this.pageSpecifierParams?.pageType;
182
- return pageType === undefined || pageType === 'search_results';
183
- }
184
-
185
- /**
186
- * Get specific facets data from search-service API based of currently query params
187
- * - this.aggregations - hold result of search service and being used for further processing.
188
- */
189
- async updateSpecificFacets(): Promise<void> {
190
- if (!this.facetKey) return; // Can't fetch facets if we don't know what type of facets we need!
191
-
192
- const trimmedQuery = this.query?.trim();
193
- if (!trimmedQuery && this.isSearchResultsPage) return; // The search page _requires_ a query
194
-
195
- const aggregations = {
196
- simpleParams: [this.facetKey],
197
- };
198
- const aggregationsSize = 65535; // todo - do we want to have all the records at once?
199
-
200
- const params: SearchParams = {
201
- ...this.pageSpecifierParams,
202
- query: trimmedQuery || '',
203
- filters: this.filterMap,
204
- aggregations,
205
- aggregationsSize,
206
- rows: 0, // todo - do we want server-side pagination with offset/page/limit flag?
207
- };
208
-
209
- const results = await this.searchService?.search(params, this.searchType);
210
- this.aggregations = results?.success?.response.aggregations;
211
- this.facetsLoading = false;
212
-
213
- const collectionTitles = results?.success?.response?.collectionTitles;
214
- if (collectionTitles) {
215
- for (const [id, title] of Object.entries(collectionTitles)) {
216
- this.collectionTitles?.set(id, title);
217
- }
218
- }
219
- }
220
-
221
- /**
222
- * Handler for page number changes from the pagination widget.
223
- */
224
- private pageNumberClicked(e: CustomEvent<{ page: number }>) {
225
- const page = e?.detail?.page;
226
- if (page) {
227
- this.pageNumber = Number(page);
228
- }
229
-
230
- this.analyticsHandler?.sendEvent({
231
- category: analyticsCategories.default,
232
- action: analyticsActions.moreFacetsPageChange,
233
- label: `${this.pageNumber}`,
234
- });
235
- }
236
-
237
- /**
238
- * Combines the selected facets with the aggregations to create a single list of facets
239
- */
240
- private get mergedFacets(): FacetGroup | undefined {
241
- if (!this.facetKey || !this.selectedFacets) return undefined;
242
-
243
- const { selectedFacetGroup, aggregationFacetGroup } = this;
244
-
245
- // If we don't have any aggregations, then there is nothing to show yet
246
- if (!aggregationFacetGroup) return undefined;
247
-
248
- // Start with either the selected group if we have one, or the aggregate group otherwise
249
- const facetGroup = { ...(selectedFacetGroup ?? aggregationFacetGroup) };
250
-
251
- // Attach the counts to the selected buckets
252
- const bucketsWithCount =
253
- selectedFacetGroup?.buckets.map(bucket => {
254
- const selectedBucket = aggregationFacetGroup.buckets.find(
255
- b => b.key === bucket.key,
256
- );
257
- return selectedBucket
258
- ? {
259
- ...bucket,
260
- count: selectedBucket.count,
261
- }
262
- : bucket;
263
- }) ?? [];
264
-
265
- // Sort the buckets by selection state
266
- // We do this *prior* to considering unapplied selections, because we want the facets
267
- // to remain in position when they are selected/unselected, rather than re-sort themselves.
268
- sortBucketsBySelectionState(bucketsWithCount, this.sortedBy);
269
-
270
- // Append any additional buckets that were not selected
271
- aggregationFacetGroup.buckets.forEach(bucket => {
272
- const existingBucket = selectedFacetGroup?.buckets.find(
273
- b => b.key === bucket.key,
274
- );
275
- if (existingBucket) return;
276
- bucketsWithCount.push(bucket);
277
- });
278
-
279
- // Apply any unapplied selections that appear on this page
280
- const unappliedBuckets = this.unappliedFacetChanges[this.facetKey];
281
- for (const [index, bucket] of bucketsWithCount.entries()) {
282
- const unappliedBucket = unappliedBuckets?.[bucket.key];
283
- if (unappliedBucket) {
284
- bucketsWithCount[index] = { ...unappliedBucket };
285
- }
286
- }
287
-
288
- // For TV creator facets, uppercase the display text
289
- if (this.facetKey === 'creator' && this.isTvSearch) {
290
- bucketsWithCount.forEach(b => {
291
- b.displayText = (b.displayText ?? b.key)?.toLocaleUpperCase();
292
-
293
- const channelLabel = this.tvChannelAliases?.get(b.displayText);
294
- if (channelLabel && channelLabel !== b.displayText) {
295
- b.extraNote = `(${channelLabel})`;
296
- }
297
- });
298
- }
299
-
300
- facetGroup.buckets = bucketsWithCount;
301
- return facetGroup;
302
- }
303
-
304
- /**
305
- * Converts the selected facets for the current facet key to a `FacetGroup`,
306
- * which is easier to work with.
307
- */
308
- private get selectedFacetGroup(): FacetGroup | undefined {
309
- if (!this.selectedFacets || !this.facetKey) return undefined;
310
-
311
- const selectedFacetsForKey = this.selectedFacets[this.facetKey];
312
- if (!selectedFacetsForKey) return undefined;
313
-
314
- const facetGroupTitle = facetTitles[this.facetKey];
315
-
316
- const buckets: FacetBucket[] = Object.entries(selectedFacetsForKey).map(
317
- ([value, data]) => {
318
- const displayText: string = value;
319
- return {
320
- displayText,
321
- key: value,
322
- count: data?.count,
323
- state: data?.state,
324
- };
325
- },
326
- );
327
-
328
- return {
329
- title: facetGroupTitle,
330
- key: this.facetKey,
331
- buckets,
332
- };
333
- }
334
-
335
- /**
336
- * Converts the raw `aggregations` for the current facet key to a `FacetGroup`,
337
- * which is easier to work with.
338
- */
339
- private get aggregationFacetGroup(): FacetGroup | undefined {
340
- if (!this.aggregations || !this.facetKey) return undefined;
341
-
342
- const currentAggregation = this.aggregations[this.facetKey];
343
- if (!currentAggregation) return undefined;
344
-
345
- const facetGroupTitle = facetTitles[this.facetKey];
346
-
347
- // Order the facets according to the current sort option
348
- let sortedBuckets = currentAggregation.getSortedBuckets(
349
- this.sortedBy,
350
- ) as Bucket[];
351
-
352
- if (this.facetKey === 'collection') {
353
- // we are not showing fav- collections or certain deemphasized collections in facets
354
- sortedBuckets = sortedBuckets?.filter(bucket => {
355
- const bucketKey = bucket?.key?.toString();
356
- return (
357
- !suppressedCollections[bucketKey] && !bucketKey?.startsWith('fav-')
358
- );
359
- });
360
- }
361
-
362
- // Construct the array of facet buckets from the aggregation buckets
363
- const facetBuckets: FacetBucket[] = sortedBuckets.map(bucket => {
364
- const bucketKeyStr = `${bucket.key}`;
365
- return {
366
- displayText: `${bucketKeyStr}`,
367
- key: `${bucketKeyStr}`,
368
- count: bucket.doc_count,
369
- state: 'none',
370
- };
371
- });
372
-
373
- return {
374
- title: facetGroupTitle,
375
- key: this.facetKey,
376
- buckets: facetBuckets,
377
- };
378
- }
379
-
380
- /**
381
- * Returns a FacetGroup representing only the current page of facet buckets to show.
382
- */
383
- private get facetGroupForCurrentPage(): FacetGroup | undefined {
384
- const { facetGroup } = this;
385
- if (!facetGroup) return undefined;
386
-
387
- // Slice out only the current page of facet buckets
388
- const firstBucketIndexOnPage = (this.pageNumber - 1) * this.facetsPerPage;
389
- const truncatedBuckets = facetGroup.buckets.slice(
390
- firstBucketIndexOnPage,
391
- firstBucketIndexOnPage + this.facetsPerPage,
392
- );
393
-
394
- return {
395
- ...facetGroup,
396
- buckets: truncatedBuckets,
397
- };
398
- }
399
-
400
- private get moreFacetsTemplate(): TemplateResult {
401
- return html`
402
- <facets-template
403
- .facetGroup=${this.facetGroupForCurrentPage}
404
- .selectedFacets=${this.selectedFacets}
405
- .collectionTitles=${this.collectionTitles}
406
- @facetClick=${(e: CustomEvent<FacetEventDetails>) => {
407
- if (this.facetKey) {
408
- this.unappliedFacetChanges = updateSelectedFacetBucket(
409
- this.unappliedFacetChanges,
410
- this.facetKey,
411
- e.detail.bucket,
412
- );
413
- }
414
- }}
415
- ></facets-template>
416
- `;
417
- }
418
-
419
- private get loaderTemplate(): TemplateResult {
420
- return html`<div class="facets-loader">
421
- <ia-activity-indicator .mode=${'processing'}></ia-activity-indicator>
422
- </div> `;
423
- }
424
-
425
- /**
426
- * How many pages of facets to show in the modal pagination widget
427
- */
428
- private get paginationSize(): number {
429
- if (!this.aggregations || !this.facetKey) return 0;
430
-
431
- // Calculate the appropriate number of pages to show in the modal pagination widget
432
- const length = this.aggregations[this.facetKey]?.buckets.length;
433
- return Math.ceil(length / this.facetsPerPage);
434
- }
435
-
436
- // render pagination if more then 1 page
437
- private get facetsPaginationTemplate() {
438
- return this.paginationSize > 1
439
- ? html`<more-facets-pagination
440
- .size=${this.paginationSize}
441
- .currentPage=${1}
442
- @pageNumberClicked=${this.pageNumberClicked}
443
- ></more-facets-pagination>`
444
- : nothing;
445
- }
446
-
447
- private get footerTemplate() {
448
- if (this.paginationSize > 0) {
449
- return html`${this.facetsPaginationTemplate}
450
- <div class="footer">
451
- <button
452
- class="btn btn-cancel"
453
- type="button"
454
- @click=${this.cancelClick}
455
- >
456
- Cancel
457
- </button>
458
- <button
459
- class="btn btn-submit"
460
- type="button"
461
- @click=${this.applySearchFacetsClicked}
462
- >
463
- Apply filters
464
- </button>
465
- </div> `;
466
- }
467
-
468
- return nothing;
469
- }
470
-
471
- private sortFacetAggregation(facetSortType: AggregationSortType) {
472
- this.sortedBy = facetSortType;
473
- this.dispatchEvent(
474
- new CustomEvent('sortedFacets', { detail: this.sortedBy }),
475
- );
476
- }
477
-
478
- private get modalHeaderTemplate(): TemplateResult {
479
- const facetSort =
480
- this.sortedBy ?? defaultFacetSort[this.facetKey as FacetOption];
481
- const defaultSwitchSide =
482
- facetSort === AggregationSortType.COUNT ? 'left' : 'right';
483
-
484
- return html`<span class="sr-only">${msg('More facets for:')}</span>
485
- <span class="title">
486
- ${this.facetGroup?.title}
487
-
488
- <label class="sort-label">${msg('Sort by:')}</label>
489
- ${this.facetKey
490
- ? html`<toggle-switch
491
- class="sort-toggle"
492
- leftValue=${AggregationSortType.COUNT}
493
- leftLabel="Count"
494
- rightValue=${valueFacetSort[this.facetKey]}
495
- .rightLabel=${this.facetGroup?.title}
496
- side=${defaultSwitchSide}
497
- @change=${(e: CustomEvent<string>) => {
498
- this.sortFacetAggregation(
499
- Number(e.detail) as AggregationSortType,
500
- );
501
- }}
502
- ></toggle-switch>`
503
- : nothing}
504
- </span>`;
505
- }
506
-
507
- render() {
508
- return html`
509
- ${this.facetsLoading
510
- ? this.loaderTemplate
511
- : html`
512
- <section id="more-facets">
513
- <div class="header-content">${this.modalHeaderTemplate}</div>
514
- <div class="facets-content">${this.moreFacetsTemplate}</div>
515
- ${this.footerTemplate}
516
- </section>
517
- `}
518
- `;
519
- }
520
-
521
- private applySearchFacetsClicked() {
522
- const mergedSelections = mergeSelectedFacets(
523
- this.selectedFacets,
524
- this.unappliedFacetChanges,
525
- );
526
-
527
- const event = new CustomEvent<SelectedFacets>('facetsChanged', {
528
- detail: mergedSelections,
529
- bubbles: true,
530
- composed: true,
531
- });
532
- this.dispatchEvent(event);
533
-
534
- // Reset the unapplied changes back to default, now that they have been applied
535
- this.unappliedFacetChanges = getDefaultSelectedFacets();
536
-
537
- this.modalManager?.closeModal();
538
- this.analyticsHandler?.sendEvent({
539
- category: analyticsCategories.default,
540
- action: `${analyticsActions.applyMoreFacetsModal}`,
541
- label: `${this.facetKey}`,
542
- });
543
- }
544
-
545
- private cancelClick() {
546
- // Reset the unapplied changes back to default
547
- this.unappliedFacetChanges = getDefaultSelectedFacets();
548
-
549
- this.modalManager?.closeModal();
550
- this.analyticsHandler?.sendEvent({
551
- category: analyticsCategories.default,
552
- action: analyticsActions.closeMoreFacetsModal,
553
- label: `${this.facetKey}`,
554
- });
555
- }
556
-
557
- static get styles(): CSSResultGroup {
558
- const modalSubmitButton = css`var(--primaryButtonBGColor, #194880)`;
559
-
560
- return [
561
- srOnlyStyle,
562
- css`
563
- section#more-facets {
564
- overflow: auto;
565
- padding: 10px; /* leaves room for scroll bar to appear without overlaying on content */
566
- --facetsColumnCount: 3;
567
- }
568
- .header-content .title {
569
- display: block;
570
- text-align: left;
571
- font-size: 1.8rem;
572
- padding: 0 10px;
573
- font-weight: bold;
574
- }
575
-
576
- .sort-label {
577
- margin-left: 20px;
578
- font-size: 1.3rem;
579
- }
580
-
581
- .sort-toggle {
582
- font-weight: normal;
583
- }
584
-
585
- .facets-content {
586
- font-size: 1.2rem;
587
- max-height: 300px;
588
- overflow: auto;
589
- padding: 10px;
590
- }
591
- .facets-loader {
592
- margin-bottom: 20px;
593
- width: 70px;
594
- display: block;
595
- margin-left: auto;
596
- margin-right: auto;
597
- }
598
- .btn {
599
- border: none;
600
- padding: 10px;
601
- margin-bottom: 10px;
602
- width: auto;
603
- border-radius: 4px;
604
- cursor: pointer;
605
- }
606
- .btn-cancel {
607
- background-color: #2c2c2c;
608
- color: white;
609
- }
610
- .btn-submit {
611
- background-color: ${modalSubmitButton};
612
- color: white;
613
- }
614
- .footer {
615
- text-align: center;
616
- margin-top: 10px;
617
- }
618
-
619
- @media (max-width: 560px) {
620
- section#more-facets {
621
- max-height: 450px;
622
- --facetsColumnCount: 1;
623
- }
624
- .facets-content {
625
- overflow-y: auto;
626
- height: 300px;
627
- }
628
- }
629
- `,
630
- ];
631
- }
632
- }
1
+ import {
2
+ css,
3
+ CSSResultGroup,
4
+ html,
5
+ LitElement,
6
+ nothing,
7
+ PropertyValues,
8
+ TemplateResult,
9
+ } from 'lit';
10
+ import { customElement, property, state } from 'lit/decorators.js';
11
+ import {
12
+ Aggregation,
13
+ Bucket,
14
+ SearchServiceInterface,
15
+ SearchParams,
16
+ SearchType,
17
+ AggregationSortType,
18
+ FilterMap,
19
+ PageType,
20
+ } from '@internetarchive/search-service';
21
+ import type { ModalManagerInterface } from '@internetarchive/modal-manager';
22
+ import type { AnalyticsManagerInterface } from '@internetarchive/analytics-manager';
23
+ import { msg } from '@lit/localize';
24
+ import {
25
+ SelectedFacets,
26
+ FacetGroup,
27
+ FacetBucket,
28
+ FacetOption,
29
+ facetTitles,
30
+ suppressedCollections,
31
+ valueFacetSort,
32
+ defaultFacetSort,
33
+ getDefaultSelectedFacets,
34
+ FacetEventDetails,
35
+ } from '../models';
36
+ import type {
37
+ CollectionTitles,
38
+ PageSpecifierParams,
39
+ TVChannelAliases,
40
+ } from '../data-source/models';
41
+ import '@internetarchive/ia-activity-indicator';
42
+ import './more-facets-pagination';
43
+ import './facets-template';
44
+ import {
45
+ analyticsActions,
46
+ analyticsCategories,
47
+ } from '../utils/analytics-events';
48
+ import './toggle-switch';
49
+ import { srOnlyStyle } from '../styles/sr-only';
50
+ import {
51
+ mergeSelectedFacets,
52
+ sortBucketsBySelectionState,
53
+ updateSelectedFacetBucket,
54
+ } from '../utils/facet-utils';
55
+ import {
56
+ MORE_FACETS__DEFAULT_PAGE_SIZE,
57
+ MORE_FACETS__MAX_AGGREGATIONS,
58
+ } from './models';
59
+
60
+ @customElement('more-facets-content')
61
+ export class MoreFacetsContent extends LitElement {
62
+ @property({ type: String }) facetKey?: FacetOption;
63
+
64
+ @property({ type: String }) query?: string;
65
+
66
+ @property({ type: Object }) filterMap?: FilterMap;
67
+
68
+ @property({ type: Number }) searchType?: SearchType;
69
+
70
+ @property({ type: Object }) pageSpecifierParams?: PageSpecifierParams;
71
+
72
+ @property({ type: Object })
73
+ collectionTitles?: CollectionTitles;
74
+
75
+ @property({ type: Object })
76
+ tvChannelAliases?: TVChannelAliases;
77
+
78
+ /**
79
+ * Maximum number of facets to show per page within the modal.
80
+ */
81
+ @property({ type: Number }) facetsPerPage = MORE_FACETS__DEFAULT_PAGE_SIZE;
82
+
83
+ /**
84
+ * Whether we are waiting for facet data to load.
85
+ * We begin with this set to true so that we show an initial loading indicator.
86
+ */
87
+ @property({ type: Boolean }) facetsLoading = true;
88
+
89
+ /**
90
+ * The set of pre-existing facet selections (including both selected & negated facets).
91
+ */
92
+ @property({ type: Object }) selectedFacets?: SelectedFacets;
93
+
94
+ @property({ type: Number }) sortedBy: AggregationSortType =
95
+ AggregationSortType.COUNT;
96
+
97
+ @property({ type: Boolean }) isTvSearch = false;
98
+
99
+ @property({ type: Object }) modalManager?: ModalManagerInterface;
100
+
101
+ @property({ type: Object }) searchService?: SearchServiceInterface;
102
+
103
+ @property({ type: Object, attribute: false })
104
+ analyticsHandler?: AnalyticsManagerInterface;
105
+
106
+ /**
107
+ * The full set of aggregations received from the search service
108
+ */
109
+ @state() private aggregations?: Record<string, Aggregation>;
110
+
111
+ /**
112
+ * A FacetGroup storing the full set of facet buckets to be shown on the dialog.
113
+ */
114
+ @state() private facetGroup?: FacetGroup;
115
+
116
+ /**
117
+ * An object holding any changes the patron has made to their facet selections
118
+ * within the modal dialog but which they have not yet applied. These are
119
+ * eventually merged into the existing `selectedFacets` when the patron applies
120
+ * their changes, or discarded if they cancel/close the dialog.
121
+ */
122
+ @state() private unappliedFacetChanges: SelectedFacets =
123
+ getDefaultSelectedFacets();
124
+
125
+ /**
126
+ * Which page of facets we are showing.
127
+ */
128
+ @state() private pageNumber = 1;
129
+
130
+ willUpdate(changed: PropertyValues): void {
131
+ if (
132
+ changed.has('aggregations') ||
133
+ changed.has('facetsPerPage') ||
134
+ changed.has('sortedBy') ||
135
+ changed.has('selectedFacets') ||
136
+ changed.has('unappliedFacetChanges')
137
+ ) {
138
+ // Convert the merged selected facets & aggregations into a facet group, and
139
+ // store it for reuse across pages.
140
+ this.facetGroup = this.mergedFacets;
141
+ }
142
+ }
143
+
144
+ updated(changed: PropertyValues): void {
145
+ // If any of the search properties change, it triggers a facet fetch
146
+ if (
147
+ changed.has('facetKey') ||
148
+ changed.has('query') ||
149
+ changed.has('searchType') ||
150
+ changed.has('filterMap')
151
+ ) {
152
+ this.facetsLoading = true;
153
+ this.pageNumber = 1;
154
+ this.sortedBy = defaultFacetSort[this.facetKey as FacetOption];
155
+
156
+ this.updateSpecificFacets();
157
+ }
158
+ }
159
+
160
+ firstUpdated(): void {
161
+ this.setupEscapeListeners();
162
+ }
163
+
164
+ /**
165
+ * Close more facets modal on Escape click
166
+ */
167
+ private setupEscapeListeners() {
168
+ if (this.modalManager) {
169
+ document.addEventListener('keydown', (e: KeyboardEvent) => {
170
+ if (e.key === 'Escape') {
171
+ this.modalManager?.closeModal();
172
+ }
173
+ });
174
+ } else {
175
+ document.removeEventListener('keydown', () => {});
176
+ }
177
+ }
178
+
179
+ /**
180
+ * Whether facet requests are for the search_results page type (either defaulted or explicitly).
181
+ */
182
+ private get isSearchResultsPage(): boolean {
183
+ // Default page type is search_results when none is specified, so we check
184
+ // for undefined as well.
185
+ const pageType: PageType | undefined = this.pageSpecifierParams?.pageType;
186
+ return pageType === undefined || pageType === 'search_results';
187
+ }
188
+
189
+ /**
190
+ * Get specific facets data from search-service API based of currently query params
191
+ * - this.aggregations - hold result of search service and being used for further processing.
192
+ */
193
+ async updateSpecificFacets(): Promise<void> {
194
+ if (!this.facetKey) return; // Can't fetch facets if we don't know what type of facets we need!
195
+
196
+ const trimmedQuery = this.query?.trim();
197
+ if (!trimmedQuery && this.isSearchResultsPage) return; // The search page _requires_ a query
198
+
199
+ const aggregations = {
200
+ simpleParams: [this.facetKey],
201
+ };
202
+ const aggregationsSize = MORE_FACETS__MAX_AGGREGATIONS; // Only request the 10K highest-count facets
203
+
204
+ const params: SearchParams = {
205
+ ...this.pageSpecifierParams,
206
+ query: trimmedQuery || '',
207
+ filters: this.filterMap,
208
+ aggregations,
209
+ aggregationsSize,
210
+ rows: 0, // todo - do we want server-side pagination with offset/page/limit flag?
211
+ };
212
+
213
+ const results = await this.searchService?.search(params, this.searchType);
214
+ this.aggregations = results?.success?.response.aggregations;
215
+ this.facetsLoading = false;
216
+
217
+ const collectionTitles = results?.success?.response?.collectionTitles;
218
+ if (collectionTitles) {
219
+ for (const [id, title] of Object.entries(collectionTitles)) {
220
+ this.collectionTitles?.set(id, title);
221
+ }
222
+ }
223
+ }
224
+
225
+ /**
226
+ * Handler for page number changes from the pagination widget.
227
+ */
228
+ private pageNumberClicked(e: CustomEvent<{ page: number }>) {
229
+ const page = e?.detail?.page;
230
+ if (page) {
231
+ this.pageNumber = Number(page);
232
+ }
233
+
234
+ this.analyticsHandler?.sendEvent({
235
+ category: analyticsCategories.default,
236
+ action: analyticsActions.moreFacetsPageChange,
237
+ label: `${this.pageNumber}`,
238
+ });
239
+ }
240
+
241
+ /**
242
+ * Combines the selected facets with the aggregations to create a single list of facets
243
+ */
244
+ private get mergedFacets(): FacetGroup | undefined {
245
+ if (!this.facetKey || !this.selectedFacets) return undefined;
246
+
247
+ const { selectedFacetGroup, aggregationFacetGroup } = this;
248
+
249
+ // If we don't have any aggregations, then there is nothing to show yet
250
+ if (!aggregationFacetGroup) return undefined;
251
+
252
+ // Start with either the selected group if we have one, or the aggregate group otherwise
253
+ const facetGroup = { ...(selectedFacetGroup ?? aggregationFacetGroup) };
254
+
255
+ // Attach the counts to the selected buckets
256
+ const bucketsWithCount =
257
+ selectedFacetGroup?.buckets.map(bucket => {
258
+ const selectedBucket = aggregationFacetGroup.buckets.find(
259
+ b => b.key === bucket.key,
260
+ );
261
+ return selectedBucket
262
+ ? {
263
+ ...bucket,
264
+ count: selectedBucket.count,
265
+ }
266
+ : bucket;
267
+ }) ?? [];
268
+
269
+ // Sort the buckets by selection state
270
+ // We do this *prior* to considering unapplied selections, because we want the facets
271
+ // to remain in position when they are selected/unselected, rather than re-sort themselves.
272
+ sortBucketsBySelectionState(bucketsWithCount, this.sortedBy);
273
+
274
+ // Append any additional buckets that were not selected
275
+ aggregationFacetGroup.buckets.forEach(bucket => {
276
+ const existingBucket = selectedFacetGroup?.buckets.find(
277
+ b => b.key === bucket.key,
278
+ );
279
+ if (existingBucket) return;
280
+ bucketsWithCount.push(bucket);
281
+ });
282
+
283
+ // Apply any unapplied selections that appear on this page
284
+ const unappliedBuckets = this.unappliedFacetChanges[this.facetKey];
285
+ for (const [index, bucket] of bucketsWithCount.entries()) {
286
+ const unappliedBucket = unappliedBuckets?.[bucket.key];
287
+ if (unappliedBucket) {
288
+ bucketsWithCount[index] = { ...unappliedBucket };
289
+ }
290
+ }
291
+
292
+ // For TV creator facets, uppercase the display text
293
+ if (this.facetKey === 'creator' && this.isTvSearch) {
294
+ bucketsWithCount.forEach(b => {
295
+ b.displayText = (b.displayText ?? b.key)?.toLocaleUpperCase();
296
+
297
+ const channelLabel = this.tvChannelAliases?.get(b.displayText);
298
+ if (channelLabel && channelLabel !== b.displayText) {
299
+ b.extraNote = `(${channelLabel})`;
300
+ }
301
+ });
302
+ }
303
+
304
+ facetGroup.buckets = bucketsWithCount;
305
+ return facetGroup;
306
+ }
307
+
308
+ /**
309
+ * Converts the selected facets for the current facet key to a `FacetGroup`,
310
+ * which is easier to work with.
311
+ */
312
+ private get selectedFacetGroup(): FacetGroup | undefined {
313
+ if (!this.selectedFacets || !this.facetKey) return undefined;
314
+
315
+ const selectedFacetsForKey = this.selectedFacets[this.facetKey];
316
+ if (!selectedFacetsForKey) return undefined;
317
+
318
+ const facetGroupTitle = facetTitles[this.facetKey];
319
+
320
+ const buckets: FacetBucket[] = Object.entries(selectedFacetsForKey).map(
321
+ ([value, data]) => {
322
+ const displayText: string = value;
323
+ return {
324
+ displayText,
325
+ key: value,
326
+ count: data?.count,
327
+ state: data?.state,
328
+ };
329
+ },
330
+ );
331
+
332
+ return {
333
+ title: facetGroupTitle,
334
+ key: this.facetKey,
335
+ buckets,
336
+ };
337
+ }
338
+
339
+ /**
340
+ * Converts the raw `aggregations` for the current facet key to a `FacetGroup`,
341
+ * which is easier to work with.
342
+ */
343
+ private get aggregationFacetGroup(): FacetGroup | undefined {
344
+ if (!this.aggregations || !this.facetKey) return undefined;
345
+
346
+ const currentAggregation = this.aggregations[this.facetKey];
347
+ if (!currentAggregation) return undefined;
348
+
349
+ const facetGroupTitle = facetTitles[this.facetKey];
350
+
351
+ // Order the facets according to the current sort option
352
+ let sortedBuckets = currentAggregation.getSortedBuckets(
353
+ this.sortedBy,
354
+ ) as Bucket[];
355
+
356
+ if (this.facetKey === 'collection') {
357
+ // we are not showing fav- collections or certain deemphasized collections in facets
358
+ sortedBuckets = sortedBuckets?.filter(bucket => {
359
+ const bucketKey = bucket?.key?.toString();
360
+ return (
361
+ !suppressedCollections[bucketKey] && !bucketKey?.startsWith('fav-')
362
+ );
363
+ });
364
+ }
365
+
366
+ // Construct the array of facet buckets from the aggregation buckets
367
+ const facetBuckets: FacetBucket[] = sortedBuckets.map(bucket => {
368
+ const bucketKeyStr = `${bucket.key}`;
369
+ return {
370
+ displayText: `${bucketKeyStr}`,
371
+ key: `${bucketKeyStr}`,
372
+ count: bucket.doc_count,
373
+ state: 'none',
374
+ };
375
+ });
376
+
377
+ return {
378
+ title: facetGroupTitle,
379
+ key: this.facetKey,
380
+ buckets: facetBuckets,
381
+ };
382
+ }
383
+
384
+ /**
385
+ * Returns a FacetGroup representing only the current page of facet buckets to show.
386
+ */
387
+ private get facetGroupForCurrentPage(): FacetGroup | undefined {
388
+ const { facetGroup } = this;
389
+ if (!facetGroup) return undefined;
390
+
391
+ // Slice out only the current page of facet buckets
392
+ const firstBucketIndexOnPage = (this.pageNumber - 1) * this.facetsPerPage;
393
+ const truncatedBuckets = facetGroup.buckets.slice(
394
+ firstBucketIndexOnPage,
395
+ firstBucketIndexOnPage + this.facetsPerPage,
396
+ );
397
+
398
+ return {
399
+ ...facetGroup,
400
+ buckets: truncatedBuckets,
401
+ };
402
+ }
403
+
404
+ private get moreFacetsTemplate(): TemplateResult {
405
+ return html`
406
+ <facets-template
407
+ .facetGroup=${this.facetGroupForCurrentPage}
408
+ .selectedFacets=${this.selectedFacets}
409
+ .collectionTitles=${this.collectionTitles}
410
+ @facetClick=${(e: CustomEvent<FacetEventDetails>) => {
411
+ if (this.facetKey) {
412
+ this.unappliedFacetChanges = updateSelectedFacetBucket(
413
+ this.unappliedFacetChanges,
414
+ this.facetKey,
415
+ e.detail.bucket,
416
+ );
417
+ }
418
+ }}
419
+ ></facets-template>
420
+ `;
421
+ }
422
+
423
+ private get loaderTemplate(): TemplateResult {
424
+ return html`<div class="facets-loader">
425
+ <ia-activity-indicator .mode=${'processing'}></ia-activity-indicator>
426
+ </div> `;
427
+ }
428
+
429
+ /**
430
+ * How many pages of facets to show in the modal pagination widget
431
+ */
432
+ private get paginationSize(): number {
433
+ if (!this.aggregations || !this.facetKey) return 0;
434
+
435
+ // Calculate the appropriate number of pages to show in the modal pagination widget
436
+ const length = this.aggregations[this.facetKey]?.buckets.length;
437
+ return Math.ceil(length / this.facetsPerPage);
438
+ }
439
+
440
+ // render pagination if more then 1 page
441
+ private get facetsPaginationTemplate() {
442
+ return this.paginationSize > 1
443
+ ? html`<more-facets-pagination
444
+ .size=${this.paginationSize}
445
+ .currentPage=${1}
446
+ @pageNumberClicked=${this.pageNumberClicked}
447
+ ></more-facets-pagination>`
448
+ : nothing;
449
+ }
450
+
451
+ private get footerTemplate() {
452
+ if (this.paginationSize > 0) {
453
+ return html`${this.facetsPaginationTemplate}
454
+ <div class="footer">
455
+ <button
456
+ class="btn btn-cancel"
457
+ type="button"
458
+ @click=${this.cancelClick}
459
+ >
460
+ Cancel
461
+ </button>
462
+ <button
463
+ class="btn btn-submit"
464
+ type="button"
465
+ @click=${this.applySearchFacetsClicked}
466
+ >
467
+ Apply filters
468
+ </button>
469
+ </div> `;
470
+ }
471
+
472
+ return nothing;
473
+ }
474
+
475
+ private sortFacetAggregation(facetSortType: AggregationSortType) {
476
+ this.sortedBy = facetSortType;
477
+ this.dispatchEvent(
478
+ new CustomEvent('sortedFacets', { detail: this.sortedBy }),
479
+ );
480
+ }
481
+
482
+ private get modalHeaderTemplate(): TemplateResult {
483
+ const facetSort =
484
+ this.sortedBy ?? defaultFacetSort[this.facetKey as FacetOption];
485
+ const defaultSwitchSide =
486
+ facetSort === AggregationSortType.COUNT ? 'left' : 'right';
487
+
488
+ return html`<span class="sr-only">${msg('More facets for:')}</span>
489
+ <span class="title">
490
+ ${this.facetGroup?.title}
491
+
492
+ <label class="sort-label">${msg('Sort by:')}</label>
493
+ ${this.facetKey
494
+ ? html`<toggle-switch
495
+ class="sort-toggle"
496
+ leftValue=${AggregationSortType.COUNT}
497
+ leftLabel="Count"
498
+ rightValue=${valueFacetSort[this.facetKey]}
499
+ .rightLabel=${this.facetGroup?.title}
500
+ side=${defaultSwitchSide}
501
+ @change=${(e: CustomEvent<string>) => {
502
+ this.sortFacetAggregation(
503
+ Number(e.detail) as AggregationSortType,
504
+ );
505
+ }}
506
+ ></toggle-switch>`
507
+ : nothing}
508
+ </span>`;
509
+ }
510
+
511
+ render() {
512
+ return html`
513
+ ${this.facetsLoading
514
+ ? this.loaderTemplate
515
+ : html`
516
+ <section id="more-facets">
517
+ <div class="header-content">${this.modalHeaderTemplate}</div>
518
+ <div class="facets-content">${this.moreFacetsTemplate}</div>
519
+ ${this.footerTemplate}
520
+ </section>
521
+ `}
522
+ `;
523
+ }
524
+
525
+ private applySearchFacetsClicked() {
526
+ const mergedSelections = mergeSelectedFacets(
527
+ this.selectedFacets,
528
+ this.unappliedFacetChanges,
529
+ );
530
+
531
+ const event = new CustomEvent<SelectedFacets>('facetsChanged', {
532
+ detail: mergedSelections,
533
+ bubbles: true,
534
+ composed: true,
535
+ });
536
+ this.dispatchEvent(event);
537
+
538
+ // Reset the unapplied changes back to default, now that they have been applied
539
+ this.unappliedFacetChanges = getDefaultSelectedFacets();
540
+
541
+ this.modalManager?.closeModal();
542
+ this.analyticsHandler?.sendEvent({
543
+ category: analyticsCategories.default,
544
+ action: `${analyticsActions.applyMoreFacetsModal}`,
545
+ label: `${this.facetKey}`,
546
+ });
547
+ }
548
+
549
+ private cancelClick() {
550
+ // Reset the unapplied changes back to default
551
+ this.unappliedFacetChanges = getDefaultSelectedFacets();
552
+
553
+ this.modalManager?.closeModal();
554
+ this.analyticsHandler?.sendEvent({
555
+ category: analyticsCategories.default,
556
+ action: analyticsActions.closeMoreFacetsModal,
557
+ label: `${this.facetKey}`,
558
+ });
559
+ }
560
+
561
+ static get styles(): CSSResultGroup {
562
+ const modalSubmitButton = css`var(--primaryButtonBGColor, #194880)`;
563
+
564
+ return [
565
+ srOnlyStyle,
566
+ css`
567
+ section#more-facets {
568
+ overflow: auto;
569
+ padding: 10px; /* leaves room for scroll bar to appear without overlaying on content */
570
+ --facetsColumnCount: 3;
571
+ }
572
+ .header-content .title {
573
+ display: block;
574
+ text-align: left;
575
+ font-size: 1.8rem;
576
+ padding: 0 10px;
577
+ font-weight: bold;
578
+ }
579
+
580
+ .sort-label {
581
+ margin-left: 20px;
582
+ font-size: 1.3rem;
583
+ }
584
+
585
+ .sort-toggle {
586
+ font-weight: normal;
587
+ }
588
+
589
+ .facets-content {
590
+ font-size: 1.2rem;
591
+ max-height: 300px;
592
+ overflow: auto;
593
+ padding: 10px;
594
+ }
595
+ .facets-loader {
596
+ margin-bottom: 20px;
597
+ width: 70px;
598
+ display: block;
599
+ margin-left: auto;
600
+ margin-right: auto;
601
+ }
602
+ .btn {
603
+ border: none;
604
+ padding: 10px;
605
+ margin-bottom: 10px;
606
+ width: auto;
607
+ border-radius: 4px;
608
+ cursor: pointer;
609
+ }
610
+ .btn-cancel {
611
+ background-color: #2c2c2c;
612
+ color: white;
613
+ }
614
+ .btn-submit {
615
+ background-color: ${modalSubmitButton};
616
+ color: white;
617
+ }
618
+ .footer {
619
+ text-align: center;
620
+ margin-top: 10px;
621
+ }
622
+
623
+ @media (max-width: 560px) {
624
+ section#more-facets {
625
+ max-height: 450px;
626
+ --facetsColumnCount: 1;
627
+ }
628
+ .facets-content {
629
+ overflow-y: auto;
630
+ height: 300px;
631
+ }
632
+ }
633
+ `,
634
+ ];
635
+ }
636
+ }