@nulib/canopy 0.0.0 → 2.0.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 (141) hide show
  1. package/bin/canopy.js +16 -0
  2. package/lib/AGENTS.md +107 -0
  3. package/lib/base-path.js +67 -0
  4. package/lib/build/appearance.js +76 -0
  5. package/lib/build/assets.js +30 -0
  6. package/lib/build/build.js +350 -0
  7. package/lib/build/dev.js +1355 -0
  8. package/lib/build/devtoast.config.json +6 -0
  9. package/lib/build/devtoast.css +14 -0
  10. package/lib/build/facets.js +19 -0
  11. package/lib/build/fonts.js +105 -0
  12. package/lib/build/iiif.js +2990 -0
  13. package/lib/build/log.js +31 -0
  14. package/lib/build/mdx.js +1967 -0
  15. package/lib/build/package-names.js +111 -0
  16. package/lib/build/pages.js +420 -0
  17. package/lib/build/rehype-task-list-labels.js +54 -0
  18. package/lib/build/runtimes.js +141 -0
  19. package/lib/build/search-index.js +55 -0
  20. package/lib/build/search-text.js +160 -0
  21. package/lib/build/search-workflow.js +72 -0
  22. package/lib/build/search.js +302 -0
  23. package/lib/build/sitemap.js +197 -0
  24. package/lib/build/styles.js +140 -0
  25. package/lib/build/theme-tokens.js +78 -0
  26. package/lib/build/ui-styles.js +25 -0
  27. package/lib/build/upgrade-notices.js +121 -0
  28. package/lib/cli.js +64 -0
  29. package/lib/common.js +580 -0
  30. package/lib/components/bibliography.js +197 -0
  31. package/lib/components/featured.js +237 -0
  32. package/lib/components/hero-slider-runtime.js +215 -0
  33. package/lib/components/image-story-runtime-entry.js +249 -0
  34. package/lib/components/map-runtime.js +114 -0
  35. package/lib/components/metadata-index.js +32 -0
  36. package/lib/components/nav-place.js +227 -0
  37. package/lib/components/navigation.js +381 -0
  38. package/lib/components/referenced.js +217 -0
  39. package/lib/components/slider-runtime-entry.js +106 -0
  40. package/lib/components/timeline-runtime.js +80 -0
  41. package/lib/components/viewer-runtime-entry.js +88 -0
  42. package/lib/config-path.js +78 -0
  43. package/lib/default-locale.js +113 -0
  44. package/lib/discovery/browser-loader.js +107 -0
  45. package/lib/discovery/browser.js +115 -0
  46. package/lib/discovery/config.js +25 -0
  47. package/lib/discovery/envelope.js +124 -0
  48. package/lib/discovery/export.js +226 -0
  49. package/lib/discovery/ingestion.js +62 -0
  50. package/lib/discovery/pagination.js +66 -0
  51. package/lib/discovery/provenance.js +79 -0
  52. package/lib/discovery/search.js +81 -0
  53. package/lib/discovery/tools.js +155 -0
  54. package/lib/discovery/validation.js +121 -0
  55. package/lib/head.js +154 -0
  56. package/lib/iiif/thumbnail.js +402 -0
  57. package/lib/index.js +9 -0
  58. package/lib/locale-runtime.js +69 -0
  59. package/lib/locales.js +203 -0
  60. package/lib/orchestrator.js +231 -0
  61. package/lib/page-context.js +24 -0
  62. package/lib/search/bundle.js +25 -0
  63. package/lib/search/data.js +202 -0
  64. package/lib/search/engine.js +86 -0
  65. package/lib/search/index-cache.js +95 -0
  66. package/lib/search/search-app.jsx +835 -0
  67. package/lib/search/search-engine-runtime.js +44 -0
  68. package/lib/search/search-form-runtime.js +462 -0
  69. package/lib/search/search.js +676 -0
  70. package/package.json +109 -3
  71. package/types/base-path.d.ts +4 -0
  72. package/types/orchestrator.d.ts +17 -0
  73. package/ui/dist/index.mjs +7358 -0
  74. package/ui/dist/index.mjs.map +7 -0
  75. package/ui/dist/server.mjs +12731 -0
  76. package/ui/dist/server.mjs.map +7 -0
  77. package/ui/fonts/OFL.txt +98 -0
  78. package/ui/fonts/google-sans-flex-latin-ext.woff2 +0 -0
  79. package/ui/fonts/google-sans-flex-latin.woff2 +0 -0
  80. package/ui/fonts/source-serif-4-italic-latin-ext.woff2 +0 -0
  81. package/ui/fonts/source-serif-4-italic-latin.woff2 +0 -0
  82. package/ui/fonts/source-serif-4-latin-ext.woff2 +0 -0
  83. package/ui/fonts/source-serif-4-latin.woff2 +0 -0
  84. package/ui/styles/base/_common.scss +97 -0
  85. package/ui/styles/base/_heading.scss +61 -0
  86. package/ui/styles/base/_markdown.scss +188 -0
  87. package/ui/styles/base/_type.scss +51 -0
  88. package/ui/styles/base/_utilities.scss +7 -0
  89. package/ui/styles/base/index.scss +5 -0
  90. package/ui/styles/components/_article-card.scss +108 -0
  91. package/ui/styles/components/_band.scss +104 -0
  92. package/ui/styles/components/_bibliography.scss +88 -0
  93. package/ui/styles/components/_buttons.scss +143 -0
  94. package/ui/styles/components/_card.scss +109 -0
  95. package/ui/styles/components/_diagram.scss +76 -0
  96. package/ui/styles/components/_feature.scss +66 -0
  97. package/ui/styles/components/_footer.scss +136 -0
  98. package/ui/styles/components/_gallery.scss +476 -0
  99. package/ui/styles/components/_image-story.scss +56 -0
  100. package/ui/styles/components/_interstitial-hero.scss +625 -0
  101. package/ui/styles/components/_layout.scss +83 -0
  102. package/ui/styles/components/_map.scss +296 -0
  103. package/ui/styles/components/_metadata-index.scss +68 -0
  104. package/ui/styles/components/_nav-tree.scss +80 -0
  105. package/ui/styles/components/_referenced-items.scss +69 -0
  106. package/ui/styles/components/_sub-navigation.scss +208 -0
  107. package/ui/styles/components/_swoosh.scss +50 -0
  108. package/ui/styles/components/_timeline.scss +350 -0
  109. package/ui/styles/components/_work.scss +71 -0
  110. package/ui/styles/components/header/_header.scss +294 -0
  111. package/ui/styles/components/header/_logo.scss +99 -0
  112. package/ui/styles/components/header/_navbar.scss +143 -0
  113. package/ui/styles/components/header/index.scss +3 -0
  114. package/ui/styles/components/iiif/_image.scss +32 -0
  115. package/ui/styles/components/iiif/_slider.scss +5 -0
  116. package/ui/styles/components/iiif/index.scss +2 -0
  117. package/ui/styles/components/index.scss +25 -0
  118. package/ui/styles/components/modal/_modal.scss +130 -0
  119. package/ui/styles/components/modal/index.scss +1 -0
  120. package/ui/styles/components/search/_filters.scss +259 -0
  121. package/ui/styles/components/search/_form.scss +187 -0
  122. package/ui/styles/components/search/_panel.scss +7 -0
  123. package/ui/styles/components/search/_results.scss +241 -0
  124. package/ui/styles/components/search/_tabs.scss +60 -0
  125. package/ui/styles/components/search/index.scss +4 -0
  126. package/ui/styles/index.css +5007 -0
  127. package/ui/styles/index.scss +11 -0
  128. package/ui/styles/settings/_breakpoints.scss +7 -0
  129. package/ui/styles/settings/_focus.scss +15 -0
  130. package/ui/styles/settings/_tokens.scss +170 -0
  131. package/ui/styles/settings/_type.scss +126 -0
  132. package/ui/styles/version-parity.css +116 -0
  133. package/ui/tailwind-canopy-iiif-plugin.js +39 -0
  134. package/ui/tailwind-canopy-iiif-preset.js +32 -0
  135. package/ui/tailwind-config.d.ts +29 -0
  136. package/ui/tailwind-config.js +159 -0
  137. package/ui/tailwind-default.config.mjs +4 -0
  138. package/ui/theme-color.js +130 -0
  139. package/ui/theme-palette.js +337 -0
  140. package/ui/theme.js +153 -0
  141. package/README.md +0 -3
