@internetarchive/collection-browser 3.3.4-alpha-webdev7761.5 → 3.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/dist/src/collection-browser.d.ts +2 -15
  2. package/dist/src/collection-browser.js +693 -868
  3. package/dist/src/collection-browser.js.map +1 -1
  4. package/dist/src/collection-facets/facet-row.js +1 -2
  5. package/dist/src/collection-facets/facet-row.js.map +1 -1
  6. package/dist/src/collection-facets.js +266 -280
  7. package/dist/src/collection-facets.js.map +1 -1
  8. package/dist/src/data-source/collection-browser-data-source-interface.d.ts +1 -10
  9. package/dist/src/data-source/collection-browser-data-source-interface.js.map +1 -1
  10. package/dist/src/data-source/collection-browser-data-source.d.ts +1 -19
  11. package/dist/src/data-source/collection-browser-data-source.js +18 -36
  12. package/dist/src/data-source/collection-browser-data-source.js.map +1 -1
  13. package/dist/src/data-source/collection-browser-query-state.d.ts +2 -1
  14. package/dist/src/data-source/collection-browser-query-state.js.map +1 -1
  15. package/dist/src/data-source/models.d.ts +0 -11
  16. package/dist/src/data-source/models.js.map +1 -1
  17. package/dist/src/models.d.ts +6 -2
  18. package/dist/src/models.js +12 -8
  19. package/dist/src/models.js.map +1 -1
  20. package/dist/src/restoration-state-handler.d.ts +2 -1
  21. package/dist/src/restoration-state-handler.js +9 -3
  22. package/dist/src/restoration-state-handler.js.map +1 -1
  23. package/dist/test/collection-browser.test.js +9 -19
  24. package/dist/test/collection-browser.test.js.map +1 -1
  25. package/dist/test/restoration-state-handler.test.js +37 -5
  26. package/dist/test/restoration-state-handler.test.js.map +1 -1
  27. package/package.json +2 -2
  28. package/src/collection-browser.ts +2829 -3037
  29. package/src/collection-facets/facet-row.ts +1 -4
  30. package/src/collection-facets.ts +995 -1009
  31. package/src/data-source/collection-browser-data-source-interface.ts +0 -12
  32. package/src/data-source/collection-browser-data-source.ts +19 -59
  33. package/src/data-source/collection-browser-query-state.ts +7 -1
  34. package/src/data-source/models.ts +0 -13
  35. package/src/models.ts +14 -10
  36. package/src/restoration-state-handler.ts +11 -9
  37. package/test/collection-browser.test.ts +11 -21
  38. package/test/restoration-state-handler.test.ts +42 -12
