@dogsbay/docs-layout 0.2.0-beta.17 → 0.2.0-beta.170

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.
package/src/nav-filter.ts CHANGED
@@ -1,18 +1,17 @@
1
1
  /**
2
2
  * Multi-source nav filtering.
3
3
  *
4
- * When a docs site has multiple versions (or, in PR 5, locales)
5
- * configured, every page's emitted nav.json contains entries
6
- * from EVERY version. Without filtering, the sidebar shows
7
- * duplicate sections — once per version — which is confusing
8
- * UX (writers see "Glossary" twice).
4
+ * When a docs site has multiple products/versions/locales, every page's
5
+ * emitted nav.json contains entries from EVERY bucket. Without filtering,
6
+ * the sidebar shows a product's sections once per version, and every other
7
+ * product too — confusing UX. The fix: filter the nav tree to the current
8
+ * page's (namespace, locale, version) bucket.
9
9
  *
10
- * The fix: filter the nav tree to entries that match the
11
- * current page's version (or, eventually, locale). Pure
12
- * function; takes nav + axis filter, returns a pruned copy.
13
- *
14
- * The axis switchers handle navigation BETWEEN versions; the
15
- * sidebar nav reflects only the active axis bucket.
10
+ * The match is a single COMPOSED prefix in the canonical URL order
11
+ * `/<basePath>/<namespace>/<locale>/<version>/...` — whichever of those
12
+ * axes the current page carries. The axis switchers handle navigation
13
+ * BETWEEN buckets; the sidebar reflects only the active one. Pure
14
+ * function: nav + filter → pruned copy.
16
15
  */
17
16
 
