@nulib/canopy 0.0.0 → 2.0.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 (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,111 @@
1
+ // This package's name, and the name Canopy 1.x was published under, which sites' own
2
+ // files go on importing: `_app.mdx`, layouts, the search result templates, components.
3
+ // The MDX API is a contract (AGENTS.md), so wherever the build compiles or bundles a
4
+ // site's code it reads either name as this package. `@canopy-iiif/app` is published too,
5
+ // each of its entries passing through to this package (`packages/app-alias`), for what
6
+ // the build does not read: a site's stylesheet, its own scripts and its package.json.
7
+
8
+ 'use strict';
9
+
10
+ const PACKAGE_NAME = require('../../package.json').name;
11
+ const LEGACY_NAMES = ['@canopy-iiif/app'];
12
+ const NAMES = [PACKAGE_NAME, ...LEGACY_NAMES];
13
+
14
+ const escape = (text) => text.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&');
15
+ const filterFor = (names) => new RegExp(`^(?:${names.map(escape).join('|')})(?:/|$)`);
16
+ const ANY_NAME = filterFor(NAMES);
17
+ const LEGACY_NAME = filterFor(LEGACY_NAMES);
18
+
19
+ function splitSpec(spec) {
20
+ if (typeof spec !== 'string') return null;
21
+ for (const name of NAMES) {
22
+ if (spec === name) return {name, subpath: ''};
23
+ if (spec.startsWith(`${name}/`)) return {name, subpath: spec.slice(name.length)};
24
+ }
25
+ return null;
26
+ }
27
+
28
+ // `@canopy-iiif/app/ui` → `@nulib/canopy/ui`; any other specifier as it is.
29
+ function currentSpec(spec) {
30
+ const parts = splitSpec(spec);
31
+ return parts ? `${PACKAGE_NAME}${parts.subpath}` : spec;
32
+ }
33
+
34
+ // As `currentSpec`, with the browser's UI entry read as the server's: a page and its
35
+ // components render on the server with the SSR-safe components (`ui/server`).
36
+ function serverSpec(spec) {
37
+ const parts = splitSpec(spec);
38
+ if (!parts) return spec;
39
+ return `${PACKAGE_NAME}${parts.subpath === '/ui' ? '/ui/server' : parts.subpath}`;
40
+ }
41
+
42
+ // A recma plugin for `@mdx-js/mdx`: the page's own imports and re-exports of either name,
43
+ // as `serverSpec` (or `currentSpec`, with `server: false`) reads them. Only declarations
44
+ // are read, never the page's words, so a code example keeps the name it shows.
45
+ function recmaPackageImports(options = {}) {
46
+ const read = options.server ? serverSpec : currentSpec;
47
+ return (tree) => {
48
+ for (const node of (tree && tree.body) || []) {
49
+ if (
50
+ !node ||
51
+ (node.type !== 'ImportDeclaration' &&
52
+ node.type !== 'ExportNamedDeclaration' &&
53
+ node.type !== 'ExportAllDeclaration')
54
+ ) {
55
+ continue;
56
+ }
57
+ const source = node.source;
58
+ if (!source || typeof source.value !== 'string') continue;
59
+ const next = read(source.value);
60
+ if (next === source.value) continue;
61
+ source.value = next;
62
+ source.raw = JSON.stringify(next);
63
+ }
64
+ };
65
+ }
66
+
67
+ // esbuild, for the browser: an import of the 1.x name, resolved as this package's.
68
+ function esbuildPackageNames() {
69
+ return {
70
+ name: 'canopy-package-names',
71
+ setup(build) {
72
+ build.onResolve({filter: LEGACY_NAME}, async (args) => {
73
+ const result = await build.resolve(currentSpec(args.path), {
74
+ kind: args.kind,
75
+ importer: args.importer,
76
+ resolveDir: args.resolveDir,
77
+ });
78
+ if (result.errors && result.errors.length) return {errors: result.errors};
79
+ return {
80
+ path: result.path,
81
+ external: result.external,
82
+ namespace: result.namespace,
83
+ sideEffects: result.sideEffects,
84
+ };
85
+ });
86
+ },
87
+ };
88
+ }
89
+
90
+ // esbuild, for the server: an import of either name stays an import, for Node to load
91
+ // beside the build, as `serverSpec` reads it (or `currentSpec`, with `server: false`: a
92
+ // component loaded by its own path has always kept the UI entry it names).
93
+ function esbuildServerPackageNames(options = {}) {
94
+ const read = options.server === false ? currentSpec : serverSpec;
95
+ return {
96
+ name: 'canopy-package-names-server',
97
+ setup(build) {
98
+ build.onResolve({filter: ANY_NAME}, (args) => ({path: read(args.path), external: true}));
99
+ },
100
+ };
101
+ }
102
+
103
+ module.exports = {
104
+ PACKAGE_NAME,
105
+ LEGACY_NAMES,
106
+ currentSpec,
107
+ serverSpec,
108
+ recmaPackageImports,
109
+ esbuildPackageNames,
110
+ esbuildServerPackageNames,
111
+ };
@@ -0,0 +1,420 @@
1
+ const {
2
+ fs,
3
+ fsp,
4
+ path,
5
+ CONTENT_DIR,
6
+ OUT_DIR,
7
+ ensureDirSync,
8
+ htmlShell,
9
+ canopyBodyClassForType,
10
+ rootRelativeHref,
11
+ resolveLocaleFromContentPath,
12
+ canonicalizeLocaleCode,
13
+ getDefaultLocaleCode,
14
+ } = require('../common');
15
+ const { log } = require('./log');
16
+ const mdx = require('./mdx');
17
+ const {buildLocaleRuntimeScript} = require('../locales');
18
+ const navigation = require('../components/navigation');
19
+ const referenced = require('../components/referenced');
20
+
21
+ function relativeRuntimeScript(outPath, filename, versioned = false) {
22
+ if (!outPath || !filename) return null;
23
+ const abs = path.join(OUT_DIR, 'scripts', filename);
24
+ let rel = path.relative(path.dirname(outPath), abs).split(path.sep).join('/');
25
+ if (!versioned) return rel;
26
+ try {
27
+ const st = fs.statSync(abs);
28
+ const version = Math.floor(st.mtimeMs || Date.now());
29
+ if (version) rel += `?v=${version}`;
30
+ } catch (_) {}
31
+ return rel;
32
+ }
33
+
34
+ function normalizeWhitespace(value) {
35
+ if (!value) return '';
36
+ return String(value).replace(/\s+/g, ' ').trim();
37
+ }
38
+
39
+ function truncateDescription(value, max = 240) {
40
+ const normalized = normalizeWhitespace(value);
41
+ if (!normalized) return '';
42
+ if (normalized.length <= max) return normalized;
43
+ const slice = normalized.slice(0, Math.max(0, max - 3)).trimEnd();
44
+ return `${slice}...`;
45
+ }
46
+
47
+ function isPlainObject(value) {
48
+ return !!value && typeof value === 'object' && !Array.isArray(value);
49
+ }
50
+
51
+ function readFrontmatterString(data, key) {
52
+ if (!data) return '';
53
+ const raw = data[key];
54
+ if (raw == null) return '';
55
+ if (typeof raw === 'string') return raw.trim();
56
+ return '';
57
+ }
58
+
59
+ // Cache: dir -> frontmatter data for _layout.mdx in that dir
60
+ const LAYOUT_META = new Map();
61
+
62
+ async function getNearestDirLayoutMeta(filePath) {
63
+ const startDir = path.dirname(filePath);
64
+ let dir = startDir;
65
+ while (dir && dir.startsWith(CONTENT_DIR)) {
66
+ const key = path.resolve(dir);
67
+ if (LAYOUT_META.has(key)) {
68
+ const cached = LAYOUT_META.get(key);
69
+ if (cached) return cached;
70
+ }
71
+ const candidate = path.join(dir, '_layout.mdx');
72
+ if (fs.existsSync(candidate)) {
73
+ try {
74
+ const raw = await fsp.readFile(candidate, 'utf8');
75
+ const fm = mdx.parseFrontmatter(raw);
76
+ const data = fm && fm.data ? fm.data : null;
77
+ LAYOUT_META.set(key, data);
78
+ if (data) return data;
79
+ } catch (_) {
80
+ LAYOUT_META.set(key, null);
81
+ }
82
+ } else {
83
+ LAYOUT_META.set(key, null);
84
+ }
85
+ const parent = path.dirname(dir);
86
+ if (parent === dir) break;
87
+ dir = parent;
88
+ }
89
+ return null;
90
+ }
91
+
92
+ function mapContentPathToOutput(filePath) {
93
+ const rel = path.relative(CONTENT_DIR, filePath);
94
+ const outRel = rel.replace(/\.mdx$/i, '.html');
95
+ return path.join(OUT_DIR, outRel);
96
+ }
97
+
98
+ async function renderContentMdxToHtml(filePath, outPath, extraProps = {}, sourceOverride = null) {
99
+ const sourceRaw = sourceOverride != null ? sourceOverride : await fsp.readFile(filePath, 'utf8');
100
+ const source = typeof sourceRaw === 'string' ? sourceRaw : String(sourceRaw || '');
101
+ const title = mdx.extractTitle(source);
102
+ const relContentPath = path.relative(CONTENT_DIR, filePath);
103
+ const relOutputPath = relContentPath.replace(/\.mdx$/i, '.html');
104
+ const normalizedRel = navigation.normalizeRelativePath(relContentPath);
105
+ const pageInfo = navigation.getPageInfo(normalizedRel);
106
+ const navData = navigation.buildNavigationForFile(normalizedRel);
107
+ const allNavigationRoots = navigation.buildNavigationRoots(
108
+ pageInfo && pageInfo.slug ? pageInfo.slug : ""
109
+ );
110
+ const mergedProps = { ...(extraProps || {}) };
111
+ const frontmatter =
112
+ typeof mdx.parseFrontmatter === 'function'
113
+ ? mdx.parseFrontmatter(source)
114
+ : { data: null, content: source };
115
+ const frontmatterData = frontmatter && isPlainObject(frontmatter.data) ? frontmatter.data : null;
116
+ const frontmatterLocaleRaw = readFrontmatterString(frontmatterData, 'locale');
117
+ const frontmatterLocale = canonicalizeLocaleCode(frontmatterLocaleRaw);
118
+ const pageLocale =
119
+ frontmatterLocale ||
120
+ resolveLocaleFromContentPath(relContentPath) ||
121
+ getDefaultLocaleCode();
122
+ const referencedManifestIdsRaw = frontmatterData ? frontmatterData.referencedManifests : null;
123
+ const referencedManifestIds = referenced.normalizeReferencedManifestList(
124
+ referencedManifestIdsRaw
125
+ );
126
+ const referencedItems = referencedManifestIds.length
127
+ ? referenced.buildReferencedItems(referencedManifestIds, {
128
+ locale: pageLocale,
129
+ })
130
+ : [];
131
+ let layoutMeta = null;
132
+ try {
133
+ layoutMeta = await getNearestDirLayoutMeta(filePath);
134
+ } catch (_) {
135
+ layoutMeta = null;
136
+ }
137
+ const directType = frontmatterData && typeof frontmatterData.type === 'string' ? frontmatterData.type.trim() : '';
138
+ const layoutType = layoutMeta && typeof layoutMeta.type === 'string' ? String(layoutMeta.type).trim() : '';
139
+ const resolvedType = directType || layoutType || (!frontmatterData ? 'page' : '');
140
+ const frontmatterDescription = frontmatterData && typeof frontmatterData.description === 'string'
141
+ ? truncateDescription(frontmatterData.description)
142
+ : '';
143
+ const extractedPlain = typeof mdx.extractSearchText === 'function'
144
+ ? mdx.extractSearchText(source).excerpt
145
+ : '';
146
+ const derivedDescription = truncateDescription(extractedPlain);
147
+ const resolvedDescription = frontmatterDescription || derivedDescription;
148
+ const ogImageFrontmatter =
149
+ readFrontmatterString(frontmatterData, 'og:image') ||
150
+ readFrontmatterString(frontmatterData, 'ogImage');
151
+ const genericImage = readFrontmatterString(frontmatterData, 'image');
152
+ const resolvedImage = ogImageFrontmatter || genericImage;
153
+ const frontmatterMeta = frontmatterData && isPlainObject(frontmatterData.meta) ? frontmatterData.meta : null;
154
+ const headings = mdx.extractHeadings(source);
155
+ const basePage = pageInfo ? { ...pageInfo } : {};
156
+ if (pageLocale) basePage.locale = pageLocale;
157
+ if (title) basePage.title = title;
158
+ if (resolvedType) basePage.type = resolvedType;
159
+ if (resolvedDescription) basePage.description = resolvedDescription;
160
+ if (basePage.href && !basePage.url) basePage.url = basePage.href;
161
+ const frontmatterCanonical = readFrontmatterString(frontmatterData, 'canonical');
162
+ const fallbackCanonical = rootRelativeHref(
163
+ relOutputPath.split(path.sep).join('/')
164
+ );
165
+ const canonicalValue =
166
+ frontmatterCanonical ||
167
+ (basePage && basePage.canonical) ||
168
+ basePage.url ||
169
+ basePage.href ||
170
+ fallbackCanonical;
171
+ if (canonicalValue) basePage.canonical = canonicalValue;
172
+ if (resolvedImage) {
173
+ basePage.image = resolvedImage;
174
+ basePage.ogImage = ogImageFrontmatter || resolvedImage;
175
+ }
176
+ const existingMeta = basePage.meta && typeof basePage.meta === 'object' ? basePage.meta : {};
177
+ const pageMeta = { ...existingMeta };
178
+ if (title) pageMeta.title = title;
179
+ if (resolvedDescription) pageMeta.description = resolvedDescription;
180
+ if (resolvedType) pageMeta.type = resolvedType;
181
+ if (basePage.url || basePage.href) pageMeta.url = basePage.url || basePage.href || pageMeta.url;
182
+ if (canonicalValue) pageMeta.canonical = canonicalValue;
183
+ if (resolvedImage) {
184
+ pageMeta.image = resolvedImage;
185
+ if (!pageMeta.ogImage) pageMeta.ogImage = resolvedImage;
186
+ }
187
+ if (pageLocale) pageMeta.locale = pageLocale;
188
+ if (frontmatterMeta) Object.assign(pageMeta, frontmatterMeta);
189
+ if (Object.keys(pageMeta).length) basePage.meta = pageMeta;
190
+ if (referencedManifestIds.length) {
191
+ basePage.referencedManifests = referencedManifestIds;
192
+ }
193
+ if (referencedItems.length) {
194
+ basePage.referencedItems = referencedItems;
195
+ }
196
+ if (Object.keys(basePage).length) {
197
+ mergedProps.page = mergedProps.page
198
+ ? { ...basePage, ...mergedProps.page }
199
+ : basePage;
200
+ }
201
+ if (referencedManifestIds.length) {
202
+ mergedProps.referencedManifests = referencedManifestIds;
203
+ }
204
+ if (referencedItems.length) {
205
+ mergedProps.referencedItems = referencedItems;
206
+ }
207
+ if (!mergedProps.navigation) {
208
+ if (navData || (allNavigationRoots && Object.keys(allNavigationRoots).length)) {
209
+ const navigationPayload = navData ? {...navData} : {};
210
+ if (allNavigationRoots && Object.keys(allNavigationRoots).length) {
211
+ navigationPayload.allRoots = allNavigationRoots;
212
+ }
213
+ mergedProps.navigation = Object.keys(navigationPayload).length
214
+ ? navigationPayload
215
+ : null;
216
+ }
217
+ } else if (
218
+ mergedProps.navigation &&
219
+ allNavigationRoots &&
220
+ Object.keys(allNavigationRoots).length &&
221
+ !mergedProps.navigation.allRoots
222
+ ) {
223
+ mergedProps.navigation.allRoots = allNavigationRoots;
224
+ }
225
+ if (headings && headings.length) {
226
+ mergedProps.page = mergedProps.page
227
+ ? { ...mergedProps.page, headings }
228
+ : { headings };
229
+ }
230
+ const { body, head } = await mdx.compileMdxFile(filePath, outPath, null, mergedProps);
231
+ const needsHydrateViewer =
232
+ body.includes('data-canopy-viewer') ||
233
+ body.includes('data-canopy-scroll') ||
234
+ body.includes('data-canopy-image');
235
+ const needsHydrateSlider = body.includes('data-canopy-slider');
236
+ const needsImageStory = body.includes('data-canopy-image-story');
237
+ const needsHeroSlider = body.includes('data-canopy-hero-slider');
238
+ const needsTimeline = body.includes('data-canopy-timeline');
239
+ const needsMap = body.includes('data-canopy-map');
240
+ const needsSearchForm = true; // search form runtime is global
241
+ const needsFacets = body.includes('data-canopy-related-items');
242
+ const needsCustomClients = body.includes('data-canopy-client-component');
243
+ const viewerRel = needsHydrateViewer
244
+ ? relativeRuntimeScript(outPath, 'canopy-viewer.js', true)
245
+ : null;
246
+ const sliderRel = (needsHydrateSlider || needsFacets)
247
+ ? relativeRuntimeScript(outPath, 'canopy-slider.js', true)
248
+ : null;
249
+ const imageStoryRel = needsImageStory
250
+ ? relativeRuntimeScript(outPath, 'canopy-image-story.js', true)
251
+ : null;
252
+ const heroRel = needsHeroSlider
253
+ ? relativeRuntimeScript(outPath, 'canopy-hero-slider.js', true)
254
+ : null;
255
+ const timelineRel = needsTimeline
256
+ ? relativeRuntimeScript(outPath, 'canopy-timeline.js', true)
257
+ : null;
258
+ const mapRel = needsMap
259
+ ? relativeRuntimeScript(outPath, 'canopy-map.js', true)
260
+ : null;
261
+ const mapCssRel = needsMap
262
+ ? path.relative(path.dirname(outPath), path.join(OUT_DIR, 'scripts', 'canopy-map.css')).split(path.sep).join('/')
263
+ : null;
264
+ const facetsRel = needsFacets
265
+ ? relativeRuntimeScript(outPath, 'canopy-related-items.js', true)
266
+ : null;
267
+ let searchFormRel = null;
268
+ if (needsSearchForm) {
269
+ searchFormRel = relativeRuntimeScript(outPath, 'canopy-search-form.js', true);
270
+ }
271
+ let customClientRel = null;
272
+ if (needsCustomClients) {
273
+ try {
274
+ await mdx.ensureCustomClientRuntime();
275
+ const customAbs = path.join(OUT_DIR, 'scripts', 'canopy-custom-components.js');
276
+ let rel = path.relative(path.dirname(outPath), customAbs).split(path.sep).join('/');
277
+ try {
278
+ const st = fs.statSync(customAbs);
279
+ rel += `?v=${Math.floor(st.mtimeMs || Date.now())}`;
280
+ } catch (_) {}
281
+ customClientRel = rel;
282
+ } catch (e) {
283
+ console.warn('[canopy][mdx] failed to build custom client runtime:', e && e.message ? e.message : e);
284
+ }
285
+ }
286
+ const moduleScriptRels = [];
287
+ if (viewerRel) moduleScriptRels.push(viewerRel);
288
+ if (sliderRel) moduleScriptRels.push(sliderRel);
289
+ if (imageStoryRel) moduleScriptRels.push(imageStoryRel);
290
+ if (customClientRel) moduleScriptRels.push(customClientRel);
291
+ const primaryClassicScripts = [];
292
+ if (heroRel) primaryClassicScripts.push(heroRel);
293
+ if (timelineRel) primaryClassicScripts.push(timelineRel);
294
+ if (mapRel) primaryClassicScripts.push(mapRel);
295
+ if (facetsRel) primaryClassicScripts.push(facetsRel);
296
+ const secondaryClassicScripts = [];
297
+ if (searchFormRel) secondaryClassicScripts.push(searchFormRel);
298
+ let jsRel = null;
299
+ if (primaryClassicScripts.length) {
300
+ jsRel = primaryClassicScripts.shift();
301
+ }
302
+ const classicScriptRels = primaryClassicScripts.concat(secondaryClassicScripts);
303
+ const needsReact = !!(
304
+ needsHydrateViewer ||
305
+ needsHydrateSlider ||
306
+ needsFacets ||
307
+ needsTimeline ||
308
+ needsMap ||
309
+ (customClientRel && needsCustomClients)
310
+ );
311
+ let vendorTag = '';
312
+ if (needsReact) {
313
+ try {
314
+ await mdx.ensureReactGlobals();
315
+ const vendorAbs = path.join(OUT_DIR, 'scripts', 'react-globals.js');
316
+ let vendorRel = path.relative(path.dirname(outPath), vendorAbs).split(path.sep).join('/');
317
+ try { const stv = fs.statSync(vendorAbs); vendorRel += `?v=${Math.floor(stv.mtimeMs || Date.now())}`; } catch (_) {}
318
+ vendorTag = `<script src="${vendorRel}"></script>`;
319
+ } catch (_) {}
320
+ }
321
+ try {
322
+ const { BASE_PATH } = require('../common');
323
+ if (BASE_PATH) vendorTag = `<script>window.CANOPY_BASE_PATH=${JSON.stringify(BASE_PATH)}</script>` + vendorTag;
324
+ } catch (_) {}
325
+ const headSegments = [head];
326
+ try {
327
+ const localeScript = buildLocaleRuntimeScript(pageLocale);
328
+ if (localeScript) headSegments.push(localeScript);
329
+ } catch (_) {}
330
+ const extraScripts = [];
331
+ const pushClassicScript = (src) => {
332
+ if (!src || src === jsRel) return;
333
+ extraScripts.push(`<script defer src="${src}"></script>`);
334
+ };
335
+ const pushModuleScript = (src) => {
336
+ if (!src) return;
337
+ extraScripts.push(`<script type="module" src="${src}"></script>`);
338
+ };
339
+ classicScriptRels.forEach((src) => pushClassicScript(src));
340
+ if (moduleScriptRels.length) {
341
+ moduleScriptRels.forEach((src) => pushModuleScript(src));
342
+ }
343
+ // The hero runtime ships no CSS; its styles live in the UI
344
+ // stylesheet, so only the map needs a runtime stylesheet.
345
+ const extraStyles = [];
346
+ if (mapCssRel) {
347
+ let rel = mapCssRel;
348
+ try {
349
+ const mapCssAbs = path.join(OUT_DIR, 'scripts', 'canopy-map.css');
350
+ const st = fs.statSync(mapCssAbs);
351
+ rel += `?v=${Math.floor(st.mtimeMs || Date.now())}`;
352
+ } catch (_) {}
353
+ extraStyles.push(`<link rel="stylesheet" href="${rel}">`);
354
+ }
355
+ if (extraStyles.length) headSegments.push(extraStyles.join(''));
356
+ if (vendorTag) headSegments.push(vendorTag);
357
+ if (extraScripts.length) headSegments.push(extraScripts.join(''));
358
+ const headExtra = headSegments.join('');
359
+ const typeForClass = resolvedType || 'page';
360
+ const bodyClass = canopyBodyClassForType(typeForClass);
361
+ const html = htmlShell({
362
+ title,
363
+ body,
364
+ cssHref: null,
365
+ scriptHref: jsRel,
366
+ headExtra,
367
+ bodyClass,
368
+ lang: pageLocale,
369
+ });
370
+ const { applyBaseToHtml } = require('../common');
371
+ return applyBaseToHtml(html);
372
+ }
373
+
374
+ async function processContentEntry(absPath, pagesMetadata = []) {
375
+ const stat = await fsp.stat(absPath);
376
+ if (stat.isDirectory()) return;
377
+ if (/\.mdx$/i.test(absPath)) {
378
+ if (mdx.isReservedFile(absPath)) return;
379
+ const outPath = mapContentPathToOutput(absPath);
380
+ try {
381
+ const source = await fsp.readFile(absPath, 'utf8');
382
+ const frontmatter = typeof mdx.parseFrontmatter === 'function'
383
+ ? mdx.parseFrontmatter(source)
384
+ : { data: null };
385
+ const frontmatterData = frontmatter && isPlainObject(frontmatter.data) ? frontmatter.data : null;
386
+ ensureDirSync(path.dirname(outPath));
387
+ try { log(`• Processing MDX ${absPath}\n`, 'blue'); } catch (_) {}
388
+ const base = path.basename(absPath);
389
+ const extra = base.toLowerCase() === 'sitemap.mdx' ? { pages: pagesMetadata } : {};
390
+ const html = await renderContentMdxToHtml(absPath, outPath, extra, source);
391
+ await fsp.writeFile(outPath, html || '', 'utf8');
392
+ try { log(`✓ Built ${path.relative(process.cwd(), outPath)}\n`, 'green'); } catch (_) {}
393
+ } catch (err) {
394
+ console.error('MDX build failed for', absPath, '\n', err.message);
395
+ }
396
+ } else {
397
+ const rel = path.relative(CONTENT_DIR, absPath);
398
+ const outPath = path.join(OUT_DIR, rel);
399
+ ensureDirSync(path.dirname(outPath));
400
+ await fsp.copyFile(absPath, outPath);
401
+ try { log(`• Copied ${path.relative(process.cwd(), outPath)}\n`, 'cyan', { dim: true }); } catch (_) {}
402
+ }
403
+ }
404
+
405
+ async function buildContentTree(dir, pagesMetadata = []) {
406
+ const entries = await fsp.readdir(dir, { withFileTypes: true });
407
+ for (const e of entries) {
408
+ const p = path.join(dir, e.name);
409
+ if (e.isDirectory()) await buildContentTree(p, pagesMetadata);
410
+ else if (e.isFile()) await processContentEntry(p, pagesMetadata);
411
+ }
412
+ }
413
+
414
+ module.exports = {
415
+ getNearestDirLayoutMeta,
416
+ mapContentPathToOutput,
417
+ renderContentMdxToHtml,
418
+ processContentEntry,
419
+ buildContentTree,
420
+ };
@@ -0,0 +1,54 @@
1
+ // Markdown task lists ("- [x] Point canopy.yml at a collection") render a checkbox with
2
+ // no label (WCAG 4.1.2; ACCESSIBILITY.md C15). This rehype plugin names each checkbox
3
+ // by its item's own words, so a screen reader says "Point canopy.yml at a collection,
4
+ // checkbox, checked". Words in a nested list belong to that list's items, not this one.
5
+
6
+ const LISTS = new Set(['ul', 'ol']);
7
+
8
+ function textOf(node) {
9
+ if (!node) return '';
10
+ if (node.type === 'text') return node.value || '';
11
+ if (node.type === 'element' && LISTS.has(node.tagName)) return '';
12
+ return Array.isArray(node.children) ? node.children.map(textOf).join('') : '';
13
+ }
14
+
15
+ function isTaskItem(node) {
16
+ if (node.type !== 'element' || node.tagName !== 'li') return false;
17
+ const className = node.properties && node.properties.className;
18
+ const classes = Array.isArray(className) ? className : String(className || '').split(/\s+/);
19
+ return classes.includes('task-list-item');
20
+ }
21
+
22
+ function findCheckbox(node) {
23
+ if (!node || !Array.isArray(node.children)) return null;
24
+ for (const child of node.children) {
25
+ if (child.type !== 'element') continue;
26
+ if (LISTS.has(child.tagName)) continue;
27
+ if (child.tagName === 'input' && child.properties && child.properties.type === 'checkbox') {
28
+ return child;
29
+ }
30
+ const nested = findCheckbox(child);
31
+ if (nested) return nested;
32
+ }
33
+ return null;
34
+ }
35
+
36
+ function visit(node, fn) {
37
+ fn(node);
38
+ if (Array.isArray(node.children)) node.children.forEach((child) => visit(child, fn));
39
+ }
40
+
41
+ function rehypeTaskListLabels() {
42
+ return (tree) => {
43
+ visit(tree, (node) => {
44
+ if (!isTaskItem(node)) return;
45
+ const checkbox = findCheckbox(node);
46
+ if (!checkbox || checkbox.properties.ariaLabel || checkbox.properties.ariaLabelledBy) return;
47
+ const label = textOf(node).replace(/\s+/g, ' ').trim();
48
+ if (label) checkbox.properties.ariaLabel = label;
49
+ });
50
+ };
51
+ }
52
+
53
+ module.exports = rehypeTaskListLabels;
54
+ module.exports.rehypeTaskListLabels = rehypeTaskListLabels;