@internetarchive/collection-browser 3.5.2-alpha-webdev8160.0 → 3.5.2-alpha-webdev8093.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/dist/src/app-root.js +606 -606
  2. package/dist/src/app-root.js.map +1 -1
  3. package/dist/src/collection-browser.js +764 -764
  4. package/dist/src/collection-browser.js.map +1 -1
  5. package/dist/src/collection-facets/facet-row.js +140 -140
  6. package/dist/src/collection-facets/facet-row.js.map +1 -1
  7. package/dist/src/collection-facets/facets-template.js +23 -23
  8. package/dist/src/collection-facets/facets-template.js.map +1 -1
  9. package/dist/src/collection-facets/more-facets-content.d.ts +1 -0
  10. package/dist/src/collection-facets/more-facets-content.js +126 -127
  11. package/dist/src/collection-facets/more-facets-content.js.map +1 -1
  12. package/dist/src/collection-facets.js +267 -267
  13. package/dist/src/collection-facets.js.map +1 -1
  14. package/dist/src/data-source/collection-browser-data-source-interface.js.map +1 -1
  15. package/dist/src/data-source/collection-browser-data-source.js.map +1 -1
  16. package/dist/src/data-source/collection-browser-query-state.js.map +1 -1
  17. package/dist/src/data-source/models.js.map +1 -1
  18. package/dist/src/models.d.ts +0 -4
  19. package/dist/src/models.js +0 -8
  20. package/dist/src/models.js.map +1 -1
  21. package/dist/src/restoration-state-handler.js.map +1 -1
  22. package/dist/src/tiles/grid/collection-tile.js +77 -77
  23. package/dist/src/tiles/grid/collection-tile.js.map +1 -1
  24. package/dist/src/tiles/grid/item-tile.js +137 -137
  25. package/dist/src/tiles/grid/item-tile.js.map +1 -1
  26. package/dist/src/tiles/hover/hover-pane-controller.d.ts +8 -0
  27. package/dist/src/tiles/hover/hover-pane-controller.js +13 -1
  28. package/dist/src/tiles/hover/hover-pane-controller.js.map +1 -1
  29. package/dist/src/tiles/models.js.map +1 -1
  30. package/dist/src/tiles/tile-dispatcher.js +215 -215
  31. package/dist/src/tiles/tile-dispatcher.js.map +1 -1
  32. package/dist/test/collection-browser.test.js +189 -189
  33. package/dist/test/collection-browser.test.js.map +1 -1
  34. package/dist/test/collection-facets/more-facets-content.test.js +28 -28
  35. package/dist/test/collection-facets/more-facets-content.test.js.map +1 -1
  36. package/dist/test/restoration-state-handler.test.js.map +1 -1
  37. package/package.json +1 -1
  38. package/src/app-root.ts +1140 -1140
  39. package/src/collection-browser.ts +3075 -3075
  40. package/src/collection-facets/facet-row.ts +299 -299
  41. package/src/collection-facets/facets-template.ts +83 -83
  42. package/src/collection-facets/more-facets-content.ts +642 -644
  43. package/src/collection-facets.ts +1010 -1010
  44. package/src/data-source/collection-browser-data-source-interface.ts +345 -345
  45. package/src/data-source/collection-browser-data-source.ts +1441 -1441
  46. package/src/data-source/collection-browser-query-state.ts +59 -59
  47. package/src/data-source/models.ts +56 -56
  48. package/src/models.ts +0 -9
  49. package/src/restoration-state-handler.ts +546 -546
  50. package/src/tiles/grid/collection-tile.ts +163 -163
  51. package/src/tiles/grid/item-tile.ts +340 -340
  52. package/src/tiles/hover/hover-pane-controller.ts +15 -1
  53. package/src/tiles/models.ts +1 -1
  54. package/src/tiles/tile-dispatcher.ts +517 -517
  55. package/test/collection-browser.test.ts +2413 -2413
  56. package/test/collection-facets/more-facets-content.test.ts +231 -231
  57. package/test/restoration-state-handler.test.ts +480 -480
  58. package/vite.config.ts +29 -29
@@ -1,546 +1,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
- 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
+ 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
+ }