@internetarchive/collection-browser 3.4.1-alpha-webdev7761.4 → 3.4.1

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