@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,546 +1,544 @@
1
- import { SearchType, SortDirection } from '@internetarchive/search-service';
2
- import { getCookie, setCookie } from 'typescript-cookie';
3
- import {
4
- FacetOption,
5
- CollectionBrowserContext,
6
- CollectionDisplayMode,
7
- SelectedFacets,
8
- SortField,
9
- FacetBucket,
10
- FacetState,
11
- getDefaultSelectedFacets,
12
- sortOptionFromAPIString,
13
- SORT_OPTIONS,
14
- tvClipURLParamsToFilters,
15
- } from './models';
16
- import { arrayEquals } from './utils/array-equals';
17
-
18
- export interface RestorationState {
19
- displayMode?: CollectionDisplayMode;
20
- searchType?: SearchType;
21
- selectedSort?: SortField;
22
- sortDirection?: SortDirection;
23
- selectedFacets: SelectedFacets;
24
- baseQuery?: string;
25
- currentPage?: number;
26
- titleQuery?: string;
27
- creatorQuery?: string;
28
- minSelectedDate?: string;
29
- maxSelectedDate?: string;
30
- selectedTitleFilter?: string;
31
- selectedCreatorFilter?: string;
32
- }
33
-
34
- export interface RestorationStatePersistOptions {
35
- forceReplace?: boolean;
36
- persistMetadataSearchType?: boolean;
37
- }
38
-
39
- export interface RestorationStateHandlerInterface {
40
- persistState(
41
- state: RestorationState,
42
- options?: RestorationStatePersistOptions,
43
- ): void;
44
- getRestorationState(): RestorationState;
45
- }
46
-
47
- export class RestorationStateHandler
48
- implements RestorationStateHandlerInterface
49
- {
50
- private context: CollectionBrowserContext;
51
-
52
- private cookieDomain = '.archive.org';
53
-
54
- private cookieExpiration = 30;
55
-
56
- private cookiePath = '/';
57
-
58
- constructor(options: { context: CollectionBrowserContext }) {
59
- this.context = options.context;
60
- }
61
-
62
- persistState(
63
- state: RestorationState,
64
- options: RestorationStatePersistOptions = {},
65
- ): void {
66
- if (state.displayMode) this.persistViewStateToCookies(state.displayMode);
67
- this.persistQueryStateToUrl(state, options);
68
- }
69
-
70
- getRestorationState(): RestorationState {
71
- const restorationState = this.loadQueryStateFromUrl();
72
- const displayMode = this.loadTileViewStateFromCookies();
73
- restorationState.displayMode = displayMode;
74
- return restorationState;
75
- }
76
-
77
- private persistViewStateToCookies(displayMode: CollectionDisplayMode) {
78
- const gridState = displayMode === 'grid' ? 'tiles' : 'lists';
79
- setCookie(`view-${this.context}`, gridState, {
80
- domain: this.cookieDomain,
81
- expires: this.cookieExpiration,
82
- path: this.cookiePath,
83
- });
84
- const detailsState = displayMode === 'list-detail' ? 'showdetails' : '';
85
- setCookie(`showdetails-${this.context}`, detailsState, {
86
- domain: this.cookieDomain,
87
- expires: this.cookieExpiration,
88
- path: this.cookiePath,
89
- });
90
- }
91
-
92
- private loadTileViewStateFromCookies(): CollectionDisplayMode {
93
- const viewState = getCookie(`view-${this.context}`);
94
- const detailsState = getCookie(`showdetails-${this.context}`);
95
- if (viewState === 'tiles' || viewState === undefined) return 'grid';
96
- if (detailsState === 'showdetails') return 'list-detail';
97
- return 'list-compact';
98
- }
99
-
100
- private persistQueryStateToUrl(
101
- state: RestorationState,
102
- options: RestorationStatePersistOptions = {},
103
- ) {
104
- const url = new URL(window.location.href);
105
- const oldParams = new URLSearchParams(url.searchParams);
106
- const newParams = this.removeRecognizedParams(url.searchParams);
107
-
108
- let replaceEmptySin = false;
109
-
110
- if (state.baseQuery) {
111
- newParams.set('query', state.baseQuery);
112
- }
113
-
114
- switch (state.searchType) {
115
- case SearchType.FULLTEXT:
116
- newParams.set('sin', 'TXT');
117
- break;
118
- case SearchType.RADIO:
119
- newParams.set('sin', 'RADIO');
120
- break;
121
- case SearchType.TV:
122
- newParams.set('sin', 'TV');
123
- break;
124
- case SearchType.METADATA:
125
- // Only write the param for metadata when it isn't already the default.
126
- // Currently this is only the case within TV collections.
127
- if (options.persistMetadataSearchType || oldParams.get('sin') === 'MD')
128
- newParams.set('sin', 'MD');
129
- break;
130
- }
131
-
132
- if (oldParams.get('sin') === '') {
133
- // Treat empty sin the same as no sin at all
134
- oldParams.delete('sin');
135
- replaceEmptySin = true;
136
- }
137
-
138
- if (state.currentPage) {
139
- if (state.currentPage > 1) {
140
- newParams.set('page', state.currentPage.toString());
141
- } else {
142
- newParams.delete('page');
143
- }
144
- }
145
-
146
- if (state.selectedSort) {
147
- const sortOption = SORT_OPTIONS[state.selectedSort];
148
- let prefix = this.sortDirectionPrefix(state.sortDirection);
149
-
150
- const isTVRelevanceSort =
151
- state.searchType === SearchType.TV &&
152
- state.selectedSort === SortField.relevance;
153
-
154
- if (sortOption.field === SortField.unrecognized) {
155
- // For unrecognized sorts, use the existing param, possibly updating its direction
156
- const oldSortParam = oldParams.get('sort') ?? '';
157
- const { field, direction } =
158
- this.getSortFieldAndDirection(oldSortParam);
159
-
160
- // Use the state-specified direction if available, or extract one from the param if not
161
- if (!state.sortDirection) prefix = this.sortDirectionPrefix(direction);
162
-
163
- if (field) {
164
- newParams.set('sort', `${prefix}${field}`);
165
- } else {
166
- newParams.set('sort', oldSortParam);
167
- }
168
- } else if (sortOption.shownInURL || isTVRelevanceSort) {
169
- // Otherwise, use the canonical API form of the sort option
170
- const canonicalApiSort = sortOption.urlNames[0];
171
- newParams.set('sort', `${prefix}${canonicalApiSort}`);
172
- }
173
- }
174
-
175
- if (state.selectedFacets) {
176
- for (const [facetName, facetValues] of Object.entries(
177
- state.selectedFacets,
178
- )) {
179
- const facetEntries = Object.entries(facetValues);
180
- if (facetEntries.length === 0) continue;
181
- for (const [key, data] of facetEntries) {
182
- const notValue = data.state === 'hidden';
183
- const paramValue = `${facetName}:"${key}"`;
184
- if (notValue) {
185
- newParams.append('not[]', paramValue);
186
- } else {
187
- newParams.append('and[]', paramValue);
188
- }
189
- }
190
- }
191
- }
192
-
193
- const dateField =
194
- state.minSelectedDate?.includes('-') ||
195
- state.maxSelectedDate?.includes('-')
196
- ? 'date'
197
- : 'year';
198
-
199
- if (state.minSelectedDate && state.maxSelectedDate) {
200
- newParams.append(
201
- 'and[]',
202
- `${dateField}:[${state.minSelectedDate} TO ${state.maxSelectedDate}]`,
203
- );
204
- }
205
-
206
- if (state.titleQuery) {
207
- newParams.append('and[]', state.titleQuery);
208
- }
209
-
210
- if (state.creatorQuery) {
211
- newParams.append('and[]', state.creatorQuery);
212
- }
213
-
214
- // Ensure we aren't pushing consecutive identical states to the history stack.
215
- // - If the state has changed, we push a new history entry.
216
- // - If only the page number has changed, we replace the current history entry.
217
- // - If the state hasn't changed, then do nothing.
218
- let historyMethod: 'pushState' | 'replaceState' = options.forceReplace
219
- ? 'replaceState'
220
- : 'pushState';
221
- const nonQueryParamsMatch = this.paramsMatch(oldParams, newParams, [
222
- 'sin',
223
- 'sort',
224
- 'and[]',
225
- 'not[]',
226
- 'only_commercials',
227
- 'only_factchecks',
228
- 'only_quotes',
229
- ]);
230
-
231
- if (
232
- nonQueryParamsMatch &&
233
- this.paramsMatch(oldParams, newParams, ['query'])
234
- ) {
235
- if (replaceEmptySin) {
236
- // Get rid of any empty sin param
237
- newParams.delete('sin');
238
- } else if (this.paramsMatch(oldParams, newParams, ['page'])) {
239
- // For page number, we want to replace the page state when it changes,
240
- // not push a new history entry. If it hasn't changed, then we're done.
241
- return;
242
- }
243
- historyMethod = 'replaceState';
244
- } else if (nonQueryParamsMatch && this.hasLegacyParam(oldParams)) {
245
- // Similarly, if the only non-matching param was a legacy query param, then
246
- // we just want to overwrite it.
247
- historyMethod = 'replaceState';
248
- }
249
-
250
- window.history[historyMethod]?.(
251
- {
252
- query: state.baseQuery,
253
- searchType: state.searchType,
254
- page: state.currentPage,
255
- sort: { field: state.selectedSort, direction: state.sortDirection },
256
- minDate: state.minSelectedDate,
257
- maxDate: state.maxSelectedDate,
258
- facets: state.selectedFacets,
259
- },
260
- '',
261
- url,
262
- );
263
- }
264
-
265
- private loadQueryStateFromUrl(): RestorationState {
266
- const url = new URL(window.location.href);
267
- const searchInside = url.searchParams.get('sin');
268
- const pageNumber = url.searchParams.get('page');
269
- const searchQuery = url.searchParams.get('query');
270
- const sortQuery = url.searchParams.get('sort');
271
- const facetAnds = url.searchParams.getAll('and[]');
272
- const facetNots = url.searchParams.getAll('not[]');
273
-
274
- // We also need to check for the presence of params like 'and[0]', 'not[1]', etc.
275
- // since Facebook automatically converts URLs with [] into those forms.
276
- for (const [key, val] of url.searchParams.entries()) {
277
- if (/and\[\d+\]/.test(key)) {
278
- facetAnds.push(val);
279
- } else if (/not\[\d+\]/.test(key)) {
280
- facetNots.push(val);
281
- }
282
- }
283
-
284
- // Legacy search allowed `q` and `search` params for the query, so in the interest
285
- // of backwards-compatibility with old bookmarks, we recognize those here too.
286
- // (However, they still get upgraded to a `query` param when we persist our state
287
- // to the URL).
288
- const legacySearchQuery =
289
- url.searchParams.get('q') ?? url.searchParams.get('search');
290
-
291
- const restorationState: RestorationState = {
292
- selectedFacets: getDefaultSelectedFacets(),
293
- };
294
-
295
- if (searchQuery) {
296
- restorationState.baseQuery = searchQuery;
297
- } else if (legacySearchQuery) {
298
- restorationState.baseQuery = legacySearchQuery;
299
- }
300
-
301
- switch (searchInside) {
302
- case 'TXT':
303
- restorationState.searchType = SearchType.FULLTEXT;
304
- break;
305
- case 'RADIO':
306
- restorationState.searchType = SearchType.RADIO;
307
- break;
308
- case 'TV':
309
- restorationState.searchType = SearchType.TV;
310
- break;
311
- case 'MD':
312
- restorationState.searchType = SearchType.METADATA;
313
- break;
314
- default:
315
- restorationState.searchType = SearchType.DEFAULT;
316
- break;
317
- }
318
-
319
- if (pageNumber) {
320
- const parsed = parseInt(pageNumber, 10);
321
- restorationState.currentPage = parsed;
322
- } else {
323
- restorationState.currentPage = 1;
324
- }
325
-
326
- if (sortQuery) {
327
- const { field, direction } = this.getSortFieldAndDirection(sortQuery);
328
-
329
- const sortOption = sortOptionFromAPIString(field);
330
- restorationState.selectedSort = sortOption.field;
331
-
332
- if (['asc', 'desc'].includes(direction)) {
333
- restorationState.sortDirection = direction as SortDirection;
334
- }
335
- }
336
-
337
- if (facetAnds) {
338
- facetAnds.forEach(and => {
339
- // eslint-disable-next-line prefer-const
340
- let [field, value] = and.split(':');
341
-
342
- // Legacy search allowed and[] fields like 'creatorSorter', 'languageSorter', etc.
343
- // which we want to normalize to 'creator', 'language', etc. if redirected here.
344
- field = field.replace(/Sorter$/, '');
345
-
346
- // Legacy search also allowed a form of negative faceting like `and[]=-collection:foo`
347
- // which we want to normalize to a not[] param instead
348
- if (field.startsWith('-')) {
349
- facetNots.push(and.slice(1));
350
- return;
351
- }
352
-
353
- switch (field) {
354
- case 'date':
355
- case 'year': {
356
- const [minDate, maxDate] = value.split(' TO ');
357
- // we have two potential ways of filtering by date:
358
- // the range with "date TO date" or the single date with "date"
359
- // this is checking for the range case and if we don't have those, fall
360
- // back to the single date case
361
- if (minDate && maxDate) {
362
- restorationState.minSelectedDate = minDate.substring(
363
- 1,
364
- minDate.length,
365
- );
366
- restorationState.maxSelectedDate = maxDate.substring(
367
- 0,
368
- maxDate.length - 1,
369
- );
370
- } else {
371
- this.setSelectedFacetState(
372
- restorationState.selectedFacets,
373
- field as FacetOption,
374
- value,
375
- 'selected',
376
- );
377
- }
378
- break;
379
- }
380
- case 'firstTitle':
381
- restorationState.selectedTitleFilter = value;
382
- break;
383
- case 'firstCreator':
384
- restorationState.selectedCreatorFilter = value;
385
- break;
386
- default:
387
- this.setSelectedFacetState(
388
- restorationState.selectedFacets,
389
- field as FacetOption,
390
- value,
391
- 'selected',
392
- );
393
- }
394
- });
395
- }
396
-
397
- if (facetNots) {
398
- facetNots.forEach(not => {
399
- const [field, value] = not.split(':');
400
- this.setSelectedFacetState(
401
- restorationState.selectedFacets,
402
- field as FacetOption,
403
- value,
404
- 'hidden',
405
- );
406
- });
407
- }
408
-
409
- // TV clip special filters (carryovers from legacy page)
410
- for (const [paramKey, facetKey] of Object.entries(
411
- tvClipURLParamsToFilters,
412
- )) {
413
- if (url.searchParams.get(paramKey)) {
414
- this.setSelectedFacetState(
415
- restorationState.selectedFacets,
416
- 'clip_type',
417
- facetKey,
418
- 'selected',
419
- );
420
- break;
421
- }
422
- }
423
-
424
- return restorationState;
425
- }
426
-
427
- /**
428
- * Converts a URL sort param into a field/direction pair, if possible.
429
- * Either or both may be undefined if the param is not in a recognized format.
430
- */
431
- private getSortFieldAndDirection(sortParam: string) {
432
- // check for two different sort formats: `date desc` and `-date`
433
- const hasSpace = sortParam.indexOf(' ') > -1;
434
- let field;
435
- let direction;
436
- if (hasSpace) {
437
- [field, direction] = sortParam.split(' ');
438
- } else {
439
- field = sortParam.startsWith('-') ? sortParam.slice(1) : sortParam;
440
- direction = sortParam.startsWith('-') ? 'desc' : 'asc';
441
- }
442
-
443
- return { field, direction };
444
- }
445
-
446
- /** Returns the `-` prefix for `desc` sort, or the empty string otherwise. */
447
- private sortDirectionPrefix(sortDirection?: string) {
448
- return sortDirection === 'desc' ? '-' : '';
449
- }
450
-
451
- /** Remove optional opening and closing quotes from a string */
452
- private stripQuotes(value: string): string {
453
- if (value.startsWith('"') && value.endsWith('"')) {
454
- return value.substring(1, value.length - 1);
455
- }
456
-
457
- return value;
458
- }
459
-
460
- /**
461
- * Returns whether the two given URLSearchParams objects have
462
- * identical values for all of the given param keys. If either
463
- * object contains more than one value for a given key, then
464
- * all of the values for that key must match (disregarding order).
465
- */
466
- private paramsMatch(
467
- searchParams1: URLSearchParams,
468
- searchParams2: URLSearchParams,
469
- keys: string[],
470
- ): boolean {
471
- return keys.every(key =>
472
- arrayEquals(
473
- searchParams1.getAll(key).sort(),
474
- searchParams2.getAll(key).sort(),
475
- ),
476
- );
477
- }
478
-
479
- /**
480
- * Deletes any params from the given URLSearchParams object that are recognized
481
- * when loading state from the URL.
482
- */
483
- private removeRecognizedParams(
484
- searchParams: URLSearchParams,
485
- ): URLSearchParams {
486
- // Remove all of our standard params
487
- searchParams.delete('query');
488
- searchParams.delete('sin');
489
- searchParams.delete('page');
490
- searchParams.delete('sort');
491
- searchParams.delete('and[]');
492
- searchParams.delete('not[]');
493
-
494
- // Remove any and/not facet params that contain numbers in their square brackets
495
- for (const key of searchParams.keys()) {
496
- if (/(and|not)\[\d+\]/.test(key)) {
497
- searchParams.delete(key);
498
- }
499
- }
500
-
501
- // Also remove some legacy params that should have been upgraded to the ones above
502
- searchParams.delete('q');
503
- searchParams.delete('search');
504
- searchParams.delete('only_commercials');
505
- searchParams.delete('only_factchecks');
506
- searchParams.delete('only_quotes');
507
-
508
- return searchParams;
509
- }
510
-
511
- /**
512
- * Returns whether the given URLSearchParams object contains a param that is
513
- * only recognized as a holdover from legacy search, and should not be
514
- * persisted to the URL.
515
- */
516
- private hasLegacyParam(searchParams: URLSearchParams): boolean {
517
- return searchParams.has('q') || searchParams.has('search');
518
- }
519
-
520
- /**
521
- * Sets the facet state for the given field & value to the given state,
522
- * creating any previously-undefined buckets as needed.
523
- */
524
- private setSelectedFacetState(
525
- selectedFacets: SelectedFacets,
526
- field: FacetOption,
527
- value: string,
528
- state: FacetState,
529
- ): void {
530
- const facet = selectedFacets[field];
531
- if (!facet) return; // Unrecognized facet group, ignore it.
532
-
533
- const unQuotedValue = this.stripQuotes(value);
534
- facet[unQuotedValue] ??= this.getDefaultBucket(value);
535
- facet[unQuotedValue].state = state;
536
- }
537
-
538
- /** Returns a default bucket with the given key, count of 0, and state 'none'. */
539
- private getDefaultBucket(key: string): FacetBucket {
540
- return {
541
- key,
542
- count: 0,
543
- state: 'none',
544
- };
545
- }
546
- }
1
+ import { SearchType, SortDirection } from '@internetarchive/search-service';
2
+ import { getCookie, setCookie } from 'typescript-cookie';
3
+ import {
4
+ FacetOption,
5
+ CollectionBrowserContext,
6
+ CollectionDisplayMode,
7
+ SelectedFacets,
8
+ TvClipFilterType,
9
+ SortField,
10
+ FacetBucket,
11
+ FacetState,
12
+ getDefaultSelectedFacets,
13
+ sortOptionFromAPIString,
14
+ SORT_OPTIONS,
15
+ tvClipFiltersToURLParams,
16
+ tvClipURLParamsToFilters,
17
+ } from './models';
18
+ import { arrayEquals } from './utils/array-equals';
19
+
20
+ export interface RestorationState {
21
+ displayMode?: CollectionDisplayMode;
22
+ searchType?: SearchType;
23
+ selectedSort?: SortField;
24
+ sortDirection?: SortDirection;
25
+ selectedFacets: SelectedFacets;
26
+ baseQuery?: string;
27
+ currentPage?: number;
28
+ titleQuery?: string;
29
+ creatorQuery?: string;
30
+ minSelectedDate?: string;
31
+ maxSelectedDate?: string;
32
+ selectedTitleFilter?: string;
33
+ selectedCreatorFilter?: string;
34
+ tvClipFilter?: TvClipFilterType;
35
+ }
36
+
37
+ export interface RestorationStatePersistOptions {
38
+ forceReplace?: boolean;
39
+ persistMetadataSearchType?: boolean;
40
+ }
41
+
42
+ export interface RestorationStateHandlerInterface {
43
+ persistState(
44
+ state: RestorationState,
45
+ options?: RestorationStatePersistOptions,
46
+ ): void;
47
+ getRestorationState(): RestorationState;
48
+ }
49
+
50
+ export class RestorationStateHandler
51
+ implements RestorationStateHandlerInterface
52
+ {
53
+ private context: CollectionBrowserContext;
54
+
55
+ private cookieDomain = '.archive.org';
56
+
57
+ private cookieExpiration = 30;
58
+
59
+ private cookiePath = '/';
60
+
61
+ constructor(options: { context: CollectionBrowserContext }) {
62
+ this.context = options.context;
63
+ }
64
+
65
+ persistState(
66
+ state: RestorationState,
67
+ options: RestorationStatePersistOptions = {},
68
+ ): void {
69
+ if (state.displayMode) this.persistViewStateToCookies(state.displayMode);
70
+ this.persistQueryStateToUrl(state, options);
71
+ }
72
+
73
+ getRestorationState(): RestorationState {
74
+ const restorationState = this.loadQueryStateFromUrl();
75
+ const displayMode = this.loadTileViewStateFromCookies();
76
+ restorationState.displayMode = displayMode;
77
+ return restorationState;
78
+ }
79
+
80
+ private persistViewStateToCookies(displayMode: CollectionDisplayMode) {
81
+ const gridState = displayMode === 'grid' ? 'tiles' : 'lists';
82
+ setCookie(`view-${this.context}`, gridState, {
83
+ domain: this.cookieDomain,
84
+ expires: this.cookieExpiration,
85
+ path: this.cookiePath,
86
+ });
87
+ const detailsState = displayMode === 'list-detail' ? 'showdetails' : '';
88
+ setCookie(`showdetails-${this.context}`, detailsState, {
89
+ domain: this.cookieDomain,
90
+ expires: this.cookieExpiration,
91
+ path: this.cookiePath,
92
+ });
93
+ }
94
+
95
+ private loadTileViewStateFromCookies(): CollectionDisplayMode {
96
+ const viewState = getCookie(`view-${this.context}`);
97
+ const detailsState = getCookie(`showdetails-${this.context}`);
98
+ if (viewState === 'tiles' || viewState === undefined) return 'grid';
99
+ if (detailsState === 'showdetails') return 'list-detail';
100
+ return 'list-compact';
101
+ }
102
+
103
+ private persistQueryStateToUrl(
104
+ state: RestorationState,
105
+ options: RestorationStatePersistOptions = {},
106
+ ) {
107
+ const url = new URL(window.location.href);
108
+ const oldParams = new URLSearchParams(url.searchParams);
109
+ const newParams = this.removeRecognizedParams(url.searchParams);
110
+
111
+ let replaceEmptySin = false;
112
+
113
+ if (state.baseQuery) {
114
+ newParams.set('query', state.baseQuery);
115
+ }
116
+
117
+ switch (state.searchType) {
118
+ case SearchType.FULLTEXT:
119
+ newParams.set('sin', 'TXT');
120
+ break;
121
+ case SearchType.RADIO:
122
+ newParams.set('sin', 'RADIO');
123
+ break;
124
+ case SearchType.TV:
125
+ newParams.set('sin', 'TV');
126
+ break;
127
+ case SearchType.METADATA:
128
+ // Only write the param for metadata when it isn't already the default.
129
+ // Currently this is only the case within TV collections.
130
+ if (options.persistMetadataSearchType || oldParams.get('sin') === 'MD')
131
+ newParams.set('sin', 'MD');
132
+ break;
133
+ }
134
+
135
+ if (oldParams.get('sin') === '') {
136
+ // Treat empty sin the same as no sin at all
137
+ oldParams.delete('sin');
138
+ replaceEmptySin = true;
139
+ }
140
+
141
+ if (state.currentPage) {
142
+ if (state.currentPage > 1) {
143
+ newParams.set('page', state.currentPage.toString());
144
+ } else {
145
+ newParams.delete('page');
146
+ }
147
+ }
148
+
149
+ if (state.selectedSort) {
150
+ const sortOption = SORT_OPTIONS[state.selectedSort];
151
+ let prefix = this.sortDirectionPrefix(state.sortDirection);
152
+
153
+ if (sortOption.field === SortField.unrecognized) {
154
+ // For unrecognized sorts, use the existing param, possibly updating its direction
155
+ const oldSortParam = oldParams.get('sort') ?? '';
156
+ const { field, direction } =
157
+ this.getSortFieldAndDirection(oldSortParam);
158
+
159
+ // Use the state-specified direction if available, or extract one from the param if not
160
+ if (!state.sortDirection) prefix = this.sortDirectionPrefix(direction);
161
+
162
+ if (field) {
163
+ newParams.set('sort', `${prefix}${field}`);
164
+ } else {
165
+ newParams.set('sort', oldSortParam);
166
+ }
167
+ } else if (sortOption.shownInURL) {
168
+ // Otherwise, use the canonical API form of the sort option
169
+ const canonicalApiSort = sortOption.urlNames[0];
170
+ newParams.set('sort', `${prefix}${canonicalApiSort}`);
171
+ }
172
+ }
173
+
174
+ if (state.selectedFacets) {
175
+ for (const [facetName, facetValues] of Object.entries(
176
+ state.selectedFacets,
177
+ )) {
178
+ const facetEntries = Object.entries(facetValues);
179
+ if (facetEntries.length === 0) continue;
180
+ for (const [key, data] of facetEntries) {
181
+ const notValue = data.state === 'hidden';
182
+ const paramValue = `${facetName}:"${key}"`;
183
+ if (notValue) {
184
+ newParams.append('not[]', paramValue);
185
+ } else {
186
+ newParams.append('and[]', paramValue);
187
+ }
188
+ }
189
+ }
190
+ }
191
+
192
+ const dateField =
193
+ state.minSelectedDate?.includes('-') ||
194
+ state.maxSelectedDate?.includes('-')
195
+ ? 'date'
196
+ : 'year';
197
+
198
+ if (state.minSelectedDate && state.maxSelectedDate) {
199
+ newParams.append(
200
+ 'and[]',
201
+ `${dateField}:[${state.minSelectedDate} TO ${state.maxSelectedDate}]`,
202
+ );
203
+ }
204
+
205
+ if (state.titleQuery) {
206
+ newParams.append('and[]', state.titleQuery);
207
+ }
208
+
209
+ if (state.creatorQuery) {
210
+ newParams.append('and[]', state.creatorQuery);
211
+ }
212
+
213
+ // TV clip special filters
214
+ if (state.tvClipFilter) {
215
+ const tvClipParam = tvClipFiltersToURLParams[state.tvClipFilter];
216
+ if (tvClipParam) newParams.append(tvClipParam, '1');
217
+ }
218
+
219
+ // Ensure we aren't pushing consecutive identical states to the history stack.
220
+ // - If the state has changed, we push a new history entry.
221
+ // - If only the page number has changed, we replace the current history entry.
222
+ // - If the state hasn't changed, then do nothing.
223
+ let historyMethod: 'pushState' | 'replaceState' = options.forceReplace
224
+ ? 'replaceState'
225
+ : 'pushState';
226
+ const nonQueryParamsMatch = this.paramsMatch(oldParams, newParams, [
227
+ 'sin',
228
+ 'sort',
229
+ 'and[]',
230
+ 'not[]',
231
+ 'only_commercials',
232
+ 'only_factchecks',
233
+ 'only_quotes',
234
+ ]);
235
+
236
+ if (
237
+ nonQueryParamsMatch &&
238
+ this.paramsMatch(oldParams, newParams, ['query'])
239
+ ) {
240
+ if (replaceEmptySin) {
241
+ // Get rid of any empty sin param
242
+ newParams.delete('sin');
243
+ } else if (this.paramsMatch(oldParams, newParams, ['page'])) {
244
+ // For page number, we want to replace the page state when it changes,
245
+ // not push a new history entry. If it hasn't changed, then we're done.
246
+ return;
247
+ }
248
+ historyMethod = 'replaceState';
249
+ } else if (nonQueryParamsMatch && this.hasLegacyParam(oldParams)) {
250
+ // Similarly, if the only non-matching param was a legacy query param, then
251
+ // we just want to overwrite it.
252
+ historyMethod = 'replaceState';
253
+ }
254
+
255
+ window.history[historyMethod]?.(
256
+ {
257
+ query: state.baseQuery,
258
+ searchType: state.searchType,
259
+ page: state.currentPage,
260
+ sort: { field: state.selectedSort, direction: state.sortDirection },
261
+ minDate: state.minSelectedDate,
262
+ maxDate: state.maxSelectedDate,
263
+ facets: state.selectedFacets,
264
+ },
265
+ '',
266
+ url,
267
+ );
268
+ }
269
+
270
+ private loadQueryStateFromUrl(): RestorationState {
271
+ const url = new URL(window.location.href);
272
+ const searchInside = url.searchParams.get('sin');
273
+ const pageNumber = url.searchParams.get('page');
274
+ const searchQuery = url.searchParams.get('query');
275
+ const sortQuery = url.searchParams.get('sort');
276
+ const facetAnds = url.searchParams.getAll('and[]');
277
+ const facetNots = url.searchParams.getAll('not[]');
278
+
279
+ // We also need to check for the presence of params like 'and[0]', 'not[1]', etc.
280
+ // since Facebook automatically converts URLs with [] into those forms.
281
+ for (const [key, val] of url.searchParams.entries()) {
282
+ if (/and\[\d+\]/.test(key)) {
283
+ facetAnds.push(val);
284
+ } else if (/not\[\d+\]/.test(key)) {
285
+ facetNots.push(val);
286
+ }
287
+ }
288
+
289
+ // Legacy search allowed `q` and `search` params for the query, so in the interest
290
+ // of backwards-compatibility with old bookmarks, we recognize those here too.
291
+ // (However, they still get upgraded to a `query` param when we persist our state
292
+ // to the URL).
293
+ const legacySearchQuery =
294
+ url.searchParams.get('q') ?? url.searchParams.get('search');
295
+
296
+ const restorationState: RestorationState = {
297
+ selectedFacets: getDefaultSelectedFacets(),
298
+ };
299
+
300
+ if (searchQuery) {
301
+ restorationState.baseQuery = searchQuery;
302
+ } else if (legacySearchQuery) {
303
+ restorationState.baseQuery = legacySearchQuery;
304
+ }
305
+
306
+ switch (searchInside) {
307
+ case 'TXT':
308
+ restorationState.searchType = SearchType.FULLTEXT;
309
+ break;
310
+ case 'RADIO':
311
+ restorationState.searchType = SearchType.RADIO;
312
+ break;
313
+ case 'TV':
314
+ restorationState.searchType = SearchType.TV;
315
+ break;
316
+ case 'MD':
317
+ restorationState.searchType = SearchType.METADATA;
318
+ break;
319
+ default:
320
+ restorationState.searchType = SearchType.DEFAULT;
321
+ break;
322
+ }
323
+
324
+ if (pageNumber) {
325
+ const parsed = parseInt(pageNumber, 10);
326
+ restorationState.currentPage = parsed;
327
+ } else {
328
+ restorationState.currentPage = 1;
329
+ }
330
+
331
+ if (sortQuery) {
332
+ const { field, direction } = this.getSortFieldAndDirection(sortQuery);
333
+
334
+ const sortOption = sortOptionFromAPIString(field);
335
+ restorationState.selectedSort = sortOption.field;
336
+
337
+ if (['asc', 'desc'].includes(direction)) {
338
+ restorationState.sortDirection = direction as SortDirection;
339
+ }
340
+ }
341
+
342
+ if (facetAnds) {
343
+ facetAnds.forEach(and => {
344
+ // eslint-disable-next-line prefer-const
345
+ let [field, value] = and.split(':');
346
+
347
+ // Legacy search allowed and[] fields like 'creatorSorter', 'languageSorter', etc.
348
+ // which we want to normalize to 'creator', 'language', etc. if redirected here.
349
+ field = field.replace(/Sorter$/, '');
350
+
351
+ // Legacy search also allowed a form of negative faceting like `and[]=-collection:foo`
352
+ // which we want to normalize to a not[] param instead
353
+ if (field.startsWith('-')) {
354
+ facetNots.push(and.slice(1));
355
+ return;
356
+ }
357
+
358
+ switch (field) {
359
+ case 'date':
360
+ case 'year': {
361
+ const [minDate, maxDate] = value.split(' TO ');
362
+ // we have two potential ways of filtering by date:
363
+ // the range with "date TO date" or the single date with "date"
364
+ // this is checking for the range case and if we don't have those, fall
365
+ // back to the single date case
366
+ if (minDate && maxDate) {
367
+ restorationState.minSelectedDate = minDate.substring(
368
+ 1,
369
+ minDate.length,
370
+ );
371
+ restorationState.maxSelectedDate = maxDate.substring(
372
+ 0,
373
+ maxDate.length - 1,
374
+ );
375
+ } else {
376
+ this.setSelectedFacetState(
377
+ restorationState.selectedFacets,
378
+ field as FacetOption,
379
+ value,
380
+ 'selected',
381
+ );
382
+ }
383
+ break;
384
+ }
385
+ case 'firstTitle':
386
+ restorationState.selectedTitleFilter = value;
387
+ break;
388
+ case 'firstCreator':
389
+ restorationState.selectedCreatorFilter = value;
390
+ break;
391
+ default:
392
+ this.setSelectedFacetState(
393
+ restorationState.selectedFacets,
394
+ field as FacetOption,
395
+ value,
396
+ 'selected',
397
+ );
398
+ }
399
+ });
400
+ }
401
+
402
+ if (facetNots) {
403
+ facetNots.forEach(not => {
404
+ const [field, value] = not.split(':');
405
+ this.setSelectedFacetState(
406
+ restorationState.selectedFacets,
407
+ field as FacetOption,
408
+ value,
409
+ 'hidden',
410
+ );
411
+ });
412
+ }
413
+
414
+ // TV clip special filters (carryovers from legacy page)
415
+ for (const [paramKey, filter] of Object.entries(tvClipURLParamsToFilters)) {
416
+ if (url.searchParams.get(paramKey)) {
417
+ restorationState.tvClipFilter = filter;
418
+ break;
419
+ }
420
+ }
421
+
422
+ return restorationState;
423
+ }
424
+
425
+ /**
426
+ * Converts a URL sort param into a field/direction pair, if possible.
427
+ * Either or both may be undefined if the param is not in a recognized format.
428
+ */
429
+ private getSortFieldAndDirection(sortParam: string) {
430
+ // check for two different sort formats: `date desc` and `-date`
431
+ const hasSpace = sortParam.indexOf(' ') > -1;
432
+ let field;
433
+ let direction;
434
+ if (hasSpace) {
435
+ [field, direction] = sortParam.split(' ');
436
+ } else {
437
+ field = sortParam.startsWith('-') ? sortParam.slice(1) : sortParam;
438
+ direction = sortParam.startsWith('-') ? 'desc' : 'asc';
439
+ }
440
+
441
+ return { field, direction };
442
+ }
443
+
444
+ /** Returns the `-` prefix for `desc` sort, or the empty string otherwise. */
445
+ private sortDirectionPrefix(sortDirection?: string) {
446
+ return sortDirection === 'desc' ? '-' : '';
447
+ }
448
+
449
+ /** Remove optional opening and closing quotes from a string */
450
+ private stripQuotes(value: string): string {
451
+ if (value.startsWith('"') && value.endsWith('"')) {
452
+ return value.substring(1, value.length - 1);
453
+ }
454
+
455
+ return value;
456
+ }
457
+
458
+ /**
459
+ * Returns whether the two given URLSearchParams objects have
460
+ * identical values for all of the given param keys. If either
461
+ * object contains more than one value for a given key, then
462
+ * all of the values for that key must match (disregarding order).
463
+ */
464
+ private paramsMatch(
465
+ searchParams1: URLSearchParams,
466
+ searchParams2: URLSearchParams,
467
+ keys: string[],
468
+ ): boolean {
469
+ return keys.every(key =>
470
+ arrayEquals(
471
+ searchParams1.getAll(key).sort(),
472
+ searchParams2.getAll(key).sort(),
473
+ ),
474
+ );
475
+ }
476
+
477
+ /**
478
+ * Deletes any params from the given URLSearchParams object that are recognized
479
+ * when loading state from the URL.
480
+ */
481
+ private removeRecognizedParams(
482
+ searchParams: URLSearchParams,
483
+ ): URLSearchParams {
484
+ // Remove all of our standard params
485
+ searchParams.delete('query');
486
+ searchParams.delete('sin');
487
+ searchParams.delete('page');
488
+ searchParams.delete('sort');
489
+ searchParams.delete('and[]');
490
+ searchParams.delete('not[]');
491
+
492
+ // Remove any and/not facet params that contain numbers in their square brackets
493
+ for (const key of searchParams.keys()) {
494
+ if (/(and|not)\[\d+\]/.test(key)) {
495
+ searchParams.delete(key);
496
+ }
497
+ }
498
+
499
+ // Also remove some legacy params that should have been upgraded to the ones above
500
+ searchParams.delete('q');
501
+ searchParams.delete('search');
502
+ searchParams.delete('only_commercials');
503
+ searchParams.delete('only_factchecks');
504
+ searchParams.delete('only_quotes');
505
+
506
+ return searchParams;
507
+ }
508
+
509
+ /**
510
+ * Returns whether the given URLSearchParams object contains a param that is
511
+ * only recognized as a holdover from legacy search, and should not be
512
+ * persisted to the URL.
513
+ */
514
+ private hasLegacyParam(searchParams: URLSearchParams): boolean {
515
+ return searchParams.has('q') || searchParams.has('search');
516
+ }
517
+
518
+ /**
519
+ * Sets the facet state for the given field & value to the given state,
520
+ * creating any previously-undefined buckets as needed.
521
+ */
522
+ private setSelectedFacetState(
523
+ selectedFacets: SelectedFacets,
524
+ field: FacetOption,
525
+ value: string,
526
+ state: FacetState,
527
+ ): void {
528
+ const facet = selectedFacets[field];
529
+ if (!facet) return; // Unrecognized facet group, ignore it.
530
+
531
+ const unQuotedValue = this.stripQuotes(value);
532
+ facet[unQuotedValue] ??= this.getDefaultBucket(value);
533
+ facet[unQuotedValue].state = state;
534
+ }
535
+
536
+ /** Returns a default bucket with the given key, count of 0, and state 'none'. */
537
+ private getDefaultBucket(key: string): FacetBucket {
538
+ return {
539
+ key,
540
+ count: 0,
541
+ state: 'none',
542
+ };
543
+ }
544
+ }