@internetarchive/collection-browser 3.5.2 → 3.5.3

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