@@ -0,0 +1,835 @@
1
+ import React, {useEffect, useMemo, useSyncExternalStore, useState} from "react";
2
+ import {createRoot} from "react-dom/client";
3
+ import {
4
+ SearchResultsUI,
5
+ SearchTabsUI,
6
+ SearchFiltersDialog,
7
+ } from "../../ui/dist/index.mjs";
8
+ import resultTemplates from "__CANOPY_SEARCH_RESULT_TEMPLATES__";
9
+ import FlexSearch from "flexsearch";
10
+ import localeRuntime from "../locale-runtime.js";
11
+ import {createEngine} from "./engine.js";
12
+ import {apiUrl, loadSearchData, withBasePath} from "./data.js";
13
+ import {openIndex} from "./index-cache.js";
14
+ const SITE_TITLE_FALLBACK = "Site title";
15
+ const {getRuntimeMessage, formatRuntimeMessage} = localeRuntime;
16
+
17
+ function readSiteTitleFromGlobals() {
18
+ try {
19
+ if (
20
+ typeof window !== "undefined" &&
21
+ typeof window.CANOPY_SITE_TITLE === "string"
22
+ ) {
23
+ const raw = window.CANOPY_SITE_TITLE.trim();
24
+ if (raw) return raw;
25
+ }
26
+ } catch (_) {}
27
+ try {
28
+ if (
29
+ typeof globalThis !== "undefined" &&
30
+ typeof globalThis.CANOPY_SITE_TITLE === "string"
31
+ ) {
32
+ const raw = globalThis.CANOPY_SITE_TITLE.trim();
33
+ if (raw) return raw;
34
+ }
35
+ } catch (_) {}
36
+ try {
37
+ if (typeof document !== "undefined" && document.title) {
38
+ const trimmed = document.title.trim();
39
+ if (!trimmed) return "";
40
+ const parts = trimmed.split("|").map((part) => part.trim()).filter(Boolean);
41
+ if (parts.length > 1) return parts[parts.length - 1];
42
+ return trimmed;
43
+ }
44
+ } catch (_) {}
45
+ return "";
46
+ }
47
+
48
+ // The header's dialogs carry the site's title as the header shows it (`_app.mdx`'s
49
+ // `title`), which `canopy.yml`'s `title` need not be; the filters take the same.
50
+ function readSiteTitleFromHeader() {
51
+ try {
52
+ const label =
53
+ document.getElementById("canopy-modal-search-label") ||
54
+ document.getElementById("canopy-modal-nav-label");
55
+ return label && label.textContent ? label.textContent.trim() : "";
56
+ } catch (_) {
57
+ return "";
58
+ }
59
+ }
60
+
61
+ function resolveSiteTitle() {
62
+ const title = readSiteTitleFromHeader() || readSiteTitleFromGlobals();
63
+ return title || SITE_TITLE_FALLBACK;
64
+ }
65
+
66
+ function resolveTypeLabel(type) {
67
+ const key = String(type || "").toLowerCase();
68
+ if (key === "work") return getRuntimeMessage("common.types.work", "Works");
69
+ if (key === "page") return getRuntimeMessage("common.types.page", "Pages");
70
+ if (key === "docs") return getRuntimeMessage("common.types.docs", "Docs");
71
+ if (key === "all") return getRuntimeMessage("common.nouns.types", "types");
72
+ if (key === "annotation") return getRuntimeMessage("common.nouns.items", "items");
73
+ return key ? key.charAt(0).toUpperCase() + key.slice(1) : "";
74
+ }
75
+
76
+ function createSearchStore() {
77
+ let engine = null;
78
+ let state = {
79
+ query: new URLSearchParams(location.search).get("q") || "",
80
+ type: new URLSearchParams(location.search).get("type") || "all",
81
+ loading: true,
82
+ records: [],
83
+ types: [],
84
+ index: null,
85
+ counts: {},
86
+ facets: [],
87
+ facetsDocsMap: {},
88
+ filters: {},
89
+ activeFilterCount: 0,
90
+ annotationsEnabled: false,
91
+ resultSettings: {},
92
+ failed: false,
93
+ };
94
+ const listeners = new Set();
95
+ function notify() {
96
+ listeners.forEach((fn) => {
97
+ try {
98
+ fn();
99
+ } catch (_) {}
100
+ });
101
+ }
102
+ // Keep a memoized snapshot so getSnapshot returns stable references
103
+ let snapshot = null;
104
+ function recomputeSnapshot() {
105
+ const {index, records, query, type, filters, facetsDocsMap} = state;
106
+ let base = [];
107
+ let results = [];
108
+ let totalForType = Array.isArray(records) ? records.length : 0;
109
+ let counts = {};
110
+ if (records && records.length) {
111
+ if (!query) {
112
+ base = records;
113
+ } else {
114
+ try {
115
+ const ids = engine ? engine.search(index, query, 200) : [];
116
+ base = ids.map((i) => records[i]).filter(Boolean);
117
+ } catch (_) {
118
+ base = [];
119
+ }
120
+ }
121
+ const normalizedFilters =
122
+ filters && typeof filters === "object" ? filters : {};
123
+ const totalActiveFilters = Object.keys(normalizedFilters).reduce(
124
+ (sum, slug) => {
125
+ const arr = Array.isArray(normalizedFilters[slug])
126
+ ? normalizedFilters[slug]
127
+ : [];
128
+ return sum + arr.filter(Boolean).length;
129
+ },
130
+ 0
131
+ );
132
+ state.activeFilterCount = totalActiveFilters;
133
+
134
+ const shouldFilterWorks =
135
+ totalActiveFilters > 0 && String(type).toLowerCase() === "work";
136
+ let allowed = null; // Set of record indices that satisfy filters
137
+ if (shouldFilterWorks) {
138
+ Object.keys(normalizedFilters).forEach((facetSlug) => {
139
+ const values = Array.isArray(normalizedFilters[facetSlug])
140
+ ? normalizedFilters[facetSlug]
141
+ : [];
142
+ if (!values.length) return;
143
+ const docMap =
144
+ facetsDocsMap && facetsDocsMap[facetSlug]
145
+ ? facetsDocsMap[facetSlug]
146
+ : null;
147
+ if (!docMap) {
148
+ allowed = new Set();
149
+ return;
150
+ }
151
+ const union = new Set();
152
+ values.forEach((valueSlugRaw) => {
153
+ const valueSlug = String(valueSlugRaw);
154
+ const docsSet = docMap[valueSlug];
155
+ if (docsSet && docsSet.size) {
156
+ docsSet.forEach((idx) => union.add(idx));
157
+ }
158
+ });
159
+ if (union.size === 0) {
160
+ allowed = new Set();
161
+ return;
162
+ }
163
+ if (!allowed) {
164
+ allowed = new Set(union);
165
+ } else {
166
+ allowed = new Set(
167
+ Array.from(allowed).filter((idx) => union.has(idx))
168
+ );
169
+ }
170
+ });
171
+ }
172
+
173
+ try {
174
+ counts = base.reduce((acc, r) => {
175
+ const t = String((r && r.type) || "page").toLowerCase();
176
+ if (shouldFilterWorks && t === "work") {
177
+ if (!allowed || !allowed.has(r && r.__docIndex)) return acc;
178
+ }
179
+ acc[t] = (acc[t] || 0) + 1;
180
+ return acc;
181
+ }, {});
182
+ } catch (_) {
183
+ counts = {};
184
+ }
185
+
186
+ const annotationMatches = base.filter((r) => r && r.annotation);
187
+ if (annotationMatches.length)
188
+ counts.annotation = annotationMatches.length;
189
+
190
+ const typeLower = String(type).toLowerCase();
191
+ if (typeLower === "annotation") {
192
+ results = annotationMatches.map((r) => ({
193
+ ...r,
194
+ type: "annotation",
195
+ originalType: r ? r.type : undefined,
196
+ }));
197
+ totalForType = annotationMatches.length;
198
+ } else {
199
+ results =
200
+ typeLower === "all"
201
+ ? base
202
+ : base.filter((r) => String(r.type).toLowerCase() === typeLower);
203
+ if (shouldFilterWorks && allowed) {
204
+ results = results.filter((r) => allowed.has(r && r.__docIndex));
205
+ }
206
+
207
+ if (typeLower !== "all") {
208
+ try {
209
+ totalForType = records.filter(
210
+ (r) => String(r.type).toLowerCase() === typeLower
211
+ ).length;
212
+ } catch (_) {}
213
+ }
214
+ }
215
+ }
216
+ const {facetsDocsMap: _fMap, ...publicState} = state;
217
+ snapshot = {
218
+ ...publicState,
219
+ results,
220
+ total: totalForType,
221
+ shown: results.length,
222
+ counts,
223
+ };
224
+ }
225
+ function set(partial) {
226
+ state = {...state, ...partial};
227
+ recomputeSnapshot();
228
+ notify();
229
+ }
230
+
231
+ function syncFiltersToUrl(nextFilters) {
232
+ try {
233
+ const url = new URL(location.href);
234
+ const facetSlugs = new Set();
235
+ if (Array.isArray(state.facets)) {
236
+ state.facets.forEach((facet) => {
237
+ if (facet && facet.slug) facetSlugs.add(String(facet.slug));
238
+ });
239
+ }
240
+ Object.keys(nextFilters || {}).forEach((slug) => {
241
+ if (slug) facetSlugs.add(String(slug));
242
+ });
243
+ facetSlugs.forEach((slug) => url.searchParams.delete(slug));
244
+ Object.keys(nextFilters || {}).forEach((slug) => {
245
+ const vals = Array.isArray(nextFilters[slug])
246
+ ? nextFilters[slug].filter(Boolean)
247
+ : [];
248
+ if (vals.length)
249
+ url.searchParams.set(slug, Array.from(new Set(vals)).join(","));
250
+ });
251
+ const qs = url.searchParams.toString();
252
+ history.replaceState(
253
+ null,
254
+ "",
255
+ qs ? `${url.pathname}?${qs}` : url.pathname
256
+ );
257
+ } catch (_) {}
258
+ }
259
+
260
+ function toggleFilter(facetSlug, valueSlug, nextChecked) {
261
+ const slug = String(facetSlug || "");
262
+ const value = String(valueSlug || "");
263
+ if (!slug || !value) return;
264
+ const current = Array.isArray(state.filters && state.filters[slug])
265
+ ? [...state.filters[slug]]
266
+ : [];
267
+ const setValues = new Set(current);
268
+ const shouldCheck =
269
+ typeof nextChecked === "boolean" ? nextChecked : !setValues.has(value);
270
+ if (shouldCheck) setValues.add(value);
271
+ else setValues.delete(value);
272
+ const nextFilters = {...state.filters};
273
+ if (setValues.size) nextFilters[slug] = Array.from(setValues);
274
+ else delete nextFilters[slug];
275
+ syncFiltersToUrl(nextFilters);
276
+ set({filters: nextFilters});
277
+ }
278
+
279
+ function clearFilters() {
280
+ syncFiltersToUrl({});
281
+ set({filters: {}});
282
+ }
283
+
284
+ async function hydrateFacets() {
285
+ try {
286
+ const res = await fetch(apiUrl('search/facets.json'));
287
+ if (!res || !res.ok) return;
288
+ const json = await res.json().catch(() => null);
289
+ if (!Array.isArray(json)) return;
290
+ const sanitized = [];
291
+ const docsMap = {};
292
+ json.forEach((facet) => {
293
+ if (
294
+ !facet ||
295
+ !facet.label ||
296
+ !facet.slug ||
297
+ !Array.isArray(facet.values)
298
+ )
299
+ return;
300
+ const slug = String(facet.slug);
301
+ const values = [];
302
+ const valueMap = {};
303
+ facet.values.forEach((valueEntry) => {
304
+ if (!valueEntry || !valueEntry.slug) return;
305
+ const vSlug = String(valueEntry.slug);
306
+ const vLabel =
307
+ valueEntry.value != null ? String(valueEntry.value) : "";
308
+ const docCount = Number.isFinite(Number(valueEntry.doc_count))
309
+ ? Number(valueEntry.doc_count)
310
+ : undefined;
311
+ const docs = Array.isArray(valueEntry.docs)
312
+ ? valueEntry.docs.map((idx) => Number(idx))
313
+ : [];
314
+ if (!valueMap[vSlug]) valueMap[vSlug] = new Set();
315
+ docs.forEach((idx) => {
316
+ if (Number.isInteger(idx)) valueMap[vSlug].add(idx);
317
+ });
318
+ values.push({value: vLabel, slug: vSlug, doc_count: docCount});
319
+ });
320
+ docsMap[slug] = valueMap;
321
+ sanitized.push({label: String(facet.label), slug, values});
322
+ });
323
+
324
+ // Pre-populate filters from query params once facets are known
325
+ const params = new URLSearchParams(location.search);
326
+ const nextFilters = {};
327
+ sanitized.forEach((facet) => {
328
+ const slug = facet.slug;
329
+ const valid = new Set(facet.values.map((item) => item.slug));
330
+ const requested = [];
331
+ params.getAll(slug).forEach((raw) => {
332
+ const parts = String(raw || "").split(",");
333
+ parts.forEach((part) => {
334
+ const trimmed = part && part.trim ? part.trim() : part;
335
+ if (trimmed && valid.has(trimmed)) requested.push(trimmed);
336
+ });
337
+ });
338
+ if (requested.length)
339
+ nextFilters[slug] = Array.from(new Set(requested));
340
+ });
341
+
342
+ set({facets: sanitized, facetsDocsMap: docsMap, filters: nextFilters});
343
+ syncFiltersToUrl(nextFilters);
344
+ } catch (_) {}
345
+ }
346
+ function subscribe(fn) {
347
+ listeners.add(fn);
348
+ return () => listeners.delete(fn);
349
+ }
350
+ function getSnapshot() {
351
+ return snapshot;
352
+ }
353
+ // Initialize snapshot
354
+ recomputeSnapshot();
355
+ // Load the records, open the index (from the visitor's cache when it holds this
356
+ // version), and pick the first tab.
357
+ (async () => {
358
+ try {
359
+ const DEBUG = (() => {
360
+ try {
361
+ const p = new URLSearchParams(location.search);
362
+ return (
363
+ p.has("searchDebug") || localStorage.CANOPY_SEARCH_DEBUG === "1"
364
+ );
365
+ } catch (_) {
366
+ return false;
367
+ }
368
+ })();
369
+ engine = createEngine(FlexSearch);
370
+ const {
371
+ searchMeta,
372
+ version,
373
+ records: data,
374
+ annotationCount,
375
+ } = await loadSearchData();
376
+ const tabsOrder = (
377
+ searchMeta && searchMeta.tabs && Array.isArray(searchMeta.tabs.order)
378
+ ? searchMeta.tabs.order
379
+ : []
380
+ )
381
+ .map((s) => String(s).trim().toLowerCase())
382
+ .filter(Boolean);
383
+ let resultsOrder = [];
384
+ let resultLayoutMap = {};
385
+ try {
386
+ const resultsMeta =
387
+ searchMeta && searchMeta.results ? searchMeta.results : null;
388
+ if (resultsMeta) {
389
+ const rawOrder = Array.isArray(resultsMeta.order)
390
+ ? resultsMeta.order
391
+ : [];
392
+ const rawSettings =
393
+ resultsMeta.settings && typeof resultsMeta.settings === "object"
394
+ ? resultsMeta.settings
395
+ : {};
396
+ const normalizedOrder = [];
397
+ const normalizedMap = {};
398
+ const seenTypes = new Set();
399
+ const resolveEntry = (value) => {
400
+ const type = String(value || "")
401
+ .trim()
402
+ .toLowerCase();
403
+ if (!type || seenTypes.has(type)) return;
404
+ const cfg = rawSettings[type] || rawSettings[value] || {};
405
+ const layout =
406
+ String((cfg && cfg.layout) || "").toLowerCase() === "grid"
407
+ ? "grid"
408
+ : "list";
409
+ const result =
410
+ String((cfg && cfg.result) || "").toLowerCase() === "figure"
411
+ ? "figure"
412
+ : "article";
413
+ normalizedMap[type] = { layout, result };
414
+ normalizedOrder.push(type);
415
+ seenTypes.add(type);
416
+ };
417
+ rawOrder.forEach(resolveEntry);
418
+ Object.keys(rawSettings || {}).forEach(resolveEntry);
419
+ if (normalizedOrder.length) {
420
+ resultsOrder = normalizedOrder;
421
+ resultLayoutMap = normalizedMap;
422
+ }
423
+ }
424
+ } catch (_) {}
425
+ const t0 =
426
+ typeof performance !== "undefined" && performance.now
427
+ ? performance.now()
428
+ : Date.now();
429
+ const {index: idx, cached} = await openIndex({
430
+ engine,
431
+ records: data,
432
+ version,
433
+ });
434
+ if (DEBUG) {
435
+ const t1 =
436
+ typeof performance !== "undefined" && performance.now
437
+ ? performance.now()
438
+ : Date.now();
439
+ // eslint-disable-next-line no-console
440
+ console.info(
441
+ `[Search] Index ${cached ? "imported from IndexedDB" : "built"} in ${Math.round(
442
+ t1 - t0
443
+ )}ms (records=${data.length}) v=${String(version).slice(0, 8)}`
444
+ );
445
+ }
446
+
447
+ const ts = Array.from(
448
+ new Set(data.map((r) => String((r && r.type) || "page")))
449
+ );
450
+ if (annotationCount && !ts.includes("annotation"))
451
+ ts.push("annotation");
452
+ const order =
453
+ Array.isArray(resultsOrder) && resultsOrder.length
454
+ ? resultsOrder
455
+ : Array.isArray(tabsOrder) && tabsOrder.length
456
+ ? tabsOrder
457
+ : ["work", "docs", "page"];
458
+ ts.sort((a, b) => {
459
+ const ia = order.indexOf(a);
460
+ const ib = order.indexOf(b);
461
+ return (ia < 0 ? 99 : ia) - (ib < 0 ? 99 : ib) || a.localeCompare(b);
462
+ });
463
+ // Default to configured first tab if no type param present
464
+ try {
465
+ const p = new URLSearchParams(location.search);
466
+ const hasType = p.has("type");
467
+ if (!hasType) {
468
+ let def = order && order.length ? order[0] : "all";
469
+ if (!ts.includes(def)) def = ts[0] || "all";
470
+ if (def && def !== "all") {
471
+ p.set("type", def);
472
+ history.replaceState(
473
+ null,
474
+ "",
475
+ `${location.pathname}?${p.toString()}`
476
+ );
477
+ }
478
+ set({type: def});
479
+ }
480
+ } catch (_) {}
481
+ set({
482
+ index: idx,
483
+ records: data,
484
+ types: ts,
485
+ loading: false,
486
+ annotationsEnabled: annotationCount > 0,
487
+ resultSettings: resultLayoutMap,
488
+ });
489
+ await hydrateFacets();
490
+ } catch (error) {
491
+ // Say so, here and on the page, rather than show no results for every query.
492
+ try {
493
+ console.error("[Search] failed to load", error);
494
+ } catch (_) {}
495
+ set({loading: false, failed: true});
496
+ }
497
+ })();
498
+ // API
499
+ function setQuery(q) {
500
+ set({query: q});
501
+ const u = new URL(location.href);
502
+ if (q) u.searchParams.set("q", q);
503
+ else u.searchParams.delete("q");
504
+ history.replaceState(
505
+ null,
506
+ "",
507
+ u.searchParams.toString()
508
+ ? `${u.pathname}?${u.searchParams.toString()}`
509
+ : u.pathname
510
+ );
511
+ }
512
+ function setType(t) {
513
+ set({type: t});
514
+ const u = new URL(location.href);
515
+ if (t && t !== "all") u.searchParams.set("type", t);
516
+ else u.searchParams.delete("type");
517
+ history.replaceState(
518
+ null,
519
+ "",
520
+ u.searchParams.toString()
521
+ ? `${u.pathname}?${u.searchParams.toString()}`
522
+ : u.pathname
523
+ );
524
+ }
525
+ return {
526
+ subscribe,
527
+ getSnapshot,
528
+ setQuery,
529
+ setType,
530
+ toggleFilter,
531
+ clearFilters,
532
+ };
533
+ }
534
+
535
+ // The header's field (`search-form-runtime.js`) drives this page's results rather than
536
+ // its own suggestions, whatever the page's route (`/es/buscar`, say).
537
+ if (typeof window !== "undefined") window.CanopySearchPage = true;
538
+
539
+ const store = typeof window !== "undefined" ? createSearchStore() : null;
540
+
541
+ function useStore() {
542
+ const snap = useSyncExternalStore(
543
+ store.subscribe,
544
+ store.getSnapshot,
545
+ store.getSnapshot
546
+ );
547
+ return {
548
+ ...snap,
549
+ setQuery: store.setQuery,
550
+ setType: store.setType,
551
+ toggleFilter: store.toggleFilter,
552
+ clearFilters: store.clearFilters,
553
+ };
554
+ }
555
+
556
+ function pageHas(selector) {
557
+ try {
558
+ return Boolean(document.querySelector(selector));
559
+ } catch (_) {
560
+ return false;
561
+ }
562
+ }
563
+
564
+ function ResultsMount(props = {}) {
565
+ const {results, type, types, loading, failed, query, resultSettings} = useStore();
566
+ if (loading)
567
+ return (
568
+ <div className="text-gray-800">
569
+ {formatRuntimeMessage("common.statuses.loading", "Loading…")}
570
+ </div>
571
+ );
572
+ if (failed)
573
+ return (
574
+ <div className="text-gray-800">
575
+ {formatRuntimeMessage("common.statuses.unavailable", "{content} unavailable.", {
576
+ content: getRuntimeMessage("common.nouns.search", "Search"),
577
+ })}
578
+ </div>
579
+ );
580
+ const normalizedType = String(type || "").trim().toLowerCase();
581
+ const hasOverrides =
582
+ resultSettings && Object.keys(resultSettings || {}).length > 0;
583
+ const typeSettings =
584
+ (normalizedType && resultSettings && resultSettings[normalizedType]) || null;
585
+ let layout = (props && props.layout) || "grid";
586
+ let variant = "auto";
587
+ if (typeSettings) {
588
+ layout = typeSettings.layout || "list";
589
+ variant = typeSettings.result || "article";
590
+ } else if (hasOverrides) {
591
+ layout = "list";
592
+ variant = "article";
593
+ }
594
+ return (
595
+ <SearchResultsUI
596
+ results={results}
597
+ type={type}
598
+ layout={layout}
599
+ query={query}
600
+ templates={resultTemplates}
601
+ variant={variant}
602
+ tabbed={
603
+ pageHas("[data-canopy-search-tabs]") &&
604
+ Array.isArray(types) &&
605
+ types.includes(type)
606
+ }
607
+ headingLevel={props.headingLevel}
608
+ />
609
+ );
610
+ }
611
+ function TabsMount() {
612
+ const {
613
+ type,
614
+ setType,
615
+ types,
616
+ counts,
617
+ facets,
618
+ filters,
619
+ activeFilterCount,
620
+ toggleFilter,
621
+ clearFilters,
622
+ } = useStore();
623
+ const [open, setOpen] = useState(false);
624
+ const hasFilters = Array.isArray(facets) && facets.length > 0;
625
+ const allowFilters = hasFilters && String(type).toLowerCase() === "work";
626
+ useEffect(() => {
627
+ if (!allowFilters && open) setOpen(false);
628
+ }, [allowFilters, open]);
629
+ const handleToggle = (facetSlug, valueSlug, checked) => {
630
+ if (toggleFilter) toggleFilter(facetSlug, valueSlug, checked);
631
+ };
632
+ const brandLabel = useMemo(() => resolveSiteTitle(), []);
633
+ const brandHref = useMemo(() => withBasePath("/"), []);
634
+ return (
635
+ <>
636
+ <SearchTabsUI
637
+ type={type}
638
+ onTypeChange={setType}
639
+ types={types}
640
+ counts={counts}
641
+ onOpenFilters={allowFilters ? () => setOpen(true) : undefined}
642
+ activeFilterCount={activeFilterCount || 0}
643
+ filtersOpen={allowFilters ? open : false}
644
+ panelId={
645
+ pageHas("[data-canopy-search-results]") ? "search-results" : undefined
646
+ }
647
+ />
648
+ {allowFilters ? (
649
+ <SearchFiltersDialog
650
+ open={open}
651
+ onOpenChange={setOpen}
652
+ facets={facets}
653
+ selected={filters}
654
+ onToggle={handleToggle}
655
+ onClear={() => clearFilters && clearFilters()}
656
+ brandLabel={brandLabel}
657
+ brandHref={brandHref}
658
+ />
659
+ ) : null}
660
+ </>
661
+ );
662
+ }
663
+ // What the search found, as a status message (4.1.3): shown at once, and said to a
664
+ // screen reader by a visually hidden twin once typing pauses, so it hears the count once
665
+ // rather than at every key.
666
+ const ANNOUNCE_DELAY = 800;
667
+
668
+ function SummaryMount() {
669
+ const {query, type, shown, total, loading, failed} = useStore();
670
+ const text = useMemo(() => {
671
+ if (loading || failed) return "";
672
+ const itemsLabel = getRuntimeMessage("common.nouns.items", "items");
673
+ if (!query) {
674
+ return formatRuntimeMessage(
675
+ "common.statuses.summary_content",
676
+ "Showing {shown} of {total} {content}",
677
+ {shown, total, content: itemsLabel},
678
+ );
679
+ }
680
+ const typeLabel = resolveTypeLabel(type);
681
+ return formatRuntimeMessage(
682
+ "common.statuses.search_summary",
683
+ 'Found {shown} of {total} in {type} for "{query}"',
684
+ {shown, total, type: typeLabel, query},
685
+ );
686
+ }, [query, type, shown, total, loading, failed]);
687
+ const spoken = failed
688
+ ? formatRuntimeMessage("common.statuses.unavailable", "{content} unavailable.", {
689
+ content: getRuntimeMessage("common.nouns.search", "Search"),
690
+ })
691
+ : text;
692
+ const [announced, setAnnounced] = useState("");
693
+ useEffect(() => {
694
+ const timer = setTimeout(() => setAnnounced(spoken), ANNOUNCE_DELAY);
695
+ return () => clearTimeout(timer);
696
+ }, [spoken]);
697
+ return (
698
+ <>
699
+ <div className="text-sm text-gray-800" aria-hidden="true">
700
+ {text}
701
+ </div>
702
+ <div role="status" className="sr-only">
703
+ {announced}
704
+ </div>
705
+ </>
706
+ );
707
+ }
708
+
709
+ function parseProps(el) {
710
+ try {
711
+ const s = el.querySelector('script[type="application/json"]');
712
+ if (s) return JSON.parse(s.textContent || "{}");
713
+ } catch (_) {}
714
+ return {};
715
+ }
716
+
717
+ function bindSearchInputToStore() {
718
+ if (!store || typeof document === "undefined") return;
719
+ try {
720
+ const input = document.querySelector("[data-canopy-search-form-input]");
721
+ if (!input || input.dataset.canopySearchSync === "1") return;
722
+ input.dataset.canopySearchSync = "1";
723
+
724
+ const syncFromStore = () => {
725
+ try {
726
+ const snap = store.getSnapshot();
727
+ const nextVal =
728
+ snap && typeof snap.query === "string" ? snap.query : "";
729
+ if (input.value !== nextVal) input.value = nextVal;
730
+ } catch (_) {}
731
+ };
732
+
733
+ const onInput = (event) => {
734
+ try {
735
+ const val =
736
+ event && event.target && typeof event.target.value === "string"
737
+ ? event.target.value
738
+ : "";
739
+ const current = (() => {
740
+ try {
741
+ const snap = store.getSnapshot();
742
+ return snap && typeof snap.query === "string" ? snap.query : "";
743
+ } catch (_) {
744
+ return "";
745
+ }
746
+ })();
747
+ if (val === current) return;
748
+ store.setQuery(val);
749
+ } catch (_) {}
750
+ };
751
+
752
+ input.addEventListener("input", onInput);
753
+ const unsubscribe = store.subscribe(syncFromStore);
754
+ syncFromStore();
755
+
756
+ const cleanup = () => {
757
+ try {
758
+ input.removeEventListener("input", onInput);
759
+ } catch (_) {}
760
+ try {
761
+ if (typeof unsubscribe === "function") unsubscribe();
762
+ } catch (_) {}
763
+ };
764
+ window.addEventListener("beforeunload", cleanup, {once: true});
765
+ } catch (_) {}
766
+ }
767
+
768
+ // The results' headings sit one level below the last heading the page shows before them
769
+ // (DESIGN.md §0, "Headings follow the page"; ACCESSIBILITY.md R7): under the search
770
+ // layout's `h1`, `h2`. `<SearchResults headingLevel={n} />` says otherwise.
771
+ function headingLevelBefore(node) {
772
+ try {
773
+ const before = Array.from(document.querySelectorAll("h1, h2, h3, h4, h5, h6")).filter(
774
+ (heading) =>
775
+ !node.contains(heading) &&
776
+ heading.compareDocumentPosition(node) & Node.DOCUMENT_POSITION_FOLLOWING &&
777
+ heading.getClientRects().length > 0 &&
778
+ !heading.closest('[aria-hidden="true"], [hidden], [inert]')
779
+ );
780
+ const last = before[before.length - 1];
781
+ return last ? Number(last.tagName.slice(1)) + 1 : 2;
782
+ } catch (_) {
783
+ return 2;
784
+ }
785
+ }
786
+
787
+ function mountAt(selector, Comp, extend) {
788
+ const nodes = document.querySelectorAll(selector);
789
+ nodes.forEach((n) => {
790
+ try {
791
+ const root = createRoot(n);
792
+ const parsed = parseProps(n);
793
+ const props = typeof extend === "function" ? extend(n, parsed) : parsed;
794
+ root.render(<Comp {...props} />);
795
+ } catch (e) {
796
+ // Surface helpful diagnostics in dev
797
+ try {
798
+ console.error(
799
+ "[Search] mount error at",
800
+ selector,
801
+ e && e.message ? e.message : e,
802
+ e && e.stack ? e.stack : ""
803
+ );
804
+ } catch (_) {}
805
+ }
806
+ });
807
+ }
808
+
809
+ if (typeof document !== "undefined") {
810
+ const run = () => {
811
+ // Mount tabs and other search UI pieces
812
+ mountAt("[data-canopy-search-tabs]", TabsMount);
813
+ mountAt("[data-canopy-search-results]", ResultsMount, (node, props) => ({
814
+ ...props,
815
+ headingLevel: Number(props.headingLevel) || headingLevelBefore(node),
816
+ }));
817
+ mountAt("[data-canopy-search-summary]", SummaryMount);
818
+ bindSearchInputToStore();
819
+ // Total mount removed
820
+ try {
821
+ window.addEventListener("canopy:search:setQuery", (ev) => {
822
+ try {
823
+ const q =
824
+ ev && ev.detail && typeof ev.detail.query === "string"
825
+ ? ev.detail.query
826
+ : document.querySelector("[data-canopy-search-form-input]")?.value ||
827
+ "";
828
+ if (typeof q === "string") store.setQuery(q);
829
+ } catch (_) {}
830
+ });
831
+ } catch (_) {}
832
+ };
833
+ if (document.readyState !== "loading") run();
834
+ else document.addEventListener("DOMContentLoaded", run, {once: true});
835
+ }