@@ -1,1009 +1,995 @@
1
- import {
2
- css,
3
- html,
4
- LitElement,
5
- PropertyValues,
6
- nothing,
7
- TemplateResult,
8
- } from 'lit';
9
- import { customElement, property, state } from 'lit/decorators.js';
10
- import { map } from 'lit/directives/map.js';
11
- import { ref } from 'lit/directives/ref.js';
12
- import { msg } from '@lit/localize';
13
- import { classMap } from 'lit/directives/class-map.js';
14
- import {
15
- Aggregation,
16
- AggregationSortType,
17
- Bucket,
18
- FilterMap,
19
- SearchServiceInterface,
20
- SearchType,
21
- } from '@internetarchive/search-service';
22
- import '@internetarchive/histogram-date-range';
23
- import '@internetarchive/feature-feedback';
24
- import {
25
- ModalConfig,
26
- ModalManagerInterface,
27
- } from '@internetarchive/modal-manager';
28
- import type { FeatureFeedbackServiceInterface } from '@internetarchive/feature-feedback';
29
- import type { RecaptchaManagerInterface } from '@internetarchive/recaptcha-manager';
30
- import type { AnalyticsManagerInterface } from '@internetarchive/analytics-manager';
31
- import type { SharedResizeObserverInterface } from '@internetarchive/shared-resize-observer';
32
- import type {
33
- BarScalingOption,
34
- BinSnappingInterval,
35
- } from '@internetarchive/histogram-date-range';
36
- import chevronIcon from './assets/img/icons/chevron';
37
- import expandIcon from './assets/img/icons/expand';
38
- import {
39
- FacetOption,
40
- SelectedFacets,
41
- FacetGroup,
42
- FacetBucket,
43
- defaultFacetDisplayOrder,
44
- facetTitles,
45
- lendingFacetDisplayNames,
46
- lendingFacetKeysVisibility,
47
- LendingFacetKey,
48
- suppressedCollections,
49
- defaultFacetSort,
50
- FacetEventDetails,
51
- } from './models';
52
- import type {
53
- CollectionTitles,
54
- PageSpecifierParams,
55
- TVChannelAliases,
56
- } from './data-source/models';
57
- import {
58
- analyticsActions,
59
- analyticsCategories,
60
- } from './utils/analytics-events';
61
- import { srOnlyStyle } from './styles/sr-only';
62
- import { ExpandedDatePicker } from './expanded-date-picker';
63
- import {
64
- sortBucketsBySelectionState,
65
- updateSelectedFacetBucket,
66
- } from './utils/facet-utils';
67
-
68
- import '@internetarchive/histogram-date-range';
69
- import './collection-facets/more-facets-content';
70
- import './collection-facets/facets-template';
71
- import './collection-facets/facet-tombstone-row';
72
- import './expanded-date-picker';
73
-
74
- @customElement('collection-facets')
75
- export class CollectionFacets extends LitElement {
76
- @property({ type: Object }) searchService?: SearchServiceInterface;
77
-
78
- @property({ type: Number }) searchType?: SearchType;
79
-
80
- @property({ type: Object }) aggregations?: Record<string, Aggregation>;
81
-
82
- @property({ type: Object }) histogramAggregation?: Aggregation;
83
-
84
- @property({ type: String }) minSelectedDate?: string;
85
-
86
- @property({ type: String }) maxSelectedDate?: string;
87
-
88
- @property({ type: Boolean }) moreLinksVisible = true;
89
-
90
- @property({ type: Boolean }) facetsLoading = false;
91
-
92
- @property({ type: Boolean }) histogramAggregationLoading = false;
93
-
94
- @property({ type: Object }) selectedFacets?: SelectedFacets;
95
-
96
- @property({ type: Boolean }) collapsableFacets = false;
97
-
98
- @property({ type: Number }) contentWidth?: number;
99
-
100
- @property({ type: Boolean }) showHistogramDatePicker = false;
101
-
102
- @property({ type: Boolean }) allowExpandingDatePicker = false;
103
-
104
- @property({ type: Boolean }) suppressMediatypeFacets = false;
105
-
106
- @property({ type: String }) query?: string;
107
-
108
- @property({ type: Array }) identifiers?: string[];
109
-
110
- @property({ type: Object }) pageSpecifierParams?: PageSpecifierParams;
111
-
112
- @property({ type: Array }) parentCollections: string[] = [];
113
-
114
- @property({ type: Object }) filterMap?: FilterMap;
115
-
116
- @property({ type: String }) baseNavigationUrl?: string;
117
-
118
- @property({ type: String }) collectionPagePath: string = '/details/';
119
-
120
- @property({ type: Boolean }) isManageView = false;
121
-
122
- @property({ type: Boolean }) isTvSearch = false;
123
-
124
- @property({ type: Array }) facetDisplayOrder: FacetOption[] =
125
- defaultFacetDisplayOrder;
126
-
127
- @property({ type: Object, attribute: false })
128
- modalManager?: ModalManagerInterface;
129
-
130
- @property({ type: Object, attribute: false })
131
- resizeObserver?: SharedResizeObserverInterface;
132
-
133
- @property({ type: Object, attribute: false })
134
- featureFeedbackService?: FeatureFeedbackServiceInterface;
135
-
136
- @property({ type: Object, attribute: false })
137
- recaptchaManager?: RecaptchaManagerInterface;
138
-
139
- @property({ type: Object, attribute: false })
140
- analyticsHandler?: AnalyticsManagerInterface;
141
-
142
- @property({ type: Object, attribute: false })
143
- collectionTitles?: CollectionTitles;
144
-
145
- @property({ type: Object, attribute: false })
146
- tvChannelAliases?: TVChannelAliases;
147
-
148
- @state() openFacets: Record<FacetOption, boolean> = {
149
- subject: false,
150
- lending: false,
151
- mediatype: false,
152
- language: false,
153
- creator: false,
154
- collection: false,
155
- year: false,
156
- clip_type: false,
157
- program: false,
158
- person: false,
159
- sponsor: false,
160
- };
161
-
162
- /**
163
- * Maximum # of facet buckets to render per facet group
164
- */
165
- private allowedFacetCount = 6;
166
-
167
- render() {
168
- const containerClasses = classMap({
169
- loading: this.facetsLoading,
170
- managing: this.isManageView,
171
- });
172
-
173
- const heading = this.isTvSearch
174
- ? msg('Date Published')
175
- : msg('Year Published');
176
-
177
- // Added data-testid for Playwright testing
178
- // Using facet-group class and aria-labels is not ideal for Playwright locator
179
- const datePickerLabelId = 'date-picker-label';
180
- return html`
181
- <div id="container" class=${containerClasses}>
182
- ${this.showHistogramDatePicker &&
183
- (this.histogramAggregation || this.histogramAggregationLoading)
184
- ? html`
185
- <section
186
- class="facet-group"
187
- aria-labelledby=${datePickerLabelId}
188
- data-testid="facet-group-header-label-date-picker"
189
- >
190
- <h3 id=${datePickerLabelId}>
191
- ${heading} <span class="sr-only">${msg('range filter')}</span>
192
- ${this.expandDatePickerBtnTemplate}
193
- </h3>
194
- ${this.histogramTemplate}
195
- </section>
196
- `
197
- : nothing}
198
- ${this.collectionPartOfTemplate}
199
- <slot name="facets-top"></slot>
200
- ${this.mergedFacets.map(facetGroup =>
201
- this.getFacetGroupTemplate(facetGroup),
202
- )}
203
- </div>
204
- `;
205
- }
206
-
207
- private get collectionPartOfTemplate(): TemplateResult | typeof nothing {
208
- // We only display the "Part Of" section on collection pages
209
- if (!this.parentCollections?.length) return nothing;
210
-
211
- // Added data-testid for Playwright testing
212
- // Using className and aria-labels is not ideal for Playwright locator
213
- const headingId = 'partof-heading';
214
- return html`
215
- <section
216
- class="facet-group partof-collections"
217
- aria-labelledby=${headingId}
218
- data-testid="facet-group-partof-collections"
219
- >
220
- <div class="facet-group-header">
221
- <h3 id=${headingId}>${msg('Part Of')}</h3>
222
- </div>
223
- <ul>
224
- ${map(this.parentCollections, collxn => {
225
- const collectionURL = `${this.baseNavigationUrl}${this.collectionPagePath}${collxn}`;
226
-
227
- return html` <li>
228
- <a
229
- href=${collectionURL}
230
- data-id=${collxn}
231
- @click=${this.partOfCollectionClicked}
232
- >
233
- ${this.collectionTitles?.get(collxn) ?? collxn}
234
- </a>
235
- </li>`;
236
- })}
237
- </ul>
238
- </section>
239
- `;
240
- }
241
-
242
- private partOfCollectionClicked(e: Event): void {
243
- this.analyticsHandler?.sendEvent({
244
- category: analyticsCategories.default,
245
- action: analyticsActions.partOfCollectionClicked,
246
- label: (e.target as HTMLElement).dataset.id,
247
- });
248
- }
249
-
250
- /**
251
- * Properties to pass into the date-picker histogram component
252
- */
253
- private get histogramProps() {
254
- const { histogramAggregation: aggregation } = this;
255
- if (!aggregation) return undefined;
256
-
257
- // Normalize some properties from the raw aggregation
258
- const firstYear =
259
- aggregation.first_bucket_year ?? aggregation.first_bucket_key;
260
- const lastYear =
261
- aggregation.last_bucket_year ?? aggregation.last_bucket_key;
262
- if (firstYear == null || lastYear == null) return undefined; // We at least need a start/end year defined
263
-
264
- const firstMonth = aggregation.first_bucket_month ?? 1;
265
- const lastMonth = aggregation.last_bucket_month ?? 12;
266
-
267
- const yearInterval = aggregation.interval ?? 1;
268
- const monthInterval = aggregation.interval_in_months ?? 12;
269
-
270
- const zeroPadMonth = (month: number) => month.toString().padStart(2, '0');
271
-
272
- // The date picker is configured differently for TV search, allowing month-level resolution
273
- if (this.isTvSearch) {
274
- // Whether the bucket interval is less than a year
275
- // (i.e., requires individual months to be handled & labeled)
276
- const mustHandleMonths = monthInterval < 12;
277
-
278
- return {
279
- buckets: aggregation.buckets as number[],
280
- dateFormat: 'YYYY-MM',
281
- tooltipDateFormat: mustHandleMonths ? 'MMM YYYY' : 'YYYY',
282
- tooltipLabel: 'broadcast',
283
- binSnapping: (mustHandleMonths
284
- ? 'month'
285
- : 'year') as BinSnappingInterval,
286
- barScaling: 'linear' as BarScalingOption,
287
- minDate: `${firstYear}-${zeroPadMonth(firstMonth)}`,
288
- maxDate: `${lastYear}-${zeroPadMonth(lastMonth + monthInterval - 1)}`,
289
- };
290
- }
291
-
292
- // All other search types use the same configuration
293
- return {
294
- buckets: aggregation.buckets as number[],
295
- dateFormat: 'YYYY',
296
- tooltipDateFormat: 'YYYY',
297
- tooltipLabel: 'item',
298
- binSnapping: 'year' as BinSnappingInterval,
299
- barScaling: 'logarithmic' as BarScalingOption,
300
- minDate: `${firstYear}`,
301
- maxDate: `${lastYear + yearInterval - 1}`,
302
- };
303
- }
304
-
305
- /**
306
- * Opens a modal dialog containing an enlarged version of the date picker.
307
- */
308
- private showDatePickerModal(): void {
309
- const { histogramProps } = this;
310
- if (!histogramProps) return;
311
-
312
- const {
313
- buckets,
314
- dateFormat,
315
- tooltipDateFormat,
316
- tooltipLabel,
317
- binSnapping,
318
- barScaling,
319
- minDate,
320
- maxDate,
321
- } = histogramProps;
322
-
323
- // Because the modal manager does not clear its DOM content after being closed,
324
- // it may try to render the exact same date picker template when it is reopened.
325
- // And because it isn't actually a descendent of this collection-facets component,
326
- // changes to the template defined here may not trigger a reactive update to the date
327
- // picker, resulting in it displaying a stale date range.
328
- // This ref callback ensures that every time the date picker modal is opened, it will
329
- // always propagate the most recent date range into the date picker regardless of
330
- // whether Lit thinks the update is necessary.
331
- const expandedDatePickerChanged = (elmt?: Element) => {
332
- if (elmt && elmt instanceof ExpandedDatePicker) {
333
- const expandedDatePicker = elmt as ExpandedDatePicker;
334
- expandedDatePicker.minSelectedDate = this.minSelectedDate;
335
- expandedDatePicker.maxSelectedDate = this.maxSelectedDate;
336
- }
337
- };
338
-
339
- const customModalContent = html`
340
- <expanded-date-picker
341
- ${ref(expandedDatePickerChanged)}
342
- .minDate=${minDate}
343
- .maxDate=${maxDate}
344
- .minSelectedDate=${this.minSelectedDate}
345
- .maxSelectedDate=${this.maxSelectedDate}
346
- .customDateFormat=${dateFormat}
347
- .customTooltipDateFormat=${tooltipDateFormat}
348
- .customTooltipLabel=${tooltipLabel}
349
- .binSnapping=${binSnapping}
350
- .barScaling=${barScaling}
351
- .buckets=${buckets}
352
- .modalManager=${this.modalManager}
353
- .analyticsHandler=${this.analyticsHandler}
354
- @histogramDateRangeApplied=${this.histogramDateRangeUpdated}
355
- @modalClosed=${this.handleExpandedDatePickerClosed}
356
- ></expanded-date-picker>
357
- `;
358
-
359
- const config = new ModalConfig({
360
- bodyColor: '#fff',
361
- headerColor: '#194880',
362
- showHeaderLogo: false,
363
- closeOnBackdropClick: true, // TODO: want to fire analytics
364
- title: html`${msg('Select a date range')}`,
365
- });
366
-
367
- this.modalManager?.classList.add('expanded-date-picker');
368
- this.modalManager?.showModal({
369
- config,
370
- customModalContent,
371
- userClosedModalCallback: this.handleExpandedDatePickerClosed,
372
- });
373
-
374
- this.analyticsHandler?.sendEvent({
375
- category: analyticsCategories.default,
376
- action: analyticsActions.histogramExpanded,
377
- label: window.location.href,
378
- });
379
- }
380
-
381
- private handleExpandedDatePickerClosed = (): void => {
382
- this.modalManager?.classList.remove('expanded-date-picker');
383
- };
384
-
385
- updated(changed: PropertyValues) {
386
- if (changed.has('selectedFacets')) {
387
- this.dispatchFacetsChangedEvent();
388
- }
389
- }
390
-
391
- // TODO: want to fire analytics?
392
- private dispatchFacetsChangedEvent() {
393
- const event = new CustomEvent<SelectedFacets>('facetsChanged', {
394
- detail: this.selectedFacets,
395
- });
396
- this.dispatchEvent(event);
397
- }
398
-
399
- /**
400
- * Template for the "Expand" button to show the date picker modal, or
401
- * `nothing` if that button should currently not be shown.
402
- */
403
- private get expandDatePickerBtnTemplate(): TemplateResult | typeof nothing {
404
- return this.allowExpandingDatePicker && !this.facetsLoading
405
- ? html`<button
406
- class="expand-date-picker-btn"
407
- aria-haspopup="dialog"
408
- @click=${this.showDatePickerModal}
409
- >
410
- ${expandIcon}
411
- </button>`
412
- : nothing;
413
- }
414
-
415
- private get histogramTemplate(): TemplateResult | typeof nothing {
416
- if (this.histogramAggregationLoading) {
417
- return html` <div class="histogram-loading-indicator">&hellip;</div> `;
418
- }
419
-
420
- const { histogramProps } = this;
421
- if (!histogramProps) return nothing;
422
-
423
- const {
424
- buckets,
425
- dateFormat,
426
- tooltipDateFormat,
427
- tooltipLabel,
428
- binSnapping,
429
- barScaling,
430
- minDate,
431
- maxDate,
432
- } = histogramProps;
433
-
434
- return html`
435
- <histogram-date-range
436
- class=${this.isTvSearch ? 'wide-inputs' : ''}
437
- .minDate=${minDate}
438
- .maxDate=${maxDate}
439
- .minSelectedDate=${this.minSelectedDate ?? minDate}
440
- .maxSelectedDate=${this.maxSelectedDate ?? maxDate}
441
- .updateDelay=${100}
442
- .dateFormat=${dateFormat}
443
- .tooltipDateFormat=${tooltipDateFormat}
444
- .tooltipLabel=${tooltipLabel}
445
- .binSnapping=${binSnapping}
446
- .barScaling=${barScaling}
447
- .bins=${buckets}
448
- missingDataMessage="..."
449
- .width=${this.collapsableFacets && this.contentWidth
450
- ? this.contentWidth
451
- : 180}
452
- @histogramDateRangeUpdated=${this.histogramDateRangeUpdated}
453
- ></histogram-date-range>
454
- `;
455
- }
456
-
457
- /**
458
- * Dispatches a `histogramDateRangeUpdated` event with the date range copied from the
459
- * input event.
460
- *
461
- * Arrow function to ensure `this` is always bound to the current component.
462
- */
463
- private histogramDateRangeUpdated = (
464
- e: CustomEvent<{
465
- minDate: string;
466
- maxDate: string;
467
- }>,
468
- ): void => {
469
- const { minDate, maxDate } = e.detail;
470
- const event = new CustomEvent('histogramDateRangeUpdated', {
471
- detail: { minDate, maxDate },
472
- });
473
- this.dispatchEvent(event);
474
- };
475
-
476
- /**
477
- * Combines the selected facets with the aggregations to create a single list of facets
478
- */
479
- private get mergedFacets(): FacetGroup[] {
480
- const facetGroups: FacetGroup[] = [];
481
-
482
- this.facetDisplayOrder.forEach(facetKey => {
483
- if (facetKey === 'mediatype' && this.suppressMediatypeFacets) return;
484
-
485
- const selectedFacetGroup = this.selectedFacetGroups.find(
486
- group => group.key === facetKey,
487
- );
488
- const aggregateFacetGroup = this.aggregationFacetGroups.find(
489
- group => group.key === facetKey,
490
- );
491
-
492
- // if the user selected a facet, but it's not in the aggregation, we add it as-is
493
- if (selectedFacetGroup && !aggregateFacetGroup) {
494
- facetGroups.push(selectedFacetGroup);
495
- return;
496
- }
497
-
498
- // if we don't have an aggregate facet group, don't add this to the list
499
- if (!aggregateFacetGroup) return;
500
-
501
- // start with either the selected group if we have one, or the aggregate group
502
- const facetGroup = selectedFacetGroup ?? aggregateFacetGroup;
503
-
504
- // attach the counts to the selected buckets
505
- let bucketsWithCount =
506
- selectedFacetGroup?.buckets.map(bucket => {
507
- const selectedBucket = aggregateFacetGroup.buckets.find(
508
- b => b.key === bucket.key,
509
- );
510
- return selectedBucket
511
- ? {
512
- ...bucket,
513
- count: selectedBucket.count,
514
- }
515
- : bucket;
516
- }) ?? [];
517
-
518
- // append any additional buckets that were not selected
519
- aggregateFacetGroup.buckets.forEach(bucket => {
520
- const existingBucket = bucketsWithCount.find(b => b.key === bucket.key);
521
- if (existingBucket) return;
522
- bucketsWithCount.push(bucket);
523
- });
524
-
525
- /**
526
- * render limited facet items on page facet area
527
- *
528
- * - by-default we are showing 6 items
529
- * - additionally want to show all items (selected/suppressed) in page facet area
530
- */
531
- let allowedFacetCount = Object.keys(
532
- (selectedFacetGroup?.buckets as []) || [],
533
- )?.length;
534
- if (allowedFacetCount < this.allowedFacetCount) {
535
- allowedFacetCount = this.allowedFacetCount; // splice start index from 0th
536
- }
537
-
538
- // For lending facets, only include a specific subset of buckets
539
- if (facetKey === 'lending') {
540
- bucketsWithCount = bucketsWithCount.filter(
541
- bucket => lendingFacetKeysVisibility[bucket.key as LendingFacetKey],
542
- );
543
- }
544
-
545
- // Sort the FacetBuckets so that selected and hidden buckets come before the rest
546
- sortBucketsBySelectionState(bucketsWithCount, defaultFacetSort[facetKey]);
547
-
548
- // For mediatype facets, ensure the collection bucket is always shown if present
549
- if (facetKey === 'mediatype') {
550
- const collectionIndex = bucketsWithCount.findIndex(
551
- bucket => bucket.key === 'collection',
552
- );
553
-
554
- if (collectionIndex >= allowedFacetCount) {
555
- const [collectionBucket] = bucketsWithCount.splice(
556
- collectionIndex,
557
- 1,
558
- );
559
-
560
- // If we're showing lots of selected facets, ensure we're not cutting off the last one
561
- if (allowedFacetCount > this.allowedFacetCount) {
562
- allowedFacetCount += 1;
563
- }
564
-
565
- bucketsWithCount.splice(allowedFacetCount - 1, 0, collectionBucket);
566
- }
567
- }
568
-
569
- // For TV creator facets, uppercase the display text
570
- if (facetKey === 'creator' && this.isTvSearch) {
571
- bucketsWithCount.forEach(b => {
572
- b.displayText = (b.displayText ?? b.key)?.toLocaleUpperCase();
573
-
574
- const channelLabel = this.tvChannelAliases?.get(b.displayText);
575
- if (channelLabel && channelLabel !== b.displayText) {
576
- b.extraNote = `(${channelLabel})`;
577
- }
578
- });
579
- }
580
- // For TV clip_type facets, capitalize the display text
581
- if (facetKey === 'clip_type') {
582
- bucketsWithCount.forEach(b => {
583
- b.displayText ??= b.key;
584
- b.displayText =
585
- b.displayText.charAt(0).toLocaleUpperCase() +
586
- b.displayText.slice(1);
587
- });
588
- }
589
-
590
- // slice off how many items we want to show in page facet area
591
- facetGroup.buckets = bucketsWithCount.slice(0, allowedFacetCount);
592
-
593
- facetGroups.push(facetGroup);
594
- });
595
-
596
- return facetGroups;
597
- }
598
-
599
- /**
600
- * Converts the selected facets to a `FacetGroup` array,
601
- * which is easier to work with
602
- */
603
- private get selectedFacetGroups(): FacetGroup[] {
604
- if (!this.selectedFacets) return [];
605
-
606
- const facetGroups: FacetGroup[] = Object.entries(this.selectedFacets).map(
607
- ([key, selectedFacets]) => {
608
- const option = key as FacetOption;
609
- const title = facetTitles[option];
610
-
611
- const buckets: FacetBucket[] = Object.entries(selectedFacets).map(
612
- ([value, facetData]) => {
613
- let displayText: string = value;
614
- // for lending facets, convert the key to a readable format
615
- if (option === 'lending') {
616
- displayText =
617
- lendingFacetDisplayNames[value as LendingFacetKey] ?? value;
618
- }
619
- return {
620
- displayText,
621
- key: value,
622
- count: facetData.count,
623
- state: facetData.state,
624
- };
625
- },
626
- );
627
-
628
- return {
629
- title,
630
- key: option,
631
- buckets,
632
- };
633
- },
634
- );
635
-
636
- return facetGroups;
637
- }
638
-
639
- /**
640
- * Converts the raw `aggregations` to `FacetGroups`, which are easier to use
641
- */
642
- private get aggregationFacetGroups(): FacetGroup[] {
643
- const facetGroups: FacetGroup[] = [];
644
- Object.entries(this.aggregations ?? []).forEach(([key, aggregation]) => {
645
- // the year_histogram and date_histogram data is in a different format so can't be handled here
646
- if (['year_histogram', 'date_histogram'].includes(key)) return;
647
-
648
- const option = key as FacetOption;
649
- const title = facetTitles[option];
650
- if (!title) return;
651
-
652
- let castedBuckets = aggregation.getSortedBuckets(
653
- defaultFacetSort[option],
654
- ) as Bucket[];
655
-
656
- if (option === 'collection') {
657
- // we are not showing fav- collections or certain deemphasized collections in facets
658
- castedBuckets = castedBuckets?.filter(bucket => {
659
- const bucketKey = bucket?.key?.toString();
660
- return (
661
- !suppressedCollections[bucketKey] && !bucketKey?.startsWith('fav-')
662
- );
663
- });
664
- }
665
-
666
- const facetBuckets: FacetBucket[] = castedBuckets.map(bucket => {
667
- const bucketKey = bucket.key;
668
- let displayText = `${bucket.key}`;
669
- // for lending facets, convert the bucket key to a readable format
670
- if (option === 'lending') {
671
- displayText =
672
- lendingFacetDisplayNames[bucket.key as LendingFacetKey] ??
673
- `${bucket.key}`;
674
- }
675
- return {
676
- displayText,
677
- key: `${bucketKey}`,
678
- count: bucket.doc_count,
679
- state: 'none',
680
- };
681
- });
682
- const group: FacetGroup = {
683
- title,
684
- key: option,
685
- buckets: facetBuckets,
686
- };
687
- facetGroups.push(group);
688
- });
689
- return facetGroups;
690
- }
691
-
692
- /**
693
- * Generate the template for a facet group with a header and the collapsible
694
- * chevron for the mobile view
695
- */
696
- private getFacetGroupTemplate(
697
- facetGroup: FacetGroup,
698
- ): TemplateResult | typeof nothing {
699
- if (!this.facetsLoading && facetGroup.buckets.length === 0) return nothing;
700
-
701
- const { key } = facetGroup;
702
- const isOpen = this.openFacets[key];
703
- const collapser = html`
704
- <span class="collapser ${isOpen ? 'open' : ''}"> ${chevronIcon} </span>
705
- `;
706
-
707
- const toggleCollapsed = () => {
708
- const newOpenFacets = { ...this.openFacets };
709
- newOpenFacets[key] = !isOpen;
710
- this.openFacets = newOpenFacets;
711
- };
712
-
713
- // Added data-testid for Playwright testing
714
- // Using className and aria-labels is not ideal for Playwright locator
715
- const headerId = `facet-group-header-label-${facetGroup.key}`;
716
- return html`
717
- <section
718
- class="facet-group ${this.collapsableFacets ? 'mobile' : ''}"
719
- aria-labelledby=${headerId}
720
- data-testid=${headerId}
721
- >
722
- <div class="facet-group-header">
723
- <h3
724
- id=${headerId}
725
- @click=${toggleCollapsed}
726
- @keyup=${toggleCollapsed}
727
- >
728
- ${this.collapsableFacets ? collapser : nothing} ${facetGroup.title}
729
- <span class="sr-only">filters</span>
730
- </h3>
731
- </div>
732
- <div
733
- class="facet-group-content ${isOpen ? 'open' : ''}"
734
- data-testid="facet-group-content-${facetGroup.key}"
735
- >
736
- ${this.facetsLoading
737
- ? this.getTombstoneFacetGroupTemplate()
738
- : html`
739
- ${this.getFacetTemplate(facetGroup)}
740
- ${this.searchMoreFacetsLink(facetGroup)}
741
- `}
742
- </div>
743
- </section>
744
- `;
745
- }
746
-
747
- private getTombstoneFacetGroupTemplate(): TemplateResult {
748
- // Render five tombstone rows
749
- return html`
750
- ${map(
751
- Array(5).fill(null),
752
- () => html`<facet-tombstone-row></facet-tombstone-row>`,
753
- )}
754
- `;
755
- }
756
-
757
- /**
758
- * Generate the More... link button just below the facets group
759
- *
760
- * TODO: want to fire analytics?
761
- */
762
- private searchMoreFacetsLink(
763
- facetGroup: FacetGroup,
764
- ): TemplateResult | typeof nothing {
765
- // Don't render More... links for FTS searches
766
- if (!this.moreLinksVisible) {
767
- return nothing;
768
- }
769
-
770
- // Don't render More... links for lending facets
771
- if (facetGroup.key === 'lending') {
772
- return nothing;
773
- }
774
-
775
- // Don't render More... link if the number of facets < this.allowedFacetCount
776
- if (Object.keys(facetGroup.buckets).length < this.allowedFacetCount) {
777
- return nothing;
778
- }
779
-
780
- // We sort years in numeric order by default, rather than bucket count
781
- const facetSort = defaultFacetSort[facetGroup.key];
782
-
783
- // Added data-testid for Playwright testing
784
- // Using the className is not ideal for Playwright locator
785
- return html`<button
786
- class="more-link"
787
- @click=${() => {
788
- this.showMoreFacetsModal(facetGroup, facetSort);
789
- this.analyticsHandler?.sendEvent({
790
- category: analyticsCategories.default,
791
- action: analyticsActions.showMoreFacetsModal,
792
- label: facetGroup.key,
793
- });
794
- this.dispatchEvent(
795
- new CustomEvent('showMoreFacets', { detail: facetGroup.key }),
796
- );
797
- }}
798
- data-testid="more-link-btn"
799
- >
800
- More...
801
- </button>`;
802
- }
803
-
804
- async showMoreFacetsModal(
805
- facetGroup: FacetGroup,
806
- sortedBy: AggregationSortType,
807
- ): Promise<void> {
808
- const customModalContent = html`
809
- <more-facets-content
810
- .analyticsHandler=${this.analyticsHandler}
811
- .facetKey=${facetGroup.key}
812
- .query=${this.query}
813
- .identifiers=${this.identifiers}
814
- .filterMap=${this.filterMap}
815
- .pageSpecifierParams=${this.pageSpecifierParams}
816
- .modalManager=${this.modalManager}
817
- .searchService=${this.searchService}
818
- .searchType=${this.searchType}
819
- .collectionTitles=${this.collectionTitles}
820
- .tvChannelAliases=${this.tvChannelAliases}
821
- .selectedFacets=${this.selectedFacets}
822
- .sortedBy=${sortedBy}
823
- .isTvSearch=${this.isTvSearch}
824
- @facetsChanged=${(e: CustomEvent) => {
825
- const event = new CustomEvent<SelectedFacets>('facetsChanged', {
826
- detail: e.detail,
827
- bubbles: true,
828
- composed: true,
829
- });
830
- this.dispatchEvent(event);
831
- }}
832
- >
833
- </more-facets-content>
834
- `;
835
-
836
- const config = new ModalConfig({
837
- bodyColor: '#fff',
838
- headerColor: '#194880',
839
- showHeaderLogo: false,
840
- closeOnBackdropClick: true, // TODO: want to fire analytics
841
- title: html`Select filters`,
842
- });
843
- this.modalManager?.classList.add('more-search-facets');
844
- this.modalManager?.showModal({
845
- config,
846
- customModalContent,
847
- userClosedModalCallback: () => {
848
- this.modalManager?.classList.remove('more-search-facets');
849
- },
850
- });
851
- }
852
-
853
- /**
854
- * Generate the list template for each bucket in a facet group
855
- */
856
- private getFacetTemplate(facetGroup: FacetGroup): TemplateResult {
857
- return html`
858
- <facets-template
859
- .collectionPagePath=${this.collectionPagePath}
860
- .facetGroup=${facetGroup}
861
- .selectedFacets=${this.selectedFacets}
862
- .collectionTitles=${this.collectionTitles}
863
- @facetClick=${(e: CustomEvent<FacetEventDetails>) => {
864
- this.selectedFacets = updateSelectedFacetBucket(
865
- this.selectedFacets,
866
- facetGroup.key,
867
- e.detail.bucket,
868
- true,
869
- );
870
-
871
- const event = new CustomEvent<SelectedFacets>('facetsChanged', {
872
- detail: this.selectedFacets,
873
- bubbles: true,
874
- composed: true,
875
- });
876
- this.dispatchEvent(event);
877
- }}
878
- ></facets-template>
879
- `;
880
- }
881
-
882
- static get styles() {
883
- return [
884
- srOnlyStyle,
885
- css`
886
- a:link {
887
- text-decoration: none;
888
- color: var(--ia-theme-link-color, #4b64ff);
889
- }
890
- a:link:hover {
891
- text-decoration: underline;
892
- }
893
-
894
- #container.loading {
895
- opacity: 0.5;
896
- }
897
-
898
- #container.managing {
899
- opacity: 0.3;
900
- }
901
-
902
- .histogram-loading-indicator {
903
- width: 100%;
904
- height: 2.25rem;
905
- margin-top: 1.75rem;
906
- font-size: 1.4rem;
907
- text-align: center;
908
- }
909
-
910
- .collapser {
911
- display: inline-block;
912
- cursor: pointer;
913
- width: 10px;
914
- height: 10px;
915
- }
916
-
917
- .collapser svg {
918
- transition: transform 0.2s ease-in-out;
919
- }
920
-
921
- .collapser.open svg {
922
- transform: rotate(90deg);
923
- }
924
-
925
- .facet-group:not(:last-child) {
926
- margin-bottom: 2rem;
927
- }
928
-
929
- .facet-group h3 {
930
- margin-bottom: 0.7rem;
931
- }
932
-
933
- .facet-group.mobile h3 {
934
- cursor: pointer;
935
- }
936
-
937
- .facet-group-header {
938
- display: flex;
939
- margin-bottom: 0.7rem;
940
- justify-content: space-between;
941
- border-bottom: 1px solid rgb(232, 232, 232);
942
- }
943
-
944
- .facet-group-content {
945
- transition: max-height 0.2s ease-in-out;
946
- }
947
-
948
- .facet-group.mobile .facet-group-content {
949
- max-height: 0;
950
- overflow: hidden;
951
- }
952
-
953
- .facet-group.mobile .facet-group-content.open {
954
- max-height: 2000px;
955
- }
956
-
957
- .partof-collections ul {
958
- list-style-type: none;
959
- padding: 0;
960
- font-size: 1.2rem;
961
- }
962
-
963
- h3 {
964
- font-size: 1.4rem;
965
- margin: 0;
966
- }
967
-
968
- .more-link {
969
- font-size: 1.2rem;
970
- text-decoration: none;
971
- padding: 0;
972
- margin-top: 0.25rem;
973
- background: inherit;
974
- border: 0;
975
- color: var(--ia-theme-link-color, #4b64ff);
976
- cursor: pointer;
977
- }
978
-
979
- #date-picker-label {
980
- display: flex;
981
- justify-content: space-between;
982
- }
983
-
984
- .expand-date-picker-btn {
985
- margin: 0;
986
- padding: 0;
987
- border: 0;
988
- appearance: none;
989
- background: none;
990
- cursor: pointer;
991
- }
992
-
993
- .expand-date-picker-btn > svg {
994
- width: 14px;
995
- height: 14px;
996
- }
997
-
998
- .sorting-icon {
999
- height: 15px;
1000
- cursor: pointer;
1001
- }
1002
-
1003
- histogram-date-range.wide-inputs {
1004
- --histogramDateRangeInputWidth: 4.8rem;
1005
- }
1006
- `,
1007
- ];
1008
- }
1009
- }
1
+ import {
2
+ css,
3
+ html,
4
+ LitElement,
5
+ PropertyValues,
6
+ nothing,
7
+ TemplateResult,
8
+ } from 'lit';
9
+ import { customElement, property, state } from 'lit/decorators.js';
10
+ import { map } from 'lit/directives/map.js';
11
+ import { ref } from 'lit/directives/ref.js';
12
+ import { msg } from '@lit/localize';
13
+ import { classMap } from 'lit/directives/class-map.js';
14
+ import {
15
+ Aggregation,
16
+ AggregationSortType,
17
+ Bucket,
18
+ FilterMap,
19
+ SearchServiceInterface,
20
+ SearchType,
21
+ } from '@internetarchive/search-service';
22
+ import '@internetarchive/histogram-date-range';
23
+ import '@internetarchive/feature-feedback';
24
+ import {
25
+ ModalConfig,
26
+ ModalManagerInterface,
27
+ } from '@internetarchive/modal-manager';
28
+ import type { FeatureFeedbackServiceInterface } from '@internetarchive/feature-feedback';
29
+ import type { RecaptchaManagerInterface } from '@internetarchive/recaptcha-manager';
30
+ import type { AnalyticsManagerInterface } from '@internetarchive/analytics-manager';
31
+ import type { SharedResizeObserverInterface } from '@internetarchive/shared-resize-observer';
32
+ import type {
33
+ BarScalingOption,
34
+ BinSnappingInterval,
35
+ } from '@internetarchive/histogram-date-range';
36
+ import chevronIcon from './assets/img/icons/chevron';
37
+ import expandIcon from './assets/img/icons/expand';
38
+ import {
39
+ FacetOption,
40
+ SelectedFacets,
41
+ FacetGroup,
42
+ FacetBucket,
43
+ defaultFacetDisplayOrder,
44
+ facetTitles,
45
+ lendingFacetDisplayNames,
46
+ lendingFacetKeysVisibility,
47
+ LendingFacetKey,
48
+ suppressedCollections,
49
+ defaultFacetSort,
50
+ FacetEventDetails,
51
+ } from './models';
52
+ import type {
53
+ CollectionTitles,
54
+ PageSpecifierParams,
55
+ TVChannelAliases,
56
+ } from './data-source/models';
57
+ import {
58
+ analyticsActions,
59
+ analyticsCategories,
60
+ } from './utils/analytics-events';
61
+ import { srOnlyStyle } from './styles/sr-only';
62
+ import { ExpandedDatePicker } from './expanded-date-picker';
63
+ import {
64
+ sortBucketsBySelectionState,
65
+ updateSelectedFacetBucket,
66
+ } from './utils/facet-utils';
67
+
68
+ import '@internetarchive/histogram-date-range';
69
+ import './collection-facets/more-facets-content';
70
+ import './collection-facets/facets-template';
71
+ import './collection-facets/facet-tombstone-row';
72
+ import './expanded-date-picker';
73
+
74
+ @customElement('collection-facets')
75
+ export class CollectionFacets extends LitElement {
76
+ @property({ type: Object }) searchService?: SearchServiceInterface;
77
+
78
+ @property({ type: Number }) searchType?: SearchType;
79
+
80
+ @property({ type: Object }) aggregations?: Record<string, Aggregation>;
81
+
82
+ @property({ type: Object }) histogramAggregation?: Aggregation;
83
+
84
+ @property({ type: String }) minSelectedDate?: string;
85
+
86
+ @property({ type: String }) maxSelectedDate?: string;
87
+
88
+ @property({ type: Boolean }) moreLinksVisible = true;
89
+
90
+ @property({ type: Boolean }) facetsLoading = false;
91
+
92
+ @property({ type: Boolean }) histogramAggregationLoading = false;
93
+
94
+ @property({ type: Object }) selectedFacets?: SelectedFacets;
95
+
96
+ @property({ type: Boolean }) collapsableFacets = false;
97
+
98
+ @property({ type: Number }) contentWidth?: number;
99
+
100
+ @property({ type: Boolean }) showHistogramDatePicker = false;
101
+
102
+ @property({ type: Boolean }) allowExpandingDatePicker = false;
103
+
104
+ @property({ type: Boolean }) suppressMediatypeFacets = false;
105
+
106
+ @property({ type: String }) query?: string;
107
+
108
+ @property({ type: Array }) identifiers?: string[];
109
+
110
+ @property({ type: Object }) pageSpecifierParams?: PageSpecifierParams;
111
+
112
+ @property({ type: Array }) parentCollections: string[] = [];
113
+
114
+ @property({ type: Object }) filterMap?: FilterMap;
115
+
116
+ @property({ type: String }) baseNavigationUrl?: string;
117
+
118
+ @property({ type: String }) collectionPagePath: string = '/details/';
119
+
120
+ @property({ type: Boolean }) isManageView = false;
121
+
122
+ @property({ type: Boolean }) isTvSearch = false;
123
+
124
+ @property({ type: Array }) facetDisplayOrder: FacetOption[] =
125
+ defaultFacetDisplayOrder;
126
+
127
+ @property({ type: Object, attribute: false })
128
+ modalManager?: ModalManagerInterface;
129
+
130
+ @property({ type: Object, attribute: false })
131
+ resizeObserver?: SharedResizeObserverInterface;
132
+
133
+ @property({ type: Object, attribute: false })
134
+ featureFeedbackService?: FeatureFeedbackServiceInterface;
135
+
136
+ @property({ type: Object, attribute: false })
137
+ recaptchaManager?: RecaptchaManagerInterface;
138
+
139
+ @property({ type: Object, attribute: false })
140
+ analyticsHandler?: AnalyticsManagerInterface;
141
+
142
+ @property({ type: Object, attribute: false })
143
+ collectionTitles?: CollectionTitles;
144
+
145
+ @property({ type: Object, attribute: false })
146
+ tvChannelAliases?: TVChannelAliases;
147
+
148
+ @state() openFacets: Record<FacetOption, boolean> = {
149
+ subject: false,
150
+ lending: false,
151
+ mediatype: false,
152
+ language: false,
153
+ creator: false,
154
+ collection: false,
155
+ year: false,
156
+ program: false,
157
+ person: false,
158
+ sponsor: false,
159
+ };
160
+
161
+ /**
162
+ * Maximum # of facet buckets to render per facet group
163
+ */
164
+ private allowedFacetCount = 6;
165
+
166
+ render() {
167
+ const containerClasses = classMap({
168
+ loading: this.facetsLoading,
169
+ managing: this.isManageView,
170
+ });
171
+
172
+ // Added data-testid for Playwright testing
173
+ // Using facet-group class and aria-labels is not ideal for Playwright locator
174
+ const datePickerLabelId = 'date-picker-label';
175
+ return html`
176
+ <div id="container" class=${containerClasses}>
177
+ ${this.showHistogramDatePicker &&
178
+ (this.histogramAggregation || this.histogramAggregationLoading)
179
+ ? html`
180
+ <section
181
+ class="facet-group"
182
+ aria-labelledby=${datePickerLabelId}
183
+ data-testid="facet-group-header-label-date-picker"
184
+ >
185
+ <h3 id=${datePickerLabelId}>
186
+ Year Published <span class="sr-only">range filter</span>
187
+ ${this.expandDatePickerBtnTemplate}
188
+ </h3>
189
+ ${this.histogramTemplate}
190
+ </section>
191
+ `
192
+ : nothing}
193
+ ${this.collectionPartOfTemplate}
194
+ ${this.mergedFacets.map(facetGroup =>
195
+ this.getFacetGroupTemplate(facetGroup),
196
+ )}
197
+ </div>
198
+ `;
199
+ }
200
+
201
+ private get collectionPartOfTemplate(): TemplateResult | typeof nothing {
202
+ // We only display the "Part Of" section on collection pages
203
+ if (!this.parentCollections?.length) return nothing;
204
+
205
+ // Added data-testid for Playwright testing
206
+ // Using className and aria-labels is not ideal for Playwright locator
207
+ const headingId = 'partof-heading';
208
+ return html`
209
+ <section
210
+ class="facet-group partof-collections"
211
+ aria-labelledby=${headingId}
212
+ data-testid="facet-group-partof-collections"
213
+ >
214
+ <div class="facet-group-header">
215
+ <h3 id=${headingId}>${msg('Part Of')}</h3>
216
+ </div>
217
+ <ul>
218
+ ${map(this.parentCollections, collxn => {
219
+ const collectionURL = `${this.baseNavigationUrl}${this.collectionPagePath}${collxn}`;
220
+
221
+ return html` <li>
222
+ <a
223
+ href=${collectionURL}
224
+ data-id=${collxn}
225
+ @click=${this.partOfCollectionClicked}
226
+ >
227
+ ${this.collectionTitles?.get(collxn) ?? collxn}
228
+ </a>
229
+ </li>`;
230
+ })}
231
+ </ul>
232
+ </section>
233
+ `;
234
+ }
235
+
236
+ private partOfCollectionClicked(e: Event): void {
237
+ this.analyticsHandler?.sendEvent({
238
+ category: analyticsCategories.default,
239
+ action: analyticsActions.partOfCollectionClicked,
240
+ label: (e.target as HTMLElement).dataset.id,
241
+ });
242
+ }
243
+
244
+ /**
245
+ * Properties to pass into the date-picker histogram component
246
+ */
247
+ private get histogramProps() {
248
+ const { histogramAggregation: aggregation } = this;
249
+ if (!aggregation) return undefined;
250
+
251
+ // Normalize some properties from the raw aggregation
252
+ const firstYear =
253
+ aggregation.first_bucket_year ?? aggregation.first_bucket_key;
254
+ const lastYear =
255
+ aggregation.last_bucket_year ?? aggregation.last_bucket_key;
256
+ if (firstYear == null || lastYear == null) return undefined; // We at least need a start/end year defined
257
+
258
+ const firstMonth = aggregation.first_bucket_month ?? 1;
259
+ const lastMonth = aggregation.last_bucket_month ?? 12;
260
+
261
+ const yearInterval = aggregation.interval ?? 1;
262
+ const monthInterval = aggregation.interval_in_months ?? 12;
263
+
264
+ const zeroPadMonth = (month: number) => month.toString().padStart(2, '0');
265
+
266
+ // The date picker is configured differently for TV search, allowing month-level resolution
267
+ if (this.isTvSearch) {
268
+ // Whether the bucket interval is less than a year
269
+ // (i.e., requires individual months to be handled & labeled)
270
+ const mustHandleMonths = monthInterval < 12;
271
+
272
+ return {
273
+ buckets: aggregation.buckets as number[],
274
+ dateFormat: 'YYYY-MM',
275
+ tooltipDateFormat: mustHandleMonths ? 'MMM YYYY' : 'YYYY',
276
+ tooltipLabel: 'broadcast',
277
+ binSnapping: (mustHandleMonths
278
+ ? 'month'
279
+ : 'year') as BinSnappingInterval,
280
+ barScaling: 'linear' as BarScalingOption,
281
+ minDate: `${firstYear}-${zeroPadMonth(firstMonth)}`,
282
+ maxDate: `${lastYear}-${zeroPadMonth(lastMonth + monthInterval - 1)}`,
283
+ };
284
+ }
285
+
286
+ // All other search types use the same configuration
287
+ return {
288
+ buckets: aggregation.buckets as number[],
289
+ dateFormat: 'YYYY',
290
+ tooltipDateFormat: 'YYYY',
291
+ tooltipLabel: 'item',
292
+ binSnapping: 'year' as BinSnappingInterval,
293
+ barScaling: 'logarithmic' as BarScalingOption,
294
+ minDate: `${firstYear}`,
295
+ maxDate: `${lastYear + yearInterval - 1}`,
296
+ };
297
+ }
298
+
299
+ /**
300
+ * Opens a modal dialog containing an enlarged version of the date picker.
301
+ */
302
+ private showDatePickerModal(): void {
303
+ const { histogramProps } = this;
304
+ if (!histogramProps) return;
305
+
306
+ const {
307
+ buckets,
308
+ dateFormat,
309
+ tooltipDateFormat,
310
+ tooltipLabel,
311
+ binSnapping,
312
+ barScaling,
313
+ minDate,
314
+ maxDate,
315
+ } = histogramProps;
316
+
317
+ // Because the modal manager does not clear its DOM content after being closed,
318
+ // it may try to render the exact same date picker template when it is reopened.
319
+ // And because it isn't actually a descendent of this collection-facets component,
320
+ // changes to the template defined here may not trigger a reactive update to the date
321
+ // picker, resulting in it displaying a stale date range.
322
+ // This ref callback ensures that every time the date picker modal is opened, it will
323
+ // always propagate the most recent date range into the date picker regardless of
324
+ // whether Lit thinks the update is necessary.
325
+ const expandedDatePickerChanged = (elmt?: Element) => {
326
+ if (elmt && elmt instanceof ExpandedDatePicker) {
327
+ const expandedDatePicker = elmt as ExpandedDatePicker;
328
+ expandedDatePicker.minSelectedDate = this.minSelectedDate;
329
+ expandedDatePicker.maxSelectedDate = this.maxSelectedDate;
330
+ }
331
+ };
332
+
333
+ const customModalContent = html`
334
+ <expanded-date-picker
335
+ ${ref(expandedDatePickerChanged)}
336
+ .minDate=${minDate}
337
+ .maxDate=${maxDate}
338
+ .minSelectedDate=${this.minSelectedDate}
339
+ .maxSelectedDate=${this.maxSelectedDate}
340
+ .customDateFormat=${dateFormat}
341
+ .customTooltipDateFormat=${tooltipDateFormat}
342
+ .customTooltipLabel=${tooltipLabel}
343
+ .binSnapping=${binSnapping}
344
+ .barScaling=${barScaling}
345
+ .buckets=${buckets}
346
+ .modalManager=${this.modalManager}
347
+ .analyticsHandler=${this.analyticsHandler}
348
+ @histogramDateRangeApplied=${this.histogramDateRangeUpdated}
349
+ @modalClosed=${this.handleExpandedDatePickerClosed}
350
+ ></expanded-date-picker>
351
+ `;
352
+
353
+ const config = new ModalConfig({
354
+ bodyColor: '#fff',
355
+ headerColor: '#194880',
356
+ showHeaderLogo: false,
357
+ closeOnBackdropClick: true, // TODO: want to fire analytics
358
+ title: html`${msg('Select a date range')}`,
359
+ });
360
+
361
+ this.modalManager?.classList.add('expanded-date-picker');
362
+ this.modalManager?.showModal({
363
+ config,
364
+ customModalContent,
365
+ userClosedModalCallback: this.handleExpandedDatePickerClosed,
366
+ });
367
+
368
+ this.analyticsHandler?.sendEvent({
369
+ category: analyticsCategories.default,
370
+ action: analyticsActions.histogramExpanded,
371
+ label: window.location.href,
372
+ });
373
+ }
374
+
375
+ private handleExpandedDatePickerClosed = (): void => {
376
+ this.modalManager?.classList.remove('expanded-date-picker');
377
+ };
378
+
379
+ updated(changed: PropertyValues) {
380
+ if (changed.has('selectedFacets')) {
381
+ this.dispatchFacetsChangedEvent();
382
+ }
383
+ }
384
+
385
+ // TODO: want to fire analytics?
386
+ private dispatchFacetsChangedEvent() {
387
+ const event = new CustomEvent<SelectedFacets>('facetsChanged', {
388
+ detail: this.selectedFacets,
389
+ });
390
+ this.dispatchEvent(event);
391
+ }
392
+
393
+ /**
394
+ * Template for the "Expand" button to show the date picker modal, or
395
+ * `nothing` if that button should currently not be shown.
396
+ */
397
+ private get expandDatePickerBtnTemplate(): TemplateResult | typeof nothing {
398
+ return this.allowExpandingDatePicker && !this.facetsLoading
399
+ ? html`<button
400
+ class="expand-date-picker-btn"
401
+ aria-haspopup="dialog"
402
+ @click=${this.showDatePickerModal}
403
+ >
404
+ <span class="sr-only">${msg('Expand date histogram')}</span>
405
+ <span aria-hidden="true">${expandIcon}</span>
406
+ </button>`
407
+ : nothing;
408
+ }
409
+
410
+ private get histogramTemplate(): TemplateResult | typeof nothing {
411
+ if (this.histogramAggregationLoading) {
412
+ return html` <div class="histogram-loading-indicator">&hellip;</div> `;
413
+ }
414
+
415
+ const { histogramProps } = this;
416
+ if (!histogramProps) return nothing;
417
+
418
+ const {
419
+ buckets,
420
+ dateFormat,
421
+ tooltipDateFormat,
422
+ tooltipLabel,
423
+ binSnapping,
424
+ barScaling,
425
+ minDate,
426
+ maxDate,
427
+ } = histogramProps;
428
+
429
+ return html`
430
+ <histogram-date-range
431
+ class=${this.isTvSearch ? 'wide-inputs' : ''}
432
+ .minDate=${minDate}
433
+ .maxDate=${maxDate}
434
+ .minSelectedDate=${this.minSelectedDate ?? minDate}
435
+ .maxSelectedDate=${this.maxSelectedDate ?? maxDate}
436
+ .updateDelay=${100}
437
+ .dateFormat=${dateFormat}
438
+ .tooltipDateFormat=${tooltipDateFormat}
439
+ .tooltipLabel=${tooltipLabel}
440
+ .binSnapping=${binSnapping}
441
+ .barScaling=${barScaling}
442
+ .bins=${buckets}
443
+ missingDataMessage="..."
444
+ .width=${this.collapsableFacets && this.contentWidth
445
+ ? this.contentWidth
446
+ : 180}
447
+ @histogramDateRangeUpdated=${this.histogramDateRangeUpdated}
448
+ ></histogram-date-range>
449
+ `;
450
+ }
451
+
452
+ /**
453
+ * Dispatches a `histogramDateRangeUpdated` event with the date range copied from the
454
+ * input event.
455
+ *
456
+ * Arrow function to ensure `this` is always bound to the current component.
457
+ */
458
+ private histogramDateRangeUpdated = (
459
+ e: CustomEvent<{
460
+ minDate: string;
461
+ maxDate: string;
462
+ }>,
463
+ ): void => {
464
+ const { minDate, maxDate } = e.detail;
465
+ const event = new CustomEvent('histogramDateRangeUpdated', {
466
+ detail: { minDate, maxDate },
467
+ });
468
+ this.dispatchEvent(event);
469
+ };
470
+
471
+ /**
472
+ * Combines the selected facets with the aggregations to create a single list of facets
473
+ */
474
+ private get mergedFacets(): FacetGroup[] {
475
+ const facetGroups: FacetGroup[] = [];
476
+
477
+ this.facetDisplayOrder.forEach(facetKey => {
478
+ if (facetKey === 'mediatype' && this.suppressMediatypeFacets) return;
479
+
480
+ const selectedFacetGroup = this.selectedFacetGroups.find(
481
+ group => group.key === facetKey,
482
+ );
483
+ const aggregateFacetGroup = this.aggregationFacetGroups.find(
484
+ group => group.key === facetKey,
485
+ );
486
+
487
+ // if the user selected a facet, but it's not in the aggregation, we add it as-is
488
+ if (selectedFacetGroup && !aggregateFacetGroup) {
489
+ facetGroups.push(selectedFacetGroup);
490
+ return;
491
+ }
492
+
493
+ // if we don't have an aggregate facet group, don't add this to the list
494
+ if (!aggregateFacetGroup) return;
495
+
496
+ // start with either the selected group if we have one, or the aggregate group
497
+ const facetGroup = selectedFacetGroup ?? aggregateFacetGroup;
498
+
499
+ // attach the counts to the selected buckets
500
+ let bucketsWithCount =
501
+ selectedFacetGroup?.buckets.map(bucket => {
502
+ const selectedBucket = aggregateFacetGroup.buckets.find(
503
+ b => b.key === bucket.key,
504
+ );
505
+ return selectedBucket
506
+ ? {
507
+ ...bucket,
508
+ count: selectedBucket.count,
509
+ }
510
+ : bucket;
511
+ }) ?? [];
512
+
513
+ // append any additional buckets that were not selected
514
+ aggregateFacetGroup.buckets.forEach(bucket => {
515
+ const existingBucket = bucketsWithCount.find(b => b.key === bucket.key);
516
+ if (existingBucket) return;
517
+ bucketsWithCount.push(bucket);
518
+ });
519
+
520
+ /**
521
+ * render limited facet items on page facet area
522
+ *
523
+ * - by-default we are showing 6 items
524
+ * - additionally want to show all items (selected/suppressed) in page facet area
525
+ */
526
+ let allowedFacetCount = Object.keys(
527
+ (selectedFacetGroup?.buckets as []) || [],
528
+ )?.length;
529
+ if (allowedFacetCount < this.allowedFacetCount) {
530
+ allowedFacetCount = this.allowedFacetCount; // splice start index from 0th
531
+ }
532
+
533
+ // For lending facets, only include a specific subset of buckets
534
+ if (facetKey === 'lending') {
535
+ bucketsWithCount = bucketsWithCount.filter(
536
+ bucket => lendingFacetKeysVisibility[bucket.key as LendingFacetKey],
537
+ );
538
+ }
539
+
540
+ // Sort the FacetBuckets so that selected and hidden buckets come before the rest
541
+ sortBucketsBySelectionState(bucketsWithCount, defaultFacetSort[facetKey]);
542
+
543
+ // For mediatype facets, ensure the collection bucket is always shown if present
544
+ if (facetKey === 'mediatype') {
545
+ const collectionIndex = bucketsWithCount.findIndex(
546
+ bucket => bucket.key === 'collection',
547
+ );
548
+
549
+ if (collectionIndex >= allowedFacetCount) {
550
+ const [collectionBucket] = bucketsWithCount.splice(
551
+ collectionIndex,
552
+ 1,
553
+ );
554
+
555
+ // If we're showing lots of selected facets, ensure we're not cutting off the last one
556
+ if (allowedFacetCount > this.allowedFacetCount) {
557
+ allowedFacetCount += 1;
558
+ }
559
+
560
+ bucketsWithCount.splice(allowedFacetCount - 1, 0, collectionBucket);
561
+ }
562
+ }
563
+
564
+ // For TV creator facets, uppercase the display text
565
+ if (facetKey === 'creator' && this.isTvSearch) {
566
+ bucketsWithCount.forEach(b => {
567
+ b.displayText = (b.displayText ?? b.key)?.toLocaleUpperCase();
568
+
569
+ const channelLabel = this.tvChannelAliases?.get(b.displayText);
570
+ if (channelLabel && channelLabel !== b.displayText) {
571
+ b.extraNote = `(${channelLabel})`;
572
+ }
573
+ });
574
+ }
575
+
576
+ // slice off how many items we want to show in page facet area
577
+ facetGroup.buckets = bucketsWithCount.slice(0, allowedFacetCount);
578
+
579
+ facetGroups.push(facetGroup);
580
+ });
581
+
582
+ return facetGroups;
583
+ }
584
+
585
+ /**
586
+ * Converts the selected facets to a `FacetGroup` array,
587
+ * which is easier to work with
588
+ */
589
+ private get selectedFacetGroups(): FacetGroup[] {
590
+ if (!this.selectedFacets) return [];
591
+
592
+ const facetGroups: FacetGroup[] = Object.entries(this.selectedFacets).map(
593
+ ([key, selectedFacets]) => {
594
+ const option = key as FacetOption;
595
+ const title = facetTitles[option];
596
+
597
+ const buckets: FacetBucket[] = Object.entries(selectedFacets).map(
598
+ ([value, facetData]) => {
599
+ let displayText: string = value;
600
+ // for lending facets, convert the key to a readable format
601
+ if (option === 'lending') {
602
+ displayText =
603
+ lendingFacetDisplayNames[value as LendingFacetKey] ?? value;
604
+ }
605
+ return {
606
+ displayText,
607
+ key: value,
608
+ count: facetData.count,
609
+ state: facetData.state,
610
+ };
611
+ },
612
+ );
613
+
614
+ return {
615
+ title,
616
+ key: option,
617
+ buckets,
618
+ };
619
+ },
620
+ );
621
+
622
+ return facetGroups;
623
+ }
624
+
625
+ /**
626
+ * Converts the raw `aggregations` to `FacetGroups`, which are easier to use
627
+ */
628
+ private get aggregationFacetGroups(): FacetGroup[] {
629
+ const facetGroups: FacetGroup[] = [];
630
+ Object.entries(this.aggregations ?? []).forEach(([key, aggregation]) => {
631
+ // the year_histogram and date_histogram data is in a different format so can't be handled here
632
+ if (['year_histogram', 'date_histogram'].includes(key)) return;
633
+
634
+ const option = key as FacetOption;
635
+ const title = facetTitles[option];
636
+ if (!title) return;
637
+
638
+ let castedBuckets = aggregation.getSortedBuckets(
639
+ defaultFacetSort[option],
640
+ ) as Bucket[];
641
+
642
+ if (option === 'collection') {
643
+ // we are not showing fav- collections or certain deemphasized collections in facets
644
+ castedBuckets = castedBuckets?.filter(bucket => {
645
+ const bucketKey = bucket?.key?.toString();
646
+ return (
647
+ !suppressedCollections[bucketKey] && !bucketKey?.startsWith('fav-')
648
+ );
649
+ });
650
+ }
651
+
652
+ const facetBuckets: FacetBucket[] = castedBuckets.map(bucket => {
653
+ const bucketKey = bucket.key;
654
+ let displayText = `${bucket.key}`;
655
+ // for lending facets, convert the bucket key to a readable format
656
+ if (option === 'lending') {
657
+ displayText =
658
+ lendingFacetDisplayNames[bucket.key as LendingFacetKey] ??
659
+ `${bucket.key}`;
660
+ }
661
+ return {
662
+ displayText,
663
+ key: `${bucketKey}`,
664
+ count: bucket.doc_count,
665
+ state: 'none',
666
+ };
667
+ });
668
+ const group: FacetGroup = {
669
+ title,
670
+ key: option,
671
+ buckets: facetBuckets,
672
+ };
673
+ facetGroups.push(group);
674
+ });
675
+ return facetGroups;
676
+ }
677
+
678
+ /**
679
+ * Generate the template for a facet group with a header and the collapsible
680
+ * chevron for the mobile view
681
+ */
682
+ private getFacetGroupTemplate(
683
+ facetGroup: FacetGroup,
684
+ ): TemplateResult | typeof nothing {
685
+ if (!this.facetsLoading && facetGroup.buckets.length === 0) return nothing;
686
+
687
+ const { key } = facetGroup;
688
+ const isOpen = this.openFacets[key];
689
+ const collapser = html`
690
+ <span class="collapser ${isOpen ? 'open' : ''}"> ${chevronIcon} </span>
691
+ `;
692
+
693
+ const toggleCollapsed = () => {
694
+ const newOpenFacets = { ...this.openFacets };
695
+ newOpenFacets[key] = !isOpen;
696
+ this.openFacets = newOpenFacets;
697
+ };
698
+
699
+ // Added data-testid for Playwright testing
700
+ // Using className and aria-labels is not ideal for Playwright locator
701
+ const headerId = `facet-group-header-label-${facetGroup.key}`;
702
+ return html`
703
+ <section
704
+ class="facet-group ${this.collapsableFacets ? 'mobile' : ''}"
705
+ aria-labelledby=${headerId}
706
+ data-testid=${headerId}
707
+ >
708
+ <div class="facet-group-header">
709
+ <h3
710
+ id=${headerId}
711
+ @click=${toggleCollapsed}
712
+ @keyup=${toggleCollapsed}
713
+ >
714
+ ${this.collapsableFacets ? collapser : nothing} ${facetGroup.title}
715
+ <span class="sr-only">filters</span>
716
+ </h3>
717
+ </div>
718
+ <div
719
+ class="facet-group-content ${isOpen ? 'open' : ''}"
720
+ data-testid="facet-group-content-${facetGroup.key}"
721
+ >
722
+ ${this.facetsLoading
723
+ ? this.getTombstoneFacetGroupTemplate()
724
+ : html`
725
+ ${this.getFacetTemplate(facetGroup)}
726
+ ${this.searchMoreFacetsLink(facetGroup)}
727
+ `}
728
+ </div>
729
+ </section>
730
+ `;
731
+ }
732
+
733
+ private getTombstoneFacetGroupTemplate(): TemplateResult {
734
+ // Render five tombstone rows
735
+ return html`
736
+ ${map(
737
+ Array(5).fill(null),
738
+ () => html`<facet-tombstone-row></facet-tombstone-row>`,
739
+ )}
740
+ `;
741
+ }
742
+
743
+ /**
744
+ * Generate the More... link button just below the facets group
745
+ *
746
+ * TODO: want to fire analytics?
747
+ */
748
+ private searchMoreFacetsLink(
749
+ facetGroup: FacetGroup,
750
+ ): TemplateResult | typeof nothing {
751
+ // Don't render More... links for FTS searches
752
+ if (!this.moreLinksVisible) {
753
+ return nothing;
754
+ }
755
+
756
+ // Don't render More... links for lending facets
757
+ if (facetGroup.key === 'lending') {
758
+ return nothing;
759
+ }
760
+
761
+ // Don't render More... link if the number of facets < this.allowedFacetCount
762
+ if (Object.keys(facetGroup.buckets).length < this.allowedFacetCount) {
763
+ return nothing;
764
+ }
765
+
766
+ // We sort years in numeric order by default, rather than bucket count
767
+ const facetSort = defaultFacetSort[facetGroup.key];
768
+
769
+ // Added data-testid for Playwright testing
770
+ // Using the className is not ideal for Playwright locator
771
+ return html`<button
772
+ class="more-link"
773
+ @click=${() => {
774
+ this.showMoreFacetsModal(facetGroup, facetSort);
775
+ this.analyticsHandler?.sendEvent({
776
+ category: analyticsCategories.default,
777
+ action: analyticsActions.showMoreFacetsModal,
778
+ label: facetGroup.key,
779
+ });
780
+ this.dispatchEvent(
781
+ new CustomEvent('showMoreFacets', { detail: facetGroup.key }),
782
+ );
783
+ }}
784
+ data-testid="more-link-btn"
785
+ >
786
+ More...
787
+ </button>`;
788
+ }
789
+
790
+ async showMoreFacetsModal(
791
+ facetGroup: FacetGroup,
792
+ sortedBy: AggregationSortType,
793
+ ): Promise<void> {
794
+ const customModalContent = html`
795
+ <more-facets-content
796
+ .analyticsHandler=${this.analyticsHandler}
797
+ .facetKey=${facetGroup.key}
798
+ .query=${this.query}
799
+ .identifiers=${this.identifiers}
800
+ .filterMap=${this.filterMap}
801
+ .pageSpecifierParams=${this.pageSpecifierParams}
802
+ .modalManager=${this.modalManager}
803
+ .searchService=${this.searchService}
804
+ .searchType=${this.searchType}
805
+ .collectionTitles=${this.collectionTitles}
806
+ .tvChannelAliases=${this.tvChannelAliases}
807
+ .selectedFacets=${this.selectedFacets}
808
+ .sortedBy=${sortedBy}
809
+ .isTvSearch=${this.isTvSearch}
810
+ @facetsChanged=${(e: CustomEvent) => {
811
+ const event = new CustomEvent<SelectedFacets>('facetsChanged', {
812
+ detail: e.detail,
813
+ bubbles: true,
814
+ composed: true,
815
+ });
816
+ this.dispatchEvent(event);
817
+ }}
818
+ >
819
+ </more-facets-content>
820
+ `;
821
+
822
+ const config = new ModalConfig({
823
+ bodyColor: '#fff',
824
+ headerColor: '#194880',
825
+ showHeaderLogo: false,
826
+ closeOnBackdropClick: true, // TODO: want to fire analytics
827
+ title: html`Select filters`,
828
+ });
829
+ this.modalManager?.classList.add('more-search-facets');
830
+ this.modalManager?.showModal({
831
+ config,
832
+ customModalContent,
833
+ userClosedModalCallback: () => {
834
+ this.modalManager?.classList.remove('more-search-facets');
835
+ },
836
+ });
837
+ }
838
+
839
+ /**
840
+ * Generate the list template for each bucket in a facet group
841
+ */
842
+ private getFacetTemplate(facetGroup: FacetGroup): TemplateResult {
843
+ return html`
844
+ <facets-template
845
+ .collectionPagePath=${this.collectionPagePath}
846
+ .facetGroup=${facetGroup}
847
+ .selectedFacets=${this.selectedFacets}
848
+ .collectionTitles=${this.collectionTitles}
849
+ @facetClick=${(e: CustomEvent<FacetEventDetails>) => {
850
+ this.selectedFacets = updateSelectedFacetBucket(
851
+ this.selectedFacets,
852
+ facetGroup.key,
853
+ e.detail.bucket,
854
+ true,
855
+ );
856
+
857
+ const event = new CustomEvent<SelectedFacets>('facetsChanged', {
858
+ detail: this.selectedFacets,
859
+ bubbles: true,
860
+ composed: true,
861
+ });
862
+ this.dispatchEvent(event);
863
+ }}
864
+ ></facets-template>
865
+ `;
866
+ }
867
+
868
+ static get styles() {
869
+ return [
870
+ srOnlyStyle,
871
+ css`
872
+ a:link {
873
+ text-decoration: none;
874
+ color: var(--ia-theme-link-color, #4b64ff);
875
+ }
876
+ a:link:hover {
877
+ text-decoration: underline;
878
+ }
879
+
880
+ #container.loading {
881
+ opacity: 0.5;
882
+ }
883
+
884
+ #container.managing {
885
+ opacity: 0.3;
886
+ }
887
+
888
+ .histogram-loading-indicator {
889
+ width: 100%;
890
+ height: 2.25rem;
891
+ margin-top: 1.75rem;
892
+ font-size: 1.4rem;
893
+ text-align: center;
894
+ }
895
+
896
+ .collapser {
897
+ display: inline-block;
898
+ cursor: pointer;
899
+ width: 10px;
900
+ height: 10px;
901
+ }
902
+
903
+ .collapser svg {
904
+ transition: transform 0.2s ease-in-out;
905
+ }
906
+
907
+ .collapser.open svg {
908
+ transform: rotate(90deg);
909
+ }
910
+
911
+ .facet-group:not(:last-child) {
912
+ margin-bottom: 2rem;
913
+ }
914
+
915
+ .facet-group h3 {
916
+ margin-bottom: 0.7rem;
917
+ }
918
+
919
+ .facet-group.mobile h3 {
920
+ cursor: pointer;
921
+ }
922
+
923
+ .facet-group-header {
924
+ display: flex;
925
+ margin-bottom: 0.7rem;
926
+ justify-content: space-between;
927
+ border-bottom: 1px solid rgb(232, 232, 232);
928
+ }
929
+
930
+ .facet-group-content {
931
+ transition: max-height 0.2s ease-in-out;
932
+ }
933
+
934
+ .facet-group.mobile .facet-group-content {
935
+ max-height: 0;
936
+ overflow: hidden;
937
+ }
938
+
939
+ .facet-group.mobile .facet-group-content.open {
940
+ max-height: 2000px;
941
+ }
942
+
943
+ .partof-collections ul {
944
+ list-style-type: none;
945
+ padding: 0;
946
+ font-size: 1.2rem;
947
+ }
948
+
949
+ h3 {
950
+ font-size: 1.4rem;
951
+ margin: 0;
952
+ }
953
+
954
+ .more-link {
955
+ font-size: 1.2rem;
956
+ text-decoration: none;
957
+ padding: 0;
958
+ margin-top: 0.25rem;
959
+ background: inherit;
960
+ border: 0;
961
+ color: var(--ia-theme-link-color, #4b64ff);
962
+ cursor: pointer;
963
+ }
964
+
965
+ #date-picker-label {
966
+ display: flex;
967
+ justify-content: space-between;
968
+ }
969
+
970
+ .expand-date-picker-btn {
971
+ margin: 0;
972
+ padding: 0;
973
+ border: 0;
974
+ appearance: none;
975
+ background: none;
976
+ cursor: pointer;
977
+ }
978
+
979
+ .expand-date-picker-btn svg {
980
+ width: 14px;
981
+ height: 14px;
982
+ }
983
+
984
+ .sorting-icon {
985
+ height: 15px;
986
+ cursor: pointer;
987
+ }
988
+
989
+ histogram-date-range.wide-inputs {
990
+ --histogramDateRangeInputWidth: 4.8rem;
991
+ }
992
+ `,
993
+ ];
994
+ }
995
+ }