@internetarchive/collection-browser 3.3.4-alpha-webdev7761.3 → 3.3.4-alpha-webdev7761.4

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