@dogsbay/docs-layout 0.2.0-beta.18 → 0.2.0-beta.180

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.
@@ -12,7 +12,9 @@ import {
12
12
  type MultiSourceMeta,
13
13
  buildSwitcherRows,
14
14
  fallbackLandingUrl,
15
+ limitRows,
15
16
  shouldRenderSwitcher,
17
+ versionMenuFor,
16
18
  } from "./switcher.js";
17
19
 
18
20
  interface Props {
@@ -23,25 +25,33 @@ interface Props {
23
25
 
24
26
  const { switcherMap, multiSource, basePath = "/docs" } = Astro.props;
25
27
  const visible = shouldRenderSwitcher("version", switcherMap, multiSource);
28
+ // Whether the menu shows is decided before `limit` (versionMenu): then the
29
+ // first N rows, plus the page's own, and the menu's links after them.
30
+ const menu = visible ? versionMenuFor(switcherMap, multiSource!) : undefined;
26
31
  const rows = visible
27
- ? buildSwitcherRows({ axis: "version", switcherMap, multiSource: multiSource! })
32
+ ? limitRows(buildSwitcherRows({ axis: "version", switcherMap, multiSource: multiSource! }), menu?.limit)
28
33
  : [];
34
+ const links = menu?.links ?? [];
29
35
  const currentRow = rows.find((r) => r.isCurrent);
30
36
  const currentLabel = currentRow?.entry.label ?? currentRow?.entry.id ?? "Version";
31
37
  ---
32
38
 
33
39
  {visible && (
34
40
  <details class="version-switcher relative">
35
- <summary class="flex cursor-pointer items-center gap-1 rounded-md border border-border px-3 py-1.5 text-sm hover:bg-accent">
36
- <span class="font-medium">{currentLabel}</span>
41
+ <summary class="flex cursor-pointer items-center gap-1 whitespace-nowrap rounded-md border border-border px-3 py-1.5 text-sm hover:bg-accent max-md:px-2">
42
+ <span class="max-w-[10rem] truncate font-medium max-md:max-w-[6rem]">{currentLabel}</span>
37
43
  {currentRow?.entry.eol && (
38
44
  <span class="ml-1 rounded bg-muted px-1 text-[10px] uppercase text-muted-foreground">EOL</span>
39
45
  )}
40
- <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="ml-1 transition-transform"><polyline points="6 9 12 15 18 9"/></svg>
46
+ {currentRow?.entry.prerelease && (
47
+ <span class="ml-1 rounded bg-muted px-1 text-[10px] uppercase text-muted-foreground">Pre</span>
48
+ )}
49
+ <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="ml-1 transition-transform" aria-hidden="true"><polyline points="6 9 12 15 18 9"/></svg>
41
50
  </summary>
42
- <ul class="absolute right-0 z-50 mt-1 min-w-[10rem] rounded-md border border-border bg-popover p-1 text-sm shadow-md">
51
+ <div class="absolute right-0 z-50 mt-1 min-w-[10rem] rounded-md border border-border bg-popover p-1 text-sm shadow-md">
52
+ <ul>
43
53
  {rows.map((row) => {
44
- const href = row.url ?? fallbackLandingUrl(basePath, row.entry.id);
54
+ const href = row.url ?? row.entry.home ?? fallbackLandingUrl(basePath, row.entry.id, row.entry.root === true);
45
55
  const isFallback = row.url === null && !row.isCurrent;
46
56
  return (
47
57
  <li>
@@ -59,6 +69,9 @@ const currentLabel = currentRow?.entry.label ?? currentRow?.entry.id ?? "Version
59
69
  {row.entry.eol && (
60
70
  <span class="rounded bg-muted px-1 text-[10px] uppercase text-muted-foreground">EOL</span>
61
71
  )}
72
+ {row.entry.prerelease && (
73
+ <span class="rounded bg-muted px-1 text-[10px] uppercase text-muted-foreground">Pre</span>
74
+ )}
62
75
  {row.entry.default && !row.isCurrent && (
63
76
  <span class="text-[10px] text-muted-foreground">default</span>
64
77
  )}
@@ -70,6 +83,18 @@ const currentLabel = currentRow?.entry.label ?? currentRow?.entry.id ?? "Version
70
83
  );
71
84
  })}
72
85
  </ul>
86
+ {links.length > 0 && (
87
+ <ul class="mt-1 border-t border-border pt-1" data-version-menu-links>
88
+ {links.map((link) => (
89
+ <li>
90
+ <a href={link.href} class="flex items-center gap-2 rounded-sm px-2 py-1.5 text-foreground no-underline hover:bg-accent">
91
+ {link.label}
92
+ </a>
93
+ </li>
94
+ ))}
95
+ </ul>
96
+ )}
97
+ </div>
73
98
  </details>
74
99
  )}
75
100
 
@@ -0,0 +1,443 @@
1
+ /**
2
+ * Client-side sidebar nav hydration.
3
+ *
4
+ * Fetches `/_dogsbay/nav.json` once per session, renders the tree DOM
5
+ * to mirror `@dogsbay/ui/sidebar/SidebarNavTree.astro`'s structure,
6
+ * and re-highlights the current page on each Astro view-transition
7
+ * page-load.
8
+ *
9
+ * Design constraints:
10
+ * - DOM output matches SidebarNavTree exactly (same tags, classes,
11
+ * data-attributes) so Tailwind's compiled CSS styles us correctly
12
+ * and any sidebar-system selectors (e.g. `data-sidebar="nav-tree"`
13
+ * hooks) keep working.
14
+ * - Filter by `version` / `locale` matches `nav-filter.ts`'s SSR
15
+ * filter so a multi-axis site renders the same nav as `ssr-full`
16
+ * mode (without the multiplicative HTML cost).
17
+ * - One fetch per page load, then the DOM persists across view
18
+ * transitions. `nav.json` has a fixed name and is served with the
19
+ * host's default caching (nothing here marks it immutable, and
20
+ * nothing should: an unhashed name served immutable keeps the old
21
+ * nav after a redeploy), so repeat visits revalidate or refetch.
22
+ *
23
+ * See plans/client-rendered-nav.md.
24
+ */
25
+ import { filterNavByAxis } from "./nav-filter.js";
26
+ import { scopeNav, sectionMenu } from "@dogsbay/site-files";
27
+ import { sectionSwitcherHtml } from "./section-switcher.js";
28
+
29
+ interface NavMark {
30
+ kind: "added" | "changed" | "removed" | "moved";
31
+ label?: string;
32
+ subtree?: boolean;
33
+ }
34
+
35
+ interface NavItem {
36
+ label: string;
37
+ href?: string;
38
+ icon?: string;
39
+ children?: NavItem[];
40
+ mark?: NavMark;
41
+ }
42
+
43
+ /**
44
+ * A state marker beside a nav label (release comparisons mark changed /
45
+ * new / removed pages; the same slot serves "new since your last
46
+ * visit", deprecation flags, version badges).
47
+ *
48
+ * Accessibility contract — mirrors SidebarNavMark.astro, which renders
49
+ * the server-side tree:
50
+ * - **Never colour alone** (WCAG 1.4.1): a distinct GLYPH carries the
51
+ * meaning, so it survives greyscale and colour-blindness; colour only
52
+ * reinforces.
53
+ * - **Survives forced-colors** (High Contrast strips backgrounds): the
54
+ * glyph is real text, so it always renders.
55
+ * - **Announced**: a visually-hidden word rides along, so the row reads
56
+ * "MySQL, changed". It is a sibling span, NOT an aria-label on the
57
+ * link — an aria-label would REPLACE the page name in the
58
+ * accessibility tree, losing the label it exists to announce.
59
+ */
60
+ const MARK_GLYPH: Record<NavMark["kind"], string> = {
61
+ added: "+",
62
+ changed: "•",
63
+ removed: "−",
64
+ moved: "→",
65
+ };
66
+
67
+ function buildMark(mark: NavMark): HTMLElement {
68
+ const text = mark.label ?? (mark.subtree ? `contains ${mark.kind}` : mark.kind);
69
+ const wrap = document.createElement("span");
70
+ wrap.className = "db-nav-mark";
71
+ wrap.dataset.navMark = mark.kind;
72
+ if (mark.subtree) wrap.dataset.navMarkSubtree = "";
73
+ wrap.title = text;
74
+
75
+ const glyph = document.createElement("span");
76
+ glyph.setAttribute("aria-hidden", "true");
77
+ glyph.textContent = MARK_GLYPH[mark.kind];
78
+ wrap.appendChild(glyph);
79
+
80
+ const sr = document.createElement("span");
81
+ sr.className = "sr-only";
82
+ sr.textContent = text;
83
+ wrap.appendChild(sr);
84
+
85
+ return wrap;
86
+ }
87
+
88
+ /**
89
+ * Module-level cache so multiple page loads in the same SPA session
90
+ * share the same fetched nav data. Cleared by re-loads (full page
91
+ * navigations) but Astro's view transitions re-execute the script
92
+ * module without reloading the page — so on view-transition the
93
+ * cached promise is reused and no extra fetch fires.
94
+ */
95
+ let navPromise: Promise<NavItem[]> | null = null;
96
+
97
+ function fetchNav(url: string): Promise<NavItem[]> {
98
+ if (!navPromise) {
99
+ navPromise = fetch(url, { credentials: "same-origin" }).then((r) => {
100
+ if (!r.ok) throw new Error(`nav.json fetch failed: ${r.status}`);
101
+ return r.json() as Promise<NavItem[]>;
102
+ });
103
+ }
104
+ return navPromise;
105
+ }
106
+
107
+ function normalize(path: string): string {
108
+ return path.replace(/\/$/, "") || "/";
109
+ }
110
+
111
+ function hasActiveDescendant(item: NavItem, current: string): boolean {
112
+ if (item.href && normalize(item.href) === current) return true;
113
+ return item.children?.some((c) => hasActiveDescendant(c, current)) ?? false;
114
+ }
115
+
116
+ /**
117
+ * Render a single nav item into a `<li>` DOM node. Matches
118
+ * SidebarNavTree's per-level class set exactly so styling stays in
119
+ * sync. Padding is computed from `level` the same way (`8 + level*12`
120
+ * pixels) so indentation lines up across the same render.
121
+ */
122
+ export function renderItem(item: NavItem, current: string, level: number): HTMLLIElement {
123
+ const li = document.createElement("li");
124
+ li.dataset.sidebar = "nav-tree-item";
125
+
126
+ const active = item.href ? normalize(item.href) === current : false;
127
+ const hasChildren = !!item.children && item.children.length > 0;
128
+ const padLeft = `${8 + level * 12}px`;
129
+ const heightClass = level === 0 ? "h-8" : "h-7";
130
+
131
+ if (hasChildren && item.href) {
132
+ // A branch that is ALSO a page (section landing page) uses the APG
133
+ // "disclosure navigation" pattern: a real link (navigates) and a
134
+ // SEPARATE toggle <button> (expands/collapses), as siblings. Nesting
135
+ // a focusable <a> inside the interactive <summary> — as this did
136
+ // before — is an axe `nested-interactive` violation ("interactive
137
+ // controls must not be nested"). Native <details> can't hold a
138
+ // visible-when-collapsed header link without that nesting, so a
139
+ // page-branch drops <details> for link + button + sibling submenu.
140
+ const open = active || hasActiveDescendant(item, current);
141
+ const submenuId = `nav-sub-${item.href.replace(/[^a-z0-9]+/gi, "-")}-${level}`;
142
+
143
+ const row = document.createElement("div");
144
+ row.className = [
145
+ "flex w-full min-w-0 items-center gap-2 rounded-md text-sm text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
146
+ heightClass,
147
+ active ? "bg-sidebar-accent font-medium text-sidebar-accent-foreground" : "",
148
+ ]
149
+ .filter(Boolean)
150
+ .join(" ");
151
+ row.style.paddingLeft = padLeft;
152
+
153
+ const toggle = document.createElement("button");
154
+ toggle.type = "button";
155
+ toggle.dataset.navToggle = "";
156
+ toggle.setAttribute("aria-controls", submenuId);
157
+ toggle.setAttribute("aria-expanded", String(open));
158
+ toggle.setAttribute("aria-label", `Toggle ${item.label} section`);
159
+ toggle.className =
160
+ "shrink-0 rounded outline-none ring-sidebar-ring focus-visible:ring-2";
161
+ toggle.innerHTML =
162
+ '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="size-4 shrink-0 transition-transform duration-200" data-chevron aria-hidden="true"><polyline points="9 18 15 12 9 6"/></svg>';
163
+ row.appendChild(toggle);
164
+
165
+ if (item.icon) {
166
+ const iconSpan = document.createElement("span");
167
+ iconSpan.className = "shrink-0 [&>svg]:size-4";
168
+ iconSpan.innerHTML = item.icon;
169
+ row.appendChild(iconSpan);
170
+ }
171
+
172
+ const link = document.createElement("a");
173
+ link.className =
174
+ "min-w-0 flex-1 truncate text-inherit no-underline outline-none ring-sidebar-ring focus-visible:ring-2";
175
+ link.href = item.href;
176
+ link.textContent = item.label;
177
+ link.dataset.navHref = item.href; // rehighlight keys off this
178
+ if (active) link.dataset.active = "true";
179
+ row.appendChild(link);
180
+
181
+ if (item.mark) {
182
+ // A SUBTREE mark describes DESCENDANTS — never strike through this
183
+ // row for it (a surviving group whose child was deleted would read
184
+ // as a deleted section).
185
+ if (!item.mark.subtree) link.dataset.navMarkRow = item.mark.kind;
186
+ row.appendChild(buildMark(item.mark));
187
+ }
188
+
189
+ const submenu = document.createElement("ul");
190
+ submenu.id = submenuId;
191
+ submenu.dataset.navSubmenu = "";
192
+ submenu.className = "flex min-w-0 flex-col";
193
+ submenu.dataset.sidebar = "nav-tree";
194
+ submenu.dataset.level = String(level + 1);
195
+ for (const child of item.children!) {
196
+ submenu.appendChild(renderItem(child, current, level + 1));
197
+ }
198
+ if (!open) submenu.hidden = true;
199
+
200
+ toggle.addEventListener("click", () => {
201
+ const isOpen = toggle.getAttribute("aria-expanded") === "true";
202
+ toggle.setAttribute("aria-expanded", String(!isOpen));
203
+ submenu.hidden = isOpen;
204
+ });
205
+
206
+ li.appendChild(row);
207
+ li.appendChild(submenu);
208
+ } else if (hasChildren) {
209
+ // Pure grouping label (no href): native <details>/<summary> is fully
210
+ // accessible here — the summary is the only interactive control, and
211
+ // its label is a plain <span>. Zero-JS expand/collapse.
212
+ const details = document.createElement("details");
213
+ if (active || hasActiveDescendant(item, current)) details.open = true;
214
+
215
+ const summary = document.createElement("summary");
216
+ summary.className = [
217
+ "flex w-full min-w-0 cursor-pointer items-center gap-2 rounded-md text-sm text-sidebar-foreground outline-none [list-style:none] ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&::-webkit-details-marker]:hidden",
218
+ heightClass,
219
+ ]
220
+ .filter(Boolean)
221
+ .join(" ");
222
+ summary.style.paddingLeft = padLeft;
223
+
224
+ summary.innerHTML =
225
+ '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="size-4 shrink-0 transition-transform duration-200" data-chevron aria-hidden="true"><polyline points="9 18 15 12 9 6"/></svg>';
226
+
227
+ if (item.icon) {
228
+ const iconSpan = document.createElement("span");
229
+ iconSpan.className = "shrink-0 [&>svg]:size-4";
230
+ iconSpan.innerHTML = item.icon;
231
+ summary.appendChild(iconSpan);
232
+ }
233
+
234
+ const label = document.createElement("span");
235
+ label.className = "min-w-0 flex-1 truncate";
236
+ label.textContent = item.label;
237
+ summary.appendChild(label);
238
+
239
+ // A collapsed group HIDES its children, so a change inside must
240
+ // signal outward — the same visibility rule the diff renderer
241
+ // applies to tabs.
242
+ if (item.mark) summary.appendChild(buildMark(item.mark));
243
+
244
+ details.appendChild(summary);
245
+
246
+ const childUl = document.createElement("ul");
247
+ childUl.className = "flex min-w-0 flex-col";
248
+ childUl.dataset.sidebar = "nav-tree";
249
+ childUl.dataset.level = String(level + 1);
250
+ for (const child of item.children!) {
251
+ childUl.appendChild(renderItem(child, current, level + 1));
252
+ }
253
+ details.appendChild(childUl);
254
+
255
+ li.appendChild(details);
256
+ } else {
257
+ const a = document.createElement("a");
258
+ a.href = item.href || "#";
259
+ a.className = [
260
+ "flex w-full min-w-0 items-center gap-2 rounded-md text-sm text-sidebar-foreground outline-none ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2",
261
+ heightClass,
262
+ active ? "bg-sidebar-accent font-medium text-sidebar-accent-foreground" : "",
263
+ ]
264
+ .filter(Boolean)
265
+ .join(" ");
266
+ a.style.paddingLeft = padLeft;
267
+ if (active) a.dataset.active = "true";
268
+ if (item.href) a.dataset.navHref = item.href;
269
+
270
+ // Spacer to align leaf text with branch text (which has a chevron).
271
+ const spacer = document.createElement("span");
272
+ spacer.className = "size-4 shrink-0";
273
+ a.appendChild(spacer);
274
+
275
+ if (item.icon) {
276
+ const iconSpan = document.createElement("span");
277
+ iconSpan.className = "shrink-0 [&>svg]:size-4";
278
+ iconSpan.innerHTML = item.icon;
279
+ a.appendChild(iconSpan);
280
+ }
281
+
282
+ const label = document.createElement("span");
283
+ label.className = "min-w-0 flex-1 truncate";
284
+ label.textContent = item.label;
285
+ a.appendChild(label);
286
+
287
+ if (item.mark) {
288
+ // strikethrough only for a page that IS removed, never for an
289
+ // aggregate about its children
290
+ if (!item.mark.subtree) a.dataset.navMarkRow = item.mark.kind;
291
+ a.appendChild(buildMark(item.mark));
292
+ }
293
+
294
+ li.appendChild(a);
295
+ }
296
+
297
+ return li;
298
+ }
299
+
300
+ /**
301
+ * Section scope (`data-nav-scope="section"`): the page's section only, under
302
+ * the section menu — the same functions DocsLayout's server render uses.
303
+ */
304
+ export function renderScoped(nav: NavItem[], current: string, home: string, root: HTMLElement, locate: string = current): void {
305
+ const opts = { home };
306
+ // `locate`: an unlisted page's place in the listed nav (data-locate-path); it marks nothing current
307
+ renderTree(scopeNav(nav, locate, "section", opts).items, current, root);
308
+ const menu = sectionSwitcherHtml({ ...sectionMenu(nav, locate, opts), homeHref: home });
309
+ if (menu) root.insertAdjacentHTML("afterbegin", menu);
310
+ }
311
+
312
+ export function renderTree(items: NavItem[], current: string, root: HTMLElement): void {
313
+ const ul = document.createElement("ul");
314
+ ul.className =
315
+ "flex min-w-0 flex-col w-full group-data-[collapsible=icon]:hidden";
316
+ ul.dataset.sidebar = "nav-tree";
317
+ ul.dataset.level = "0";
318
+ for (const item of items) {
319
+ ul.appendChild(renderItem(item, current, 0));
320
+ }
321
+ // Replace skeleton in one DOM op so there's no flash of partial state.
322
+ root.replaceChildren(ul);
323
+ root.removeAttribute("aria-busy");
324
+ }
325
+
326
+ /**
327
+ * Re-highlight the active item without rebuilding the whole tree.
328
+ * Used on `astro:page-load` when view transitions land on a new
329
+ * route — we re-toggle the `data-active` attribute and re-apply the
330
+ * active classes, then expand the new active branch's ancestors.
331
+ *
332
+ * Cheaper than a full re-render (no fetch, no DOM rebuild). For
333
+ * the wider hydration loop we still re-render when a brand-new nav
334
+ * structure is needed (e.g. switching versions), but path-only
335
+ * navigation just re-highlights.
336
+ */
337
+ function rehighlight(root: HTMLElement, current: string): void {
338
+ const ACTIVE_CLASSES = [
339
+ "bg-sidebar-accent",
340
+ "font-medium",
341
+ "text-sidebar-accent-foreground",
342
+ ];
343
+ const items = root.querySelectorAll<HTMLElement>("[data-nav-href]");
344
+ for (const el of Array.from(items)) {
345
+ const href = el.dataset.navHref;
346
+ const active = !!href && normalize(href) === current;
347
+ if (active) {
348
+ el.dataset.active = "true";
349
+ el.classList.add(...ACTIVE_CLASSES);
350
+ } else {
351
+ delete el.dataset.active;
352
+ el.classList.remove(...ACTIVE_CLASSES);
353
+ }
354
+ }
355
+ // Expand ancestors of the new active item — both native <details>
356
+ // groups and the button-driven [data-nav-submenu] disclosures used by
357
+ // section-landing (href) branches.
358
+ const active = root.querySelector<HTMLElement>('[data-active="true"]');
359
+ if (active) {
360
+ let parent: HTMLElement | null = active.parentElement;
361
+ while (parent) {
362
+ if (parent.tagName === "DETAILS") {
363
+ (parent as HTMLDetailsElement).open = true;
364
+ }
365
+ if (parent.matches("[data-nav-submenu]")) {
366
+ parent.hidden = false;
367
+ const toggle = root.querySelector<HTMLElement>(
368
+ `[data-nav-toggle][aria-controls="${parent.id}"]`,
369
+ );
370
+ toggle?.setAttribute("aria-expanded", "true");
371
+ }
372
+ parent = parent.parentElement;
373
+ }
374
+ }
375
+ }
376
+
377
+ /**
378
+ * Public entry point. Called once from `<DocsNavClient />`'s inline
379
+ * script tag. Idempotent — subsequent calls (e.g. from view
380
+ * transitions) are no-ops once the tree has been rendered; they just
381
+ * re-highlight against the new pathname.
382
+ */
383
+ export async function hydrateDocsNav(): Promise<void> {
384
+ const root = document.getElementById("docs-nav-root");
385
+ if (!root) return;
386
+
387
+ const navUrl = root.dataset.navUrl;
388
+ if (!navUrl) {
389
+ console.warn("docs-nav: missing data-nav-url");
390
+ return;
391
+ }
392
+ const current = normalize(root.dataset.currentPath || location.pathname);
393
+ const basePath = root.dataset.basePath || "";
394
+ const namespace = root.dataset.namespace || undefined;
395
+ const version = root.dataset.version || undefined;
396
+ const locale = root.dataset.locale || undefined;
397
+ const rootVersion = root.dataset.rootVersion || undefined;
398
+ const versionSegments = (root.dataset.versionSegments || "").split(" ").filter(Boolean);
399
+
400
+ try {
401
+ const nav = await fetchNav(navUrl);
402
+ const filtered = filterNavByAxis(nav, {
403
+ // Pass basePath through as-is — an empty basePath (root-served
404
+ // site) must stay "", matching the SSR path's `?? "/docs"`
405
+ // (which keeps ""). Coercing "" → "/docs" makes the filter look
406
+ // for `/docs/…` bucket hrefs that don't exist and blanks the
407
+ // whole sidebar on a root-served multi-source site.
408
+ basePath,
409
+ namespace: namespace || undefined,
410
+ version: version || undefined,
411
+ locale: locale || undefined,
412
+ ...(rootVersion ? { rootVersion, versionSegments } : {}),
413
+ });
414
+ if (root.dataset.navScope === "section") {
415
+ const locate = root.dataset.locatePath ? normalize(root.dataset.locatePath) : current;
416
+ renderScoped(filtered, current, root.dataset.home || basePath || "/", root, locate);
417
+ }
418
+ else renderTree(filtered, current, root);
419
+ } catch (err) {
420
+ console.error("docs-nav: hydration failed", err);
421
+ root.setAttribute("aria-busy", "false");
422
+ // Keep skeleton so layout doesn't collapse on failure; a real
423
+ // user will reload or follow the noscript link.
424
+ }
425
+ }
426
+
427
+ // Re-run on view transitions. astro:page-load fires both on initial
428
+ // load and after each ClientRouter transition; the module-level
429
+ // `navPromise` cache makes the post-transition path a fast
430
+ // highlight-only pass without re-fetching.
431
+ document.addEventListener("astro:page-load", () => {
432
+ const root = document.getElementById("docs-nav-root");
433
+ if (!root) return;
434
+ // If tree is already rendered (no aria-busy), just re-highlight. (The root
435
+ // is not persisted across transitions, so a new page always hydrates, from
436
+ // the cached nav: a section-scoped sidebar is rebuilt for its own section.)
437
+ if (root.getAttribute("aria-busy") === null) {
438
+ const current = normalize(root.dataset.currentPath || location.pathname);
439
+ rehighlight(root, current);
440
+ } else {
441
+ void hydrateDocsNav();
442
+ }
443
+ });
package/src/json-ld.ts CHANGED
@@ -1,55 +1,6 @@
1
1
  /**
2
- * JSON-LD helpers — pure functions consumed by DocsLayout to
3
- * decide which Schema.org `@type` to emit and to normalize the
4
- * `customJsonLd` prop shape.
5
- *
6
- * The 100daysofdocs SEO audit flagged that DocsLayout was emitting
7
- * `Article` for every page regardless of intent — tutorials and
8
- * how-to pages should render as `HowTo` for SERP rich results.
9
- * This module owns the type selection so it's testable without
10
- * spinning up an Astro renderer.
2
+ * JSON-LD helpers for DocsLayout. They live in `@dogsbay/site-files`,
3
+ * which dogsbay-ssg uses too, so both pipelines emit the same blocks.
11
4
  */
12
-
13
- /**
14
- * Map a `meta.type` value (the open-string `pageType` prop on
15
- * DocsLayout) to a Schema.org `@type`.
16
- *
17
- * The mapping intentionally accepts a few common spelling
18
- * variants (`"how-to"` / `"howto"`, `"reference"` / `"ref"` /
19
- * `"api"`) so writers don't have to learn one canonical spelling
20
- * to get the right structured data. Anything else falls back to
21
- * `Article`, which is Google's "general docs page" assumption.
22
- */
23
- export function jsonLdTypeFor(pageType: string | undefined): string {
24
- switch (pageType) {
25
- case "tutorial":
26
- case "how-to":
27
- case "howto":
28
- return "HowTo";
29
- case "reference":
30
- case "ref":
31
- case "api":
32
- return "TechArticle";
33
- case "course":
34
- return "Course";
35
- default:
36
- return "Article";
37
- }
38
- }
39
-
40
- /**
41
- * Normalize the `customJsonLd` prop into an array. DocsLayout
42
- * accepts either a single object (most common case — one extra
43
- * Course / Organization block) or an array (sites that layer
44
- * several blocks per page).
45
- *
46
- * Returns an empty array for `undefined` so the template can
47
- * iterate uniformly without conditional rendering.
48
- */
49
- export function normalizeCustomJsonLd(
50
- raw: Record<string, unknown> | Record<string, unknown>[] | undefined,
51
- ): Record<string, unknown>[] {
52
- if (!raw) return [];
53
- if (Array.isArray(raw)) return raw;
54
- return [raw];
55
- }
5
+ export { jsonLdTypeFor, normalizeCustomJsonLd, buildArticleJsonLd, buildWebSiteJsonLd } from "@dogsbay/site-files";
6
+ export type { BuildArticleJsonLdOptions } from "@dogsbay/site-files";
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Internal/external link-icon affordance — the tiny bit of logic behind
3
+ * the `data-link-icons` + `--db-link-icon-*` attributes DocsLayout stamps
4
+ * on `<body>`. Classification itself is pure CSS (by href shape); this
5
+ * only turns the configured glyphs into the attribute + custom-property
6
+ * values. See plans/link-resolution-and-icons.md.
7
+ */
8
+
9
+ export interface LinkIcons {
10
+ /** Glyph after external links (absolute / protocol-relative href). */
11
+ external?: string;
12
+ /** Glyph after internal links (root / relative href). */
13
+ internal?: string;
14
+ }
15
+
16
+ export interface LinkIconAttrs {
17
+ /**
18
+ * Space-separated active kinds for `data-link-icons` (`"external"`,
19
+ * `"internal"`, or both) — undefined when the feature is off, so the
20
+ * attribute is omitted entirely.
21
+ */
22
+ tokens?: string;
23
+ /**
24
+ * Inline `style` value setting the `--db-link-icon-*` custom
25
+ * properties to the (single-quoted, CSS-string-safe) glyphs —
26
+ * undefined when nothing is active.
27
+ */
28
+ style?: string;
29
+ }
30
+
31
+ /** CSS-string-escape a glyph so it's a valid single-quoted `content:` value. */
32
+ function cssString(glyph: string): string {
33
+ return glyph.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
34
+ }
35
+
36
+ /**
37
+ * Build the `<body>` attributes for the link-icon feature. A side is
38
+ * active only when its glyph is a non-empty string; an absent config (or
39
+ * all-empty) yields `{}` so DocsLayout emits no attributes.
40
+ */
41
+ export function linkIconAttrs(icons: LinkIcons | undefined): LinkIconAttrs {
42
+ const external = icons?.external?.trim() ? icons.external : "";
43
+ const internal = icons?.internal?.trim() ? icons.internal : "";
44
+ const tokens = [external ? "external" : "", internal ? "internal" : ""]
45
+ .filter(Boolean)
46
+ .join(" ");
47
+ const style = [
48
+ external ? `--db-link-icon-external: '${cssString(external)}'` : "",
49
+ internal ? `--db-link-icon-internal: '${cssString(internal)}'` : "",
50
+ ]
51
+ .filter(Boolean)
52
+ .join("; ");
53
+ return { tokens: tokens || undefined, style: style || undefined };
54
+ }