@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.
@@ -7,6 +7,11 @@
7
7
  * Returns the path to rewrite to (the `.md` mirror endpoint) when the
8
8
  * request should be served as markdown; returns `null` when the normal
9
9
  * HTML response should pass through.
10
+ *
11
+ * `basePath` is the prefix the site is SERVED at (Dogsbay's combined
12
+ * urlBase + basePath). It is needed only to recognise the site index,
13
+ * whose mirror is `<base>/index.md` rather than `<base>.md` — see
14
+ * `shouldRewriteToMarkdown`.
10
15
  */
11
16
 
12
17
  const Q_PARAM_RE = /^\s*q\s*=\s*([0-9.]+)\s*$/i;
@@ -28,6 +33,7 @@ const Q_PARAM_RE = /^\s*q\s*=\s*([0-9.]+)\s*$/i;
28
33
  export function shouldRewriteToMarkdown(
29
34
  accept: string | null | undefined,
30
35
  pathname: string,
36
+ basePath = "",
31
37
  ): string | null {
32
38
  if (!accept) return null;
33
39
  if (!acceptsMarkdown(accept)) return null;
@@ -35,8 +41,38 @@ export function shouldRewriteToMarkdown(
35
41
  if (hasNonHtmlExtension(pathname)) return null;
36
42
 
37
43
  const trimmed = pathname.replace(/\/$/, "");
38
- const target = trimmed === "" ? "/.md" : `${trimmed}.md`;
39
- return target;
44
+ const base = basePath.replace(/\/+$/, "");
45
+
46
+ // A request outside the served prefix is not ours to rewrite. Without
47
+ // this guard, `("/", "/docs")` fell through to `"" + ".md"` — a
48
+ // RELATIVE target, resolved against whatever the request path was.
49
+ if (base && trimmed !== base && !trimmed.startsWith(`${base}/`)) return null;
50
+
51
+ // The site index is emitted as `index.md.ts`, so its mirror is
52
+ // `<base>/index.md`. Every other page emitted by the shipped importers
53
+ // has its mirror at `<path>.md`: Dogsbay builds in Astro's directory
54
+ // format, so a leaf at `/getting-started/` maps to
55
+ // `/getting-started.md`, and a directory index like `guides/index.md`
56
+ // is NORMALIZED to slug `guides` (see import-mkdocs.ts's
57
+ // `.replace(/\/index$/, "")`), emitting `guides.astro` + `guides.md.ts`
58
+ // — so `/guides.md` exists too.
59
+ //
60
+ // Appending `.md` to the site index produced `/.md` (root-served) or
61
+ // `/blog.md` (mounted); neither exists, and `/blog.md` additionally
62
+ // falls OUTSIDE the `/blog/*` Workers route. Leaf and index URLs both
63
+ // carry a trailing slash, so only the base comparison distinguishes
64
+ // them.
65
+ //
66
+ // CAVEAT: a caller driving `exportAstroProject` directly with an
67
+ // unnormalized `<dir>/index` slug gets `src/pages/<dir>/index.astro`
68
+ // (served `/<dir>/`) whose only mirror is `/<dir>/index.md`, and this
69
+ // returns `/<dir>.md` — a 404. No shipped importer does that. If one
70
+ // ever should, generalize the sibling `.md.ts` emitter in
71
+ // `format-astro/src/project.ts` rather than guessing here from a URL
72
+ // that cannot distinguish the two shapes.
73
+ if (trimmed === base) return `${base}/index.md`;
74
+
75
+ return `${trimmed}.md`;
40
76
  }
41
77
 
42
78
  function acceptsMarkdown(accept: string): boolean {
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
+ }
package/src/pagination.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { scopeNav, type NavScope } from "@dogsbay/site-files";
2
+
1
3
  interface NavItem {
2
4
  label: string;
3
5
  href?: string;
@@ -16,13 +18,20 @@ interface PaginationResult {
16
18
 
17
19
  /**
18
20
  * Flatten a nav tree into an ordered list of pages.
19
- * Find prev/next for the given path.
21
+ * Find prev/next for the given path. With `scope: "section"` they walk the
22
+ * page's section only (`scopeNav`, shared with dogsbay-ssg), as its sidebar;
23
+ * `home` is the home page, which lists the sections.
20
24
  */
21
- export function getPagination(currentPath: string, nav: NavItem[]): PaginationResult {
22
- const allPages = flattenNav(nav);
23
- const normalized = currentPath.replace(/\/$/, "") || "/";
24
- const index = allPages.findIndex(p => p.href.replace(/\/$/, "") === normalized);
25
+ export function getPagination(currentPath: string, nav: NavItem[], scope?: NavScope, home?: string): PaginationResult {
26
+ const allPages = flattenNav(scopeNav(nav, currentPath, scope, home === undefined ? {} : { home }).items);
27
+ // A root-served site's home entry is `""` (the importer's form): it is `/`
28
+ const norm = (href: string) => href.replace(/\/$/, "") || "/";
29
+ const normalized = norm(currentPath);
30
+ const index = allPages.findIndex(p => norm(p.href) === normalized);
25
31
 
32
+ // A page in no listed entry (an unlisted page, a page outside the nav) has neither: `-1` gave
33
+ // it the first page as its Next
34
+ if (index < 0) return { prev: undefined, next: undefined };
26
35
  return {
27
36
  prev: index > 0 ? allPages[index - 1] : undefined,
28
37
  next: index < allPages.length - 1 ? allPages[index + 1] : undefined,
@@ -32,7 +41,8 @@ export function getPagination(currentPath: string, nav: NavItem[]): PaginationRe
32
41
  function flattenNav(items: NavItem[]): PaginationLink[] {
33
42
  const result: PaginationLink[] = [];
34
43
  for (const item of items) {
35
- if (item.href) result.push({ label: item.label, href: item.href });
44
+ // `!== undefined`: the home page's href is `""` on a root-served site, and is a page
45
+ if (item.href !== undefined) result.push({ label: item.label, href: item.href });
36
46
  if (item.children) result.push(...flattenNav(item.children));
37
47
  }
38
48
  return result;
@@ -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
- }