18
17
  interface NavItem {
@@ -22,145 +21,87 @@ interface NavItem {
22
21
  }
23
22
 
24
23
  export interface NavFilter {
25
- /** Site basePath (e.g. "/docs"). Used to compose the version prefix. */
24
+ /** Site basePath (e.g. "" for root, "/docs"). */
26
25
  basePath: string;
27
- /**
28
- * Current page's effective version. When undefined, no
29
- * version filtering is applied — single-version sites pass
30
- * the full nav through unchanged.
31
- */
26
+ /** Current page's product/namespace segment (outermost), if any. */
27
+ namespace?: string;
28
+ /** Current page's locale segment (after namespace), if any. */
29
+ locale?: string;
30
+ /** Current page's version segment (innermost, next to the page), if any. */
32
31
  version?: string;
33
32
  /**
34
- * Current page's effective locale. When set, nav items are
35
- * filtered to those whose href starts with the corresponding
36
- * locale segment (`<basePath>/<locale>/`).
33
+ * The version served at the site root (`versions[].path: ""`): its pages
34
+ * have no version segment. When `version` is this one, the bucket is the
35
+ * namespace/locale prefix minus the other versions' folders
36
+ * (`versionSegments`) — the longest matching prefix wins.
37
37
  */
38
- locale?: string;
38
+ rootVersion?: string;
39
+ /** The other versions' URL segments, left out of the root version's bucket. */
40
+ versionSegments?: string[];
39
41
  }
40
42
 
41
43
  /**
42
- * Walk the nav tree and drop entries that don't belong to the
43
- * current version + locale. Group nodes (no `href`, with
44
- * `children`) survive iff any descendant survives — empty
45
- * groups are pruned.
46
- *
47
- * Items without `href` AND without `children` are unusual but
48
- * pass through unchanged (defensive — never silently drop a
49
- * node we don't understand).
50
- *
51
- * Both filters apply concurrently: a multi-version multi-locale
52
- * site filters by BOTH simultaneously, so an item must match
53
- * /<basePath>/<locale>/.../<version>/... structurally.
44
+ * The root-version fields of a `NavFilter`, from the switcherMap header
45
+ * (`versions[].root`). Empty when no version is served at the root.
54
46
  */
55
- export function filterNavByAxis(
56
- items: NavItem[],
57
- filter: NavFilter,
58
- ): NavItem[] {
59
- if (!filter.version && !filter.locale) return items;
60
-
61
- // Locale axis prefix is the OUTERMOST per the canonical URL
62
- // composition: /<basePath>/<locale>/<version>/<ns>/<slug>.
63
- // We check the locale prefix first (basePath/<locale>/), then
64
- // (when version is also active) check that <version> is the
65
- // immediately-following segment.
66
- const localePrefix = filter.locale
67
- ? prefixFor(filter.basePath, filter.locale)
68
- : null;
69
- const versionSegment = filter.version ?? null;
47
+ export function rootVersionFilter(
48
+ versions: Array<{ id: string; root?: boolean }> | undefined,
49
+ ): Pick<NavFilter, "rootVersion" | "versionSegments"> {
50
+ const root = versions?.find((v) => v.root)?.id;
51
+ if (!root) return {};
52
+ return { rootVersion: root, versionSegments: versions!.map((v) => v.id).filter((id) => id !== root) };
53
+ }
70
54
 
71
- return items.flatMap((item) =>
72
- filterOne(item, localePrefix, versionSegment, filter.basePath),
55
+ /**
56
+ * Prune the nav to the current page's bucket. Group nodes (no `href`,
57
+ * with `children`) survive iff a descendant survives; empty groups and
58
+ * childless/href-less nodes are dropped (else a non-current bucket's group
59
+ * lingers as a phantom header).
60
+ */
61
+ export function filterNavByAxis(items: NavItem[], filter: NavFilter): NavItem[] {
62
+ // Canonical order: namespace → locale → version. Only the axes the
63
+ // current page actually carries contribute to the match prefix.
64
+ const atRoot = filter.rootVersion !== undefined && filter.version === filter.rootVersion;
65
+ const segs = [filter.namespace, filter.locale, atRoot ? undefined : filter.version].filter(
66
+ (s): s is string => s !== undefined && s !== "",
73
67
  );
68
+ // The root version's bucket leaves out the other versions' folders under its prefix.
69
+ const others = atRoot ? (filter.versionSegments ?? []).filter((v) => v && v !== filter.rootVersion) : [];
70
+ if (segs.length === 0 && others.length === 0) return items;
71
+
72
+ const base = filter.basePath.replace(/\/$/, "");
73
+ const prefix = `${base}/${segs.join("/")}${segs.length ? "/" : ""}`;
74
+ const prefixNoSlash = segs.length ? prefix.replace(/\/$/, "") : base || "/";
75
+ const excluded = others.map((v) => `${prefix}${v}`);
76
+
77
+ return items.flatMap((item) => filterOne(item, prefix, prefixNoSlash, excluded));
74
78
  }
75
79
 
76
- function filterOne(
77
- item: NavItem,
78
- localePrefix: string | null,
79
- versionSegment: string | null,
80
- basePath: string,
81
- ): NavItem[] {
80
+ function filterOne(item: NavItem, prefix: string, prefixNoSlash: string, excluded: string[]): NavItem[] {
82
81
  if (item.children && item.children.length > 0) {
83
- const kept = item.children.flatMap((c) =>
84
- filterOne(c, localePrefix, versionSegment, basePath),
85
- );
82
+ const kept = item.children.flatMap((c) => filterOne(c, prefix, prefixNoSlash, excluded));
86
83
  if (kept.length === 0) return [];
87
84
  return [{ ...item, children: kept }];
88
85
  }
89
86
  if (item.href !== undefined) {
90
- if (!hrefMatchesAxes(item.href, localePrefix, versionSegment, basePath)) {
91
- return [];
92
- }
93
- return [item];
87
+ return hrefMatchesPrefix(item.href, prefix, prefixNoSlash) &&
88
+ !excluded.some((x) => hrefMatchesPrefix(item.href!, `${x}/`, x))
89
+ ? [item]
90
+ : [];
94
91
  }
95
- return [item];
96
- }
97
-
98
- /**
99
- * Check that an href belongs to the requested (locale, version)
100
- * combination. Either prefix can be null — meaning that axis
101
- * isn't being filtered.
102
- */
103
- function hrefMatchesAxes(
104
- href: string,
105
- localePrefix: string | null,
106
- versionSegment: string | null,
107
- basePath: string,
108
- ): boolean {
109
- // External URLs aren't axis-bucketed.
110
- if (/^[a-z][a-z0-9+.-]*:\/\//i.test(href) || href.startsWith("mailto:")) {
111
- return false;
112
- }
113
-
114
- // Step 1: locale check. If locale axis is active, the href
115
- // must be inside /<basePath>/<locale>/.
116
- if (localePrefix !== null) {
117
- if (!hrefMatchesPrefix(href, localePrefix)) return false;
118
- }
119
-
120
- // Step 2: version check. The version segment is positioned
121
- // AFTER the locale segment when both are active, otherwise
122
- // immediately after basePath.
123
- if (versionSegment !== null) {
124
- const baseTrimmed = basePath.replace(/\/$/, "");
125
- const localeSegStart = localePrefix
126
- ? localePrefix.replace(/\/$/, "")
127
- : baseTrimmed;
128
- const versionPrefix = `${localeSegStart}/${versionSegment}/`;
129
- const versionPrefixNoSlash = versionPrefix.replace(/\/$/, "");
130
- if (
131
- !href.startsWith(versionPrefix) &&
132
- href !== versionPrefixNoSlash
133
- ) {
134
- return false;
135
- }
136
- }
137
-
138
- return true;
139
- }
140
-
141
- /**
142
- * Compose the URL prefix for a given version under the
143
- * configured basePath. Always ends in `/` so prefix-matching
144
- * doesn't accept partial segments (`/docs/v1` shouldn't match
145
- * `/docs/v10/...`).
146
- */
147
- function prefixFor(basePath: string, segment: string): string {
148
- const base = basePath.replace(/\/$/, "");
149
- return `${base}/${segment}/`;
92
+ // Childless AND href-less: no navigation, no bucket membership. In a
93
+ // filtered view it must be dropped.
94
+ return [];
150
95
  }
151
96
 
152
97
  /**
153
- * Whether an href belongs to the given version prefix. Tolerates
154
- * trailing slashes and missing-trailing-slash variants — nav
155
- * importers don't all canonicalise the same way.
98
+ * Whether an href belongs to the composed bucket prefix. Tolerates the
99
+ * bucket's landing page itself (`/<prefix>` with no trailing slash);
100
+ * external URLs never match.
156
101
  */
157
- function hrefMatchesPrefix(href: string, prefix: string): boolean {
158
- // Skip external URLs.
102
+ function hrefMatchesPrefix(href: string, prefix: string, prefixNoSlash: string): boolean {
159
103
  if (/^[a-z][a-z0-9+.-]*:\/\//i.test(href) || href.startsWith("mailto:")) {
160
104
  return false;
161
105
  }
162
- // Match `/docs/v1/...` AND `/docs/v1` (the version's landing
163
- // page itself, if a writer linked to it directly).
164
- const trimmedPrefix = prefix.replace(/\/$/, "");
165
- return href.startsWith(prefix) || href === trimmedPrefix;
106
+ return href.startsWith(prefix) || href === prefixNoSlash;
166
107
  }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Pagefind result URLs, and the base they need.
3
+ *
4
+ * Pagefind stores each page's URL relative to the directory it indexed
5
+ * (`pagefind --site dist`), then prefixes every result with `baseUrl`. When
6
+ * the caller sets none, Pagefind derives it from where the bundle was loaded:
7
+ * the folder above `pagefind/`.
8
+ *
9
+ * That default is right for one of our two subpath layouts and wrong for the
10
+ * other, measured by decoding index fragments on live sites:
11
+ *
12
+ * | Deploy | Pages built into | Stored URL | Default base | Result |
13
+ * |---|---|---|---|---|
14
+ * | Workers subpath mount | `dist/<mount>/` (nested) | `/<mount>/page/` | `/<mount>/` | `/<mount>/<mount>/page/` — 404 |
15
+ * | GitHub Pages project | `dist/` (Astro `base`) | `/page/` | `/<repo>/` | `/<repo>/page/` — correct |
16
+ *
17
+ * So no single constant works: forcing `/` fixes the Workers mount and breaks
18
+ * every GitHub Pages project site. The emitter knows which layout it built and
19
+ * passes the base explicitly; this applies it.
20
+ */
21
+
22
+ /** The slice of the Pagefind module this touches. */
23
+ export interface PagefindOptionsModule {
24
+ options?: (opts: { baseUrl?: string }) => Promise<void> | void;
25
+ }
26
+
27
+ /**
28
+ * The base Pagefind should prefix results with: the served path that the
29
+ * INDEXED directory maps to.
30
+ *
31
+ * - Workers subpath mount — pages are built INTO `dist/<mount>/`, so the
32
+ * index already carries the mount in every URL: `/`.
33
+ * - Anything else — pages sit at the `dist/` root and Astro's `base` (the
34
+ * site.url path) is added at serve time, so that is the missing prefix:
35
+ * `<urlBase>/`, or `/` at the host root.
36
+ *
37
+ * Note `basePath` (dogsbay's own prefix) is never part of it: pages are
38
+ * physically written under it, so the index already contains it.
39
+ */
40
+ export function pagefindBaseUrl(urlBase: string, nestedOutDir: boolean): string {
41
+ if (nestedOutDir) return "/";
42
+ const base = urlBase.replace(/\/+$/, "");
43
+ return base ? `${base}/` : "/";
44
+ }
45
+
46
+ /**
47
+ * Apply an emitted base to a loaded Pagefind module. A missing base (a page
48
+ * emitted before the base was passed) leaves Pagefind's own default, so an
49
+ * un-rebuilt site behaves exactly as before rather than changing under it.
50
+ */
51
+ export async function applyPagefindBaseUrl(
52
+ mod: PagefindOptionsModule,
53
+ baseUrl: string | undefined,
54
+ ): Promise<boolean> {
55
+ if (!baseUrl) return false;
56
+ if (typeof mod.options !== "function") return false;
57
+ await mod.options({ baseUrl });
58
+ return true;
59
+ }
@@ -1,40 +1,16 @@
1
1
  /**
2
- * Pure helpers for search-facet UI in `<SearchDialog>`. Splitting
3
- * the data transforms here lets vitest exercise them without
4
- * needing a Pagefind runtime or rendered DOM.
2
+ * Search-facet helpers for `<SearchDialog>`. The pure helpers (shaping,
3
+ * labels, order, trees, URL state) live in `@dogsbay/search/facets`,
4
+ * shared with dogsbay-ssg; only the Pagefind mapping is here.
5
5
  *
6
6
  * See plans/search-facets.md.
7
7
  */
8
- import { resolveTermLabel } from "./tag-list-data.js";
9
- import type { PrefixDisplay } from "./tag-list-data.js";
10
-
11
- /**
12
- * Per-taxonomy display config — same shape as
13
- * `SiteConfig.taxonomyDisplay[name]`. Keyed locally so this module
14
- * has no runtime dependency on `@dogsbay/types`.
15
- */
16
- export interface TaxonomyDisplay {
17
- prefixes?: Record<string, PrefixDisplay>;
18
- labels?: Record<string, string>;
19
- }
20
-
21
- /** Map of taxonomy name → display config. */
22
- export type TaxonomyDisplayMap = Record<string, TaxonomyDisplay>;
23
-
24
- /** One facet entry — value plus the count of pages tagged with it. */
25
- export interface FacetEntry {
26
- /** The slug as Pagefind indexed it (e.g. `"concept/a11y"`, `"how-to"`). */
27
- value: string;
28
- /** Page count for this value within the current corpus. */
29
- count: number;
30
- }
31
-
32
- /** Map of facet name (taxonomy) → ordered entries. */
33
- export type FacetMap = Record<string, FacetEntry[]>;
8
+ export * from "@dogsbay/search/facets";
9
+ import type { FilterState } from "@dogsbay/search/facets";
34
10
 
35
11
  /**
36
12
  * Pagefind's filters API surface — a thin subset of the runtime
37
- * shape, kept local so this module stays dependency-free.
13
+ * shape, kept local so this module needs no Pagefind types.
38
14
  *
39
15
  * `pagefind.filters()` resolves to a nested map:
40
16
  * `{ <facetName>: { <value>: <count> } }`. We sort + flatten it.
@@ -44,189 +20,32 @@ export interface PagefindLike {
44
20
  }
45
21
 
46
22
  /**
47
- * Convert Pagefind's nested filter map into a sorted `FacetMap`.
48
- *
49
- * Sort order: count descending, then value ascending alphabetically
50
- * (stable tie-break). Empty value lists are dropped — a facet with
51
- * zero values isn't worth a row in the UI. Returns an empty
52
- * `FacetMap` when Pagefind reports no filters at all (Pagefind log
53
- * still says "Indexed 0 filters" — usually means the head→body fix
54
- * hasn't propagated, not a real "no-tags" site).
55
- */
56
- export function shapeFacets(
57
- raw: Record<string, Record<string, number>> | undefined | null,
58
- ): FacetMap {
59
- if (!raw) return {};
60
- const out: FacetMap = {};
61
- for (const [name, valueMap] of Object.entries(raw)) {
62
- const entries = sortFacetEntries(
63
- Object.entries(valueMap).map(([value, count]) => ({ value, count })),
64
- );
65
- if (entries.length > 0) out[name] = entries;
66
- }
67
- return out;
68
- }
69
-
70
- /**
71
- * Sort facet entries by count descending, then by value
72
- * ascending alphabetically. Stable for equal-count values so
73
- * the UI doesn't shuffle between renders.
74
- */
75
- export function sortFacetEntries(entries: FacetEntry[]): FacetEntry[] {
76
- return [...entries].sort((a, b) => {
77
- if (a.count !== b.count) return b.count - a.count;
78
- return a.value.localeCompare(b.value);
79
- });
80
- }
81
-
82
- /**
83
- * Resolve the human display label for one facet value.
23
+ * Build Pagefind's `filters` argument from internal facet state.
84
24
  *
85
- * Maps the slug-form value to the configured display string by
86
- * looking up the per-taxonomy display config. For slash-nested
87
- * values (`concept/a11y`), the resolution rules match
88
- * `<TagList>` chip rendering: explicit label override wins, then
89
- * prefix label for top-level segments, then leaf segment as a
90
- * final fallback.
25
+ * Pagefind's array shape (`{ tag: ["a", "b"] }`) is AND by default —
26
+ * "page must have BOTH tags" — per
27
+ * https://pagefind.app/docs/js-api-filtering/ ("All filtering
28
+ * defaults to AND filtering"). That's the wrong UX for faceted
29
+ * search: clicking two checkboxes in the same group should widen
30
+ * the result set, not collapse it to zero. We wrap each facet in
31
+ * `{ any: [...] }` so multi-select within a facet is OR. Across
32
+ * different facets Pagefind already ANDs the keys, which matches
33
+ * the standard "narrow with each additional dimension" UX.
91
34
  *
92
- * Slug paths are split into segments via `/`, mirroring how
93
- * taxonomies indexes terms.
94
- */
95
- export function resolveFacetLabel(
96
- facetName: string,
97
- value: string,
98
- display?: TaxonomyDisplayMap,
99
- ): string {
100
- const taxonomy = display?.[facetName];
101
- const fullPath = value.split("/").filter((s) => s.length > 0);
102
- return resolveTermLabel(fullPath, taxonomy?.prefixes, taxonomy?.labels);
103
- }
104
-
105
- /**
106
- * Resolve the display label for a facet name itself (the column
107
- * header text). Looks up `prefixes[facetName].label` for built-in
108
- * taxonomies (`tags` → "Tags"), falling back to a humanized
109
- * version of the facet name (`by-audience` → "By audience").
110
- *
111
- * Per-taxonomy `prefixes` aren't a perfect fit here (they're keyed
112
- * by the segment, not by the taxonomy itself), so this is a
113
- * separate humanizer. Future schema work can add an explicit
114
- * `taxonomies.<name>.displayName` field if writers want full
115
- * control.
116
- */
117
- export function resolveFacetTitle(facetName: string): string {
118
- return facetName
119
- .replace(/[-_]/g, " ")
120
- .replace(/\b\w/g, (c) => c.toUpperCase());
121
- }
122
-
123
- // ── URL persistence ──────────────────────────────────────────────
124
-
125
- /**
126
- * Active filter state — keyed by facet name, value is the set of
127
- * selected slugs (multi-select per facet, AND across facets).
128
- */
129
- export type FilterState = Record<string, string[]>;
130
-
131
- /**
132
- * Build URLSearchParams from the current filter state. Each
133
- * facet:value combination produces one `filter=<name>:<value>`
134
- * entry, repeated per selection. The `q` query param is added
135
- * only when query is non-empty.
136
- *
137
- * Resulting URL is shareable — re-loading restores both the
138
- * search query AND active filters.
139
- */
140
- export function filterStateToUrlParams(
141
- query: string,
142
- filters: FilterState,
143
- ): URLSearchParams {
144
- const params = new URLSearchParams();
145
- if (query.trim().length > 0) params.set("q", query.trim());
146
- for (const [name, values] of Object.entries(filters)) {
147
- for (const value of values) {
148
- params.append("filter", `${name}:${value}`);
149
- }
150
- }
151
- return params;
152
- }
153
-
154
- /**
155
- * Parse `URLSearchParams` back into `{ query, filters }`. The
156
- * inverse of `filterStateToUrlParams`. Tolerant of malformed
157
- * `filter=...` entries — anything missing the `:` separator is
158
- * silently dropped (forward-compat with future schema).
159
- */
160
- export function parseFiltersFromUrl(
161
- params: URLSearchParams,
162
- ): { query: string; filters: FilterState } {
163
- const query = params.get("q") ?? "";
164
- const filters: FilterState = {};
165
- for (const raw of params.getAll("filter")) {
166
- const colonIdx = raw.indexOf(":");
167
- if (colonIdx < 1) continue; // need at least 1 char before the colon
168
- const name = raw.slice(0, colonIdx);
169
- const value = raw.slice(colonIdx + 1);
170
- if (!value) continue;
171
- if (!filters[name]) filters[name] = [];
172
- if (!filters[name].includes(value)) filters[name].push(value);
173
- }
174
- return { query, filters };
175
- }
176
-
177
- /**
178
- * Pagefind's `search()` accepts filters keyed by facet name with
179
- * either a single value, an array (OR), or a nested operator
180
- * object. We always pass the array form so multi-select works
181
- * within a facet without special-casing single-select.
35
+ * Single-value selections also go through `{ any: ["x"] }` —
36
+ * Pagefind treats a one-element `any` identically to a bare string,
37
+ * so there's no behavioural delta and the code stays branch-free.
182
38
  *
183
39
  * Empty filter state → `{}` (Pagefind returns the unfiltered
184
- * result set). A facet with an empty array also drops out so we
185
- * don't accidentally narrow to "must equal nothing".
40
+ * result set). A facet with an empty array drops out so we don't
41
+ * accidentally narrow to "must equal nothing".
186
42
  */
187
43
  export function filterStateToPagefindFilters(
188
44
  filters: FilterState,
189
- ): Record<string, string[]> {
190
- const out: Record<string, string[]> = {};
45
+ ): Record<string, { any: string[] }> {
46
+ const out: Record<string, { any: string[] }> = {};
191
47
  for (const [name, values] of Object.entries(filters)) {
192
- if (values.length > 0) out[name] = [...values];
48
+ if (values.length > 0) out[name] = { any: [...values] };
193
49
  }
194
50
  return out;
195
51
  }
196
-
197
- /**
198
- * Toggle a single (facetName, value) pair in the filter state.
199
- * Returns a new state object — the input is never mutated, so
200
- * callers can safely use this with React-style "set state to a
201
- * new value" patterns or vanilla state diffing.
202
- */
203
- export function toggleFilter(
204
- filters: FilterState,
205
- name: string,
206
- value: string,
207
- ): FilterState {
208
- const next: FilterState = { ...filters };
209
- const current = next[name] ?? [];
210
- if (current.includes(value)) {
211
- const dropped = current.filter((v) => v !== value);
212
- if (dropped.length === 0) {
213
- delete next[name];
214
- } else {
215
- next[name] = dropped;
216
- }
217
- } else {
218
- next[name] = [...current, value];
219
- }
220
- return next;
221
- }
222
-
223
- /**
224
- * Count the total number of active filter selections across all
225
- * facets. Used to render a "Clear all" button only when there's
226
- * something to clear.
227
- */
228
- export function countActiveFilters(filters: FilterState): number {
229
- let n = 0;
230
- for (const values of Object.values(filters)) n += values.length;
231
- return n;
232
- }
@@ -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
+ }