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

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.
@@ -0,0 +1,20 @@
1
+ /*
2
+ * The section menu's entries (section-switcher.ts). One short class per
3
+ * entry instead of a Tailwind list repeated on each: Cloudflare's menu has
4
+ * 115 entries, and the repeated classes were 17.7 KB of every page.
5
+ * Plain CSS over the theme tokens, so dogsbay-ssg copies this file as it is.
6
+ */
7
+ .db-section-link {
8
+ display: flex;
9
+ border-radius: calc(var(--radius) - 4px);
10
+ padding: 0.375rem 0.5rem;
11
+ color: var(--foreground);
12
+ text-decoration: none;
13
+ }
14
+ .db-section-link:hover {
15
+ background-color: var(--accent);
16
+ }
17
+ .db-section-link[aria-current="true"] {
18
+ background-color: var(--accent);
19
+ font-weight: 500;
20
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * The section menu of a sidebar scoped to one section (`build.navScope:
3
+ * section`): a link home, where the sidebar lists every section, and a
4
+ * `<details>` list of the sections like ProductSwitcher's, which works
5
+ * without JS. The markup is built HERE ONLY, as a string, so the server
6
+ * render (DocsLayout), the client-built sidebar (docs-nav-client.ts) and
7
+ * dogsbay-ssg (which copies this file, as it copies site-chrome.ts) cannot
8
+ * drift. No imports, so a copy runs on its own.
9
+ *
10
+ * The data comes from `sectionMenu` in @dogsbay/site-files. The entries are
11
+ * styled by section-switcher.css (a host includes it once), not per entry.
12
+ */
13
+
14
+ export interface SectionSwitcherEntry {
15
+ label: string;
16
+ href: string;
17
+ /** The section's position (`sectionMenu` gives it): the current one is matched by it when set. */
18
+ index?: number;
19
+ }
20
+
21
+ export interface SectionSwitcherOptions {
22
+ entries: readonly SectionSwitcherEntry[];
23
+ /** The page's section; none on a page outside every section. */
24
+ current?: SectionSwitcherEntry;
25
+ /** The site's home page: where the sidebar lists every section. */
26
+ homeHref: string;
27
+ /** Default "All sections". */
28
+ homeLabel?: string;
29
+ /** Read before the section's name, and shown when there is none. Default "Section". */
30
+ placeholder?: string;
31
+ }
32
+
33
+ const ESC: Record<string, string> = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
34
+ function esc(s: string): string {
35
+ return s.replace(/[&<>"']/g, (c) => ESC[c]!);
36
+ }
37
+
38
+ const CHEVRON =
39
+ '<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="shrink-0 transition-transform group-open/section:rotate-180" aria-hidden="true"><polyline points="6 9 12 15 18 9"/></svg>';
40
+ const BACK =
41
+ '<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="15 18 9 12 15 6"/></svg>';
42
+
43
+ /** The menu's HTML; empty when there are no sections to list. */
44
+ export function sectionSwitcherHtml(o: SectionSwitcherOptions): string {
45
+ if (!o.entries.length) return "";
46
+ const placeholder = o.placeholder ?? "Section";
47
+ const home = o.homeLabel ?? "All sections";
48
+ const items = o.entries
49
+ .map((e) => {
50
+ const cur =
51
+ o.current !== undefined &&
52
+ (e.index !== undefined && o.current.index !== undefined ? e.index === o.current.index : e.href === o.current.href);
53
+ // styled by section-switcher.css: one short class, not a class list per entry
54
+ return `<li><a href="${esc(e.href)}"${cur ? ' aria-current="true"' : ""} class="db-section-link">${esc(e.label)}</a></li>`;
55
+ })
56
+ .join("");
57
+ const name = o.current
58
+ ? `<span class="sr-only">${esc(placeholder)}: </span><span class="min-w-0 flex-1 truncate text-left font-medium">${esc(o.current.label)}</span>`
59
+ : `<span class="min-w-0 flex-1 truncate text-left text-muted-foreground">${esc(placeholder)}</span>`;
60
+ return (
61
+ `<div class="db-section-switcher flex flex-col gap-1 px-2 pb-2 group-data-[collapsible=icon]:hidden" data-section-switcher>` +
62
+ (o.current
63
+ ? `<a href="${esc(o.homeHref)}" class="flex items-center gap-1 px-1 text-xs text-sidebar-foreground/70 no-underline hover:text-sidebar-foreground" data-section-home>${BACK}${esc(home)}</a>`
64
+ : "") +
65
+ `<details class="group/section relative">` +
66
+ `<summary class="flex w-full cursor-pointer list-none items-center gap-1 rounded-md border border-border px-3 py-1.5 text-sm hover:bg-sidebar-accent [&::-webkit-details-marker]:hidden">${name}${CHEVRON}</summary>` +
67
+ `<ul class="absolute inset-x-0 z-50 mt-1 max-h-[60vh] overflow-y-auto rounded-md border border-border bg-popover p-1 text-sm shadow-md">${items}</ul>` +
68
+ `</details></div>`
69
+ );
70
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * The site's chrome as DocsLayout draws it: the `chrome` object format-astro writes into
3
+ * site.json (its `chromeData`), links already carrying the site's prefix, texts already HTML
4
+ * (@dogsbay/site-files inline Markdown), icons already SVG. dogsbay-ssg draws the same keys with
5
+ * its own markup and these classes. See plans/site-chrome.md.
6
+ */
7
+ export interface SiteChromeLink {
8
+ label: string;
9
+ href: string;
10
+ }
11
+ export interface SiteChromeMenu {
12
+ label: string;
13
+ items: SiteChromeLink[];
14
+ }
15
+ export interface SiteChromeSocial {
16
+ label: string;
17
+ href: string;
18
+ svg: string;
19
+ }
20
+ export interface SiteChromeData {
21
+ colorMode?: "light" | "dark" | "system";
22
+ logo?: { light: string; dark?: string; alt: string; replacesName: boolean };
23
+ /** `key` (format-astro): the stored id, with the site's prefix; older site.json files have only `id`. */
24
+ announcement?: { id: string; key?: string; html: string; tone: string; closeable: boolean };
25
+ header?: { links: Array<SiteChromeLink | SiteChromeMenu>; social: SiteChromeSocial[] };
26
+ footer?: { columns: Array<{ title: string; links: SiteChromeLink[] }>; social: SiteChromeSocial[] };
27
+ }
28
+
29
+ export const isMenu = (l: SiteChromeLink | SiteChromeMenu): l is SiteChromeMenu => "items" in l;
30
+
31
+ /** An http(s) address on another site: opened as the version menu's are, in the same tab, marked external for link icons. */
32
+ export const isExternal = (href: string): boolean => /^https?:\/\//i.test(href);
33
+
34
+ /** The announcement's colours by tone: the callout tokens, so the theme and dark mode apply. */
35
+ export const ANNOUNCEMENT_TONE_CLASS: Record<string, string> = {
36
+ note: "border-note/40 bg-note/15",
37
+ tip: "border-tip/40 bg-tip/15",
38
+ warning: "border-warning/40 bg-warning/20",
39
+ caution: "border-danger/40 bg-danger/15",
40
+ };
41
+
42
+ /** The width the header's links show in the bar from (in the sidebar's list below it); `never`: the list only. */
43
+ export type LinksFrom = "lg" | "xl" | "2xl" | "never";
44
+
45
+ /**
46
+ * Where the header's links fit: the first width at which their estimated width fits beside what
47
+ * else the header holds, or `never`. Estimated from the labels (about 6.2 px a character at the
48
+ * header's text size, 28 px padding a link, 14 px a dropdown's chevron) against the header beside
49
+ * the 256 px sidebar, less the trigger and padding (80 px) and the menus: about 520 px for a
50
+ * crowded header (product, version, page actions, icons), 210 px otherwise (search with its
51
+ * text, the icons). A crowded header starts at xl. Measured on Tigera's (47 characters, 4 links:
52
+ * xl) and the products fixture; a long navbar stays in the sidebar rather than push the page wide.
53
+ */
54
+ export function headerLinksFrom(links: Array<SiteChromeLink | SiteChromeMenu>, crowded: boolean): LinksFrom {
55
+ const est = links.reduce((n, l) => n + l.label.length * 6.2 + 28 + (isMenu(l) ? 14 : 0), 0);
56
+ const menus = crowded ? 520 : 210;
57
+ const widths: Array<[LinksFrom, number]> = [["lg", 1024], ["xl", 1280], ["2xl", 1536]];
58
+ for (const [from, width] of widths) {
59
+ if (crowded && from === "lg") continue;
60
+ if (est <= width - 256 - 80 - menus) return from;
61
+ }
62
+ return "never";
63
+ }
package/src/switcher.ts CHANGED
@@ -7,11 +7,37 @@
7
7
  * `format-astro/src/project.ts` (the emitter side).
8
8
  */
9
9
 
10
+ import { limitVersionRows } from "@dogsbay/site-files";
11
+
10
12
  export interface AxisEntry {
11
13
  id: string;
12
14
  label?: string;
13
15
  eol?: boolean;
16
+ /** Pre-release mark (version axis only) — the moving next/beta head. */
17
+ prerelease?: boolean;
18
+ /**
19
+ * Served but kept OFF the switcher (version axis only). Marks the number
20
+ * a `latest` alias points at, so the dropdown shows one "3.32 (latest)"
21
+ * row instead of both "latest" and "3.32".
22
+ */
23
+ hidden?: boolean;
14
24
  default?: boolean;
25
+ /**
26
+ * Served at the site root (version axis only; `versions[].path: ""` on the
27
+ * default version): its pages have no version segment, so its landing
28
+ * page is `<basePath>/`, and its per-page URLs come from the variants.
29
+ */
30
+ root?: boolean;
31
+ /** With a `products:` block: the version's home URL, where the row goes when the page is not in it. */
32
+ home?: string;
33
+ /** "Version: <label>" above each page's title (version axis only). */
34
+ badge?: boolean;
35
+ }
36
+
37
+ /** The version menu's links (hrefs as served) and limit, from `versionMenu:` (@dogsbay/site-files version-menu.ts). */
38
+ export interface VersionMenuData {
39
+ links: Array<{ label: string; href: string }>;
40
+ limit?: number;
15
41
  }
16
42
 
17
43
  export interface SwitcherVariant {
@@ -24,6 +50,70 @@ export interface SwitcherMap {
24
50
  versions: AxisEntry[];
25
51
  locales: AxisEntry[];
26
52
  byLogicalKey: Record<string, SwitcherVariant[]>;
53
+ /**
54
+ * With a `products:` block: each product's version rows per locale
55
+ * (`<product|_>/<locale|_>`), config order, hidden left out, with homes.
56
+ */
57
+ productVersions?: Record<string, AxisEntry[]>;
58
+ /**
59
+ * With a `products:` block and two or more products: the product menu per
60
+ * locale (`<locale|_>`), block order, each entry the product's home.
61
+ */
62
+ products?: Record<string, ProductMenuEntry[]>;
63
+ /** Per product name (`_`: the site-wide versions), the version menu's links and limit. */
64
+ versionMenu?: Record<string, VersionMenuData>;
65
+ /** Each unit's version banner, keyed `<product|_>/<locale|_>/<version>` (format-astro `versionBanners`). */
66
+ banners?: Record<string, VersionBannerData>;
67
+ }
68
+
69
+ /** A unit's version banner: its own text or a kind worded here, and the default version it points to. */
70
+ export type VersionBannerData = ({ kind: "custom"; text: string } | { kind: "eol" | "prerelease" | "old" }) & { latest?: { id: string; label: string; home: string } };
71
+
72
+ /** The banner's words, as dogsbay-ssg's English strings. */
73
+ export interface VersionBannerWording {
74
+ old: string;
75
+ eol: string;
76
+ prerelease: string;
77
+ goLatest: string;
78
+ }
79
+
80
+ export const VERSION_BANNER_WORDING: VersionBannerWording = {
81
+ old: "You are viewing documentation for an older version.",
82
+ eol: "This version is no longer maintained.",
83
+ prerelease: "This version is not released yet.",
84
+ goLatest: "Go to the latest version",
85
+ };
86
+
87
+ export interface ProductMenuEntry {
88
+ name: string;
89
+ label: string;
90
+ home: string;
91
+ }
92
+
93
+ export interface ProductMenu {
94
+ /** The page's product, or undefined on a page outside every product (the menu reads "Product"). */
95
+ current?: ProductMenuEntry;
96
+ entries: ProductMenuEntry[];
97
+ }
98
+
99
+ /**
100
+ * The product menu for a page (the same rules as dogsbay-ssg's): only with two
101
+ * or more products, in the page's locale (else the site's first), each entry
102
+ * going to that product's home — products do not share pages, so the current
103
+ * page is never looked up. A page outside every product has no current entry.
104
+ */
105
+ export function productMenu(switcherMap: SwitcherMap, ms?: Pick<MultiSourceMeta, "namespace" | "locale">): ProductMenu | undefined {
106
+ const byLocale = switcherMap.products;
107
+ if (!byLocale) return undefined;
108
+ const entries = byLocale[ms?.locale ?? "_"] ?? Object.values(byLocale)[0];
109
+ if (!entries || entries.length < 2) return undefined;
110
+ return { current: entries.find((e) => e.name === ms?.namespace), entries };
111
+ }
112
+
113
+ /** The current page's product version rows, when the site has a `products:` block. */
114
+ export function productVersionEntries(switcherMap: SwitcherMap, ms: MultiSourceMeta): AxisEntry[] | undefined {
115
+ if (!switcherMap.productVersions) return undefined;
116
+ return switcherMap.productVersions[`${ms.namespace ?? "_"}/${ms.locale ?? "_"}`] ?? [];
27
117
  }
28
118
 
29
119
  export interface MultiSourceMeta {
@@ -73,9 +163,32 @@ export interface BuildRowsInput {
73
163
  multiSource: MultiSourceMeta;
74
164
  }
75
165
 
166
+ /**
167
+ * Order two version ids. Compares numeric components left-to-right
168
+ * (`3.32` > `3.31`, `3.23-2` > `3.23-1`); a non-numeric alias (`latest`,
169
+ * `next`) sorts ABOVE any numbered version so descending order puts it
170
+ * first. When NEITHER id has any digits — a non-semver / codename scheme
171
+ * (`Boron`, `Argon`) — returns 0 so the sort is a no-op and the author's
172
+ * DECLARED order is preserved (JS sort is stable), rather than silently
173
+ * alphabetising and putting the newest release at the bottom.
174
+ */
175
+ export function compareVersionIds(a: string, b: string): number {
176
+ const na = (a.match(/\d+/g) ?? []).map(Number);
177
+ const nb = (b.match(/\d+/g) ?? []).map(Number);
178
+ if (na.length === 0 && nb.length === 0) return 0; // codenames → keep declared order
179
+ if (na.length === 0) return 1; // alias > number
180
+ if (nb.length === 0) return -1;
181
+ const len = Math.max(na.length, nb.length);
182
+ for (let i = 0; i < len; i++) {
183
+ const d = (na[i] ?? 0) - (nb[i] ?? 0);
184
+ if (d !== 0) return d;
185
+ }
186
+ return a.localeCompare(b);
187
+ }
188
+
76
189
  export function buildSwitcherRows(input: BuildRowsInput): SwitcherRow[] {
77
190
  const { axis, switcherMap, multiSource } = input;
78
- const entries = axis === "version" ? switcherMap.versions : switcherMap.locales;
191
+ const allEntries = axis === "version" ? switcherMap.versions : switcherMap.locales;
79
192
  const currentId =
80
193
  axis === "version" ? multiSource.version : multiSource.locale;
81
194
  const otherAxis: SwitcherAxis = axis === "version" ? "locale" : "version";
@@ -84,6 +197,65 @@ export function buildSwitcherRows(input: BuildRowsInput): SwitcherRow[] {
84
197
 
85
198
  const variants = switcherMap.byLogicalKey[logicalKeyFor(multiSource)] ?? [];
86
199
 
200
+ // A products: block: the product's own rows, in config order (the shared model's switcher)
201
+ const productRows = axis === "version" ? productVersionEntries(switcherMap, multiSource) : undefined;
202
+ if (productRows) {
203
+ return productRows.map((entry) => {
204
+ const match = variants.find((v) => v.version === entry.id && (otherCurrent === undefined || v.locale === otherCurrent));
205
+ return { entry, url: match?.url ?? null, isCurrent: entry.id === currentId };
206
+ });
207
+ }
208
+
209
+ // On a MULTI-PRODUCT (namespace-active) site the declared version list
210
+ // is the UNION across products, but a page's variants are same-namespace
211
+ // (the logical key is namespaced). Scope the version switcher to the
212
+ // versions this page's product actually has, so a Calico page never
213
+ // offers a Calico-Enterprise version. Single-product sites (no
214
+ // namespace) keep the full declared list, with fallbacks for pages
215
+ // missing in some version.
216
+ let entries = allEntries;
217
+ if (axis === "version" && multiSource.namespace !== undefined) {
218
+ const available = new Set(
219
+ variants.map((v) => v.version).filter((v): v is string => v !== undefined),
220
+ );
221
+ entries = allEntries.filter((e) => available.has(e.id) || e.id === currentId);
222
+ }
223
+
224
+ // The version dropdown always reads newest → oldest (3.32, 3.31, …),
225
+ // regardless of the declared order. Aliases (e.g. "latest") that don't
226
+ // parse as versions sort to the top, ahead of the numbers.
227
+ //
228
+ // `latest` alias + its target: a version marked `hidden` is the number
229
+ // the `latest` alias points at (Docusaurus's lastVersion). Show ONE row
230
+ // "3.32 (latest)" (linking to /latest/), derive its label from the hidden
231
+ // sibling, and drop hidden rows from the dropdown.
232
+ //
233
+ // The hidden number is DECLARED but NOT SERVED: `migrate-docusaurus
234
+ // --latest-alias` emits one source for the newest branch, at `latest`.
235
+ // That mirrors the source, where `versions: { "3.32": { path: "latest" } }`
236
+ // REPLACES the segment — docs.tigera.io has /calico/latest/ and no
237
+ // /calico/3.32/. Serving both invented a URL tree the source never had
238
+ // and duplicated every page of the newest release (338 on Calico) with
239
+ // no canonical. So the hidden entry is label-only metadata.
240
+ //
241
+ // `currentFoldedIntoLatest` still matters for a corpus that DOES serve
242
+ // the number (a hand-written config may), so a reader on `/3.32/…` has
243
+ // the merged `latest` row highlighted rather than no row at all. No
244
+ // `hidden` sibling → no merge.
245
+ let currentFoldedIntoLatest = false;
246
+ if (axis === "version") {
247
+ entries = [...entries].sort((a, b) => compareVersionIds(b.id, a.id));
248
+ const hiddenTarget = entries.find((e) => e.hidden && /\d/.test(e.id));
249
+ currentFoldedIntoLatest = hiddenTarget?.id === currentId;
250
+ entries = entries
251
+ .filter((e) => !e.hidden)
252
+ .map((e) =>
253
+ e.id === "latest" && hiddenTarget
254
+ ? { ...e, label: `${hiddenTarget.label ?? hiddenTarget.id} (latest)` }
255
+ : e,
256
+ );
257
+ }
258
+
87
259
  return entries.map((entry) => {
88
260
  const match = variants.find((v) => {
89
261
  // Match on this axis.
@@ -98,7 +270,7 @@ export function buildSwitcherRows(input: BuildRowsInput): SwitcherRow[] {
98
270
  return {
99
271
  entry,
100
272
  url: match?.url ?? null,
101
- isCurrent: entry.id === currentId,
273
+ isCurrent: entry.id === currentId || (entry.id === "latest" && currentFoldedIntoLatest),
102
274
  };
103
275
  });
104
276
  }
@@ -117,22 +289,92 @@ export function shouldRenderSwitcher(
117
289
  multiSource: MultiSourceMeta | undefined,
118
290
  ): boolean {
119
291
  if (!multiSource) return false;
120
- const entries = axis === "version" ? switcherMap.versions : switcherMap.locales;
121
- if (entries.length < 2) return false;
292
+ const entries = (axis === "version" ? productVersionEntries(switcherMap, multiSource) : undefined) ?? (axis === "version" ? switcherMap.versions : switcherMap.locales);
293
+ // Two or more versions a reader can pick (a hidden one is the number an alias serves), as dogsbay-ssg decides it
294
+ if (entries.filter((e) => !e.hidden).length < 2) return false;
122
295
  const id = axis === "version" ? multiSource.version : multiSource.locale;
123
296
  return id !== undefined;
124
297
  }
125
298
 
126
299
  /**
127
300
  * Fallback URL for a row whose target variant doesn't exist —
128
- * lands on the axis's "landing page" (`<basePath>/<id>/`).
301
+ * lands on the axis's "landing page" (`<basePath>/<id>/`, or
302
+ * `<basePath>/` for the version served at the root).
129
303
  * Lets the switcher always be clickable even when a page is
130
304
  * untranslated for some axis combo.
131
305
  */
132
306
  export function fallbackLandingUrl(
133
307
  basePath: string,
134
308
  axisEntryId: string,
309
+ atRoot = false,
135
310
  ): string {
136
311
  const trimmed = basePath.replace(/\/$/, "");
137
- return `${trimmed}/${axisEntryId}/`;
312
+ return atRoot ? `${trimmed}/` : `${trimmed}/${axisEntryId}/`;
313
+ }
314
+
315
+ /**
316
+ * The page's version menu extras: its product's (with a `products:` block),
317
+ * else the site's. Only for a menu that is shown, so its links come with it.
318
+ */
319
+ export function versionMenuFor(switcherMap: SwitcherMap, ms: Pick<MultiSourceMeta, "namespace">): VersionMenuData | undefined {
320
+ const menus = switcherMap.versionMenu;
321
+ if (!menus) return undefined;
322
+ return switcherMap.productVersions ? menus[ms.namespace ?? "_"] : menus._;
323
+ }
324
+
325
+ /**
326
+ * The menu's rows under `limit`: whether it shows is decided before (two or
327
+ * more versions), then the first `limit` rows are kept, plus the page's own.
328
+ */
329
+ export function limitRows(rows: SwitcherRow[], limit: number | undefined): SwitcherRow[] {
330
+ return limitVersionRows(rows, limit, (r) => r.isCurrent);
331
+ }
332
+
333
+ /**
334
+ * "Version: <label>" for a page whose version has `badge: true`, else
335
+ * undefined. The label is the one the version menu shows.
336
+ */
337
+ export function versionBadge(switcherMap: SwitcherMap | undefined, ms: MultiSourceMeta | undefined, wording = "Version: {label}"): string | undefined {
338
+ if (!switcherMap || !ms?.version) return undefined;
339
+ const entries = productVersionEntries(switcherMap, ms) ?? switcherMap.versions;
340
+ const entry = entries.find((e) => e.id === ms.version);
341
+ if (!entry?.badge) return undefined;
342
+ // The `latest` alias stands for the hidden number it serves (migrate-docusaurus --latest-alias)
343
+ const target = entry.id === "latest" ? [...entries].sort((a, b) => compareVersionIds(b.id, a.id)).find((e) => e.hidden && /\d/.test(e.id)) : undefined;
344
+ const shown = target ?? entry;
345
+ return wording.split("{label}").join(shown.label ?? shown.id);
346
+ }
347
+
348
+ /**
349
+ * The version banner over a page (dogsbay-ssg's `versionBanner`): the text, and a link to the same
350
+ * page in the default version, or to that version's home when the page is not there. Undefined on
351
+ * the default version, a hidden one, and a page outside every version.
352
+ */
353
+ export function versionBanner(
354
+ switcherMap: SwitcherMap | undefined,
355
+ ms: MultiSourceMeta | undefined,
356
+ wording: Partial<VersionBannerWording> = {},
357
+ ): { text: string; link?: { href: string; label: string } } | undefined {
358
+ if (!switcherMap?.banners || !ms?.version) return undefined;
359
+ const w = { ...VERSION_BANNER_WORDING, ...wording };
360
+ // The page's own unit, exactly: a fallback would hand it another product's or language's banner
361
+ const b = switcherMap.banners[`${ms.namespace ?? "_"}/${ms.locale ?? "_"}/${ms.version}`];
362
+ if (!b) return undefined;
363
+ const text = b.kind === "custom" ? b.text : b.kind === "eol" ? w.eol : b.kind === "prerelease" ? w.prerelease : w.old;
364
+ if (!b.latest) return { text };
365
+ const variants = switcherMap.byLogicalKey[`${ms.namespace ?? "docs"}/${ms.originalSlug}`] ?? [];
366
+ const same = variants.find((v) => v.version === b.latest!.id && (v.locale ?? undefined) === (ms.locale ?? undefined));
367
+ return { text, link: { href: same ? servedHref(same.url) : b.latest.home, label: w.goLatest } };
368
+ }
369
+
370
+ /**
371
+ * A variant's URL as the site serves the page (format-astro `pageHref`): a page is a folder, so
372
+ * `…/index` is its folder and the slash is kept; otherwise each link costs a redirect.
373
+ */
374
+ export function servedHref(url: string): string {
375
+ const at = url.search(/[?#]/);
376
+ const [path, rest] = at < 0 ? [url, ""] : [url.slice(0, at), url.slice(at)];
377
+ let p = path.replace(/\/+$/, "");
378
+ if (p === "index" || p.endsWith("/index")) p = p.slice(0, -"index".length).replace(/\/+$/, "");
379
+ return `${p}/${rest}`;
138
380
  }
@@ -33,6 +33,29 @@ export interface BuildChipsOptions {
33
33
  * text. URL still uses the slug.
34
34
  */
35
35
  labels?: Record<string, string>;
36
+ /**
37
+ * Color chips whose prefix has no `color` with a palette color
38
+ * hashed from the first segment (`autoTagColor`). Default false.
39
+ */
40
+ autoColor?: boolean;
41
+ }
42
+
43
+ /** Palette order for automatic colors. */
44
+ const AUTO_PALETTE: readonly TagPaletteName[] = ["blue", "amber", "emerald", "violet", "rose", "slate"];
45
+
46
+ /**
47
+ * A stable palette color for a tag segment: FNV-1a hash of the
48
+ * lowercased segment, modulo the palette. The same segment gets the
49
+ * same color on every page and every build; with more distinct tags
50
+ * than colors, colors repeat.
51
+ */
52
+ export function autoTagColor(segment: string): TagPaletteName {
53
+ let hash = 0x811c9dc5;
54
+ for (const ch of segment.toLowerCase()) {
55
+ hash ^= ch.codePointAt(0)!;
56
+ hash = Math.imul(hash, 0x01000193) >>> 0;
57
+ }
58
+ return AUTO_PALETTE[hash % AUTO_PALETTE.length];
36
59
  }
37
60
 
38
61
  export interface ChipModel {
@@ -109,39 +132,11 @@ export function resolveTagKeywords(
109
132
  }
110
133
 
111
134
  /**
112
- * Resolve the display label for a term identified by its fullPath
113
- * array (e.g. `["concept"]` or `["concept", "a11y"]`).
114
- *
115
- * Used by `<TaxonomyIndex>` term-cloud chips, `<TaxonomyTerm>`
116
- * page headings and breadcrumbs, and sub-tag pills — anywhere a
117
- * structural slug needs to render as a human label.
118
- *
119
- * Resolution order:
120
- * 1. `labels[fullSlug]` (joined fullPath) — explicit override
121
- * wins, regardless of depth.
122
- * 2. For top-level terms (`fullPath.length === 1`):
123
- * `prefixes[segment].label` — lets a top-level segment
124
- * (`concept`, `difficulty`) render as "Concept", "Difficulty".
125
- * 3. The leaf segment of the path — the rendered fallback for
126
- * deeper terms with no override.
127
- *
128
- * URLs continue to use the slug-form `fullPath`. Display only.
135
+ * Display label of a term path (`labels` override, then a top-level
136
+ * `prefixes` label, then the leaf). One implementation, shared with the
137
+ * search facet column: `@dogsbay/search/facets`.
129
138
  */
130
- export function resolveTermLabel(
131
- fullPath: readonly string[],
132
- prefixes?: Record<string, PrefixDisplay>,
133
- labels?: Record<string, string>,
134
- ): string {
135
- if (fullPath.length === 0) return "";
136
- const slug = fullPath.join("/");
137
- const override = labels?.[slug];
138
- if (override && override.length > 0) return override;
139
- if (fullPath.length === 1) {
140
- const prefixLabel = prefixes?.[fullPath[0]]?.label;
141
- if (prefixLabel && prefixLabel.length > 0) return prefixLabel;
142
- }
143
- return fullPath[fullPath.length - 1];
144
- }
139
+ export { resolveTermLabel } from "@dogsbay/search/facets";
145
140
 
146
141
  /**
147
142
  * Map raw tag slugs to render-ready chip models, applying prefix
@@ -164,7 +159,7 @@ export function buildChips(
164
159
  options: BuildChipsOptions,
165
160
  ): ChipModel[] {
166
161
  const safe = filterTags(tags);
167
- const { indexPath, prefixes, labels } = options;
162
+ const { indexPath, prefixes, labels, autoColor = false } = options;
168
163
 
169
164
  return safe.map((tag): ChipModel => {
170
165
  const href = `${indexPath}/${tag}/`;
@@ -182,7 +177,7 @@ export function buildChips(
182
177
  href,
183
178
  prefixLabel: null,
184
179
  leafLabel: overrideLeaf ?? tag,
185
- color: null,
180
+ color: autoColor ? autoTagColor(firstSegment) : null,
186
181
  };
187
182
  }
188
183
 
@@ -196,7 +191,7 @@ export function buildChips(
196
191
  href,
197
192
  prefixLabel: prefixEntry.label ?? null,
198
193
  leafLabel: leafLabel.length > 0 ? leafLabel : tag,
199
- color: prefixEntry.color ?? null,
194
+ color: prefixEntry.color ?? (autoColor ? autoTagColor(firstSegment) : null),
200
195
  };
201
196
  });
202
197
  }
package/src/toc-kind.css CHANGED
@@ -11,40 +11,40 @@
11
11
  line-height: 1.4;
12
12
  }
13
13
  .toc-kind-class {
14
- background-color: oklch(0.55 0.18 265 / 0.15);
15
- color: oklch(0.55 0.18 265);
14
+ background-color: oklch(0.44 0.18 265 / 0.15);
15
+ color: oklch(0.44 0.18 265);
16
16
  }
17
17
  .dark .toc-kind-class {
18
18
  background-color: oklch(0.7 0.15 265 / 0.2);
19
19
  color: oklch(0.7 0.15 265);
20
20
  }
21
21
  .toc-kind-meth {
22
- background-color: oklch(0.55 0.15 155 / 0.15);
23
- color: oklch(0.55 0.15 155);
22
+ background-color: oklch(0.44 0.15 155 / 0.15);
23
+ color: oklch(0.44 0.15 155);
24
24
  }
25
25
  .dark .toc-kind-meth {
26
26
  background-color: oklch(0.7 0.15 155 / 0.2);
27
27
  color: oklch(0.7 0.15 155);
28
28
  }
29
29
  .toc-kind-attr {
30
- background-color: oklch(0.6 0.15 55 / 0.15);
31
- color: oklch(0.6 0.15 55);
30
+ background-color: oklch(0.44 0.15 55 / 0.15);
31
+ color: oklch(0.44 0.15 55);
32
32
  }
33
33
  .dark .toc-kind-attr {
34
34
  background-color: oklch(0.75 0.15 55 / 0.2);
35
35
  color: oklch(0.75 0.15 55);
36
36
  }
37
37
  .toc-kind-func {
38
- background-color: oklch(0.55 0.18 330 / 0.15);
39
- color: oklch(0.55 0.18 330);
38
+ background-color: oklch(0.44 0.18 330 / 0.15);
39
+ color: oklch(0.44 0.18 330);
40
40
  }
41
41
  .dark .toc-kind-func {
42
42
  background-color: oklch(0.7 0.15 330 / 0.2);
43
43
  color: oklch(0.7 0.15 330);
44
44
  }
45
45
  .toc-kind-module {
46
- background-color: oklch(0.5 0.12 200 / 0.15);
47
- color: oklch(0.5 0.12 200);
46
+ background-color: oklch(0.44 0.12 200 / 0.15);
47
+ color: oklch(0.44 0.12 200);
48
48
  }
49
49
  .dark .toc-kind-module {
50
50
  background-color: oklch(0.65 0.12 200 / 0.2);