@grove-dev/cli 0.15.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -21,5 +21,41 @@ export declare function migrateGithubCache(options: {
21
21
  config: GroveConfig;
22
22
  write: boolean;
23
23
  }): Promise<GithubCacheMigrationRun>;
24
+ export interface MarkdownRecordsMigrationRun {
25
+ /** Records converted (or, with `write: false`, that would be), in file order. */
26
+ migrated: Array<{
27
+ slug: string;
28
+ /** The YAML record, relative to `cwd`. */
29
+ from: string;
30
+ /** The Markdown record, relative to `cwd`. */
31
+ to: string;
32
+ /** True when the record had a body (the `.md` already existed). */
33
+ body: boolean;
34
+ /** Top-level fields left out because the normalizer derives them. */
35
+ dropped: string[];
36
+ }>;
37
+ /** Records left as YAML, and why. */
38
+ refused: Array<{
39
+ slug: string;
40
+ file: string;
41
+ reason: string;
42
+ }>;
43
+ }
44
+ /**
45
+ * Convert every YAML record (`paths.recordsDir/<slug>.yml`) into a
46
+ * Markdown record (`paths.bodiesDir/<slug>.md`): YAML frontmatter, then
47
+ * the body its `content:` pointer names, byte-for-byte. A record is
48
+ * refused, and left as it is, when its target `.md` exists but is not
49
+ * its own body, when its body lives somewhere else or has frontmatter
50
+ * of its own, or when {@link yamlRecordToMarkdown} refuses it. The
51
+ * Markdown file is written before the YAML is deleted, so an
52
+ * interrupted run leaves a `duplicate_slug_format` error, never a lost
53
+ * record.
54
+ */
55
+ export declare function migrateMarkdownRecords(options: {
56
+ cwd: string;
57
+ config: GroveConfig;
58
+ write: boolean;
59
+ }): Promise<MarkdownRecordsMigrationRun>;
24
60
  export declare function buildMigrateCommand(): Command;
25
61
  //# sourceMappingURL=migrate-cli.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"migrate-cli.d.ts","sourceRoot":"","sources":["../src/migrate-cli.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,KAAK,WAAW,EAKjB,MAAM,iBAAiB,CAAC;AACzB,OAAO,E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AM,CAAC;QACb,0CAA0C;QAC1C,IAAI,EAAE,MAAM,CAAC;QACb,8CAA8C;QAC9C,EAAE,EAAE,MAAM,CAAC;QACX,mEAAmE;QACnE,IAAI,EAAE,OAAO,CAAC;QACd,qEAAqE;QACrE,OAAO,EAAE,MAAM,EAAE,CAAC;KACnB,CAAC,CAAC;IACH,qCAAqC;IACrC,OAAO,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;CAChE;AASD;;;;;;;;;;GAUG;AACH,wBAAsB,sBAAsB,CAAC,OAAO,EAAE;IACpD,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,WAAW,CAAC;IACpB,KAAK,EAAE,OAAO,CAAC;CAChB,GAAG,OAAO,CAAC,2BAA2B,CAAC,CAwEvC;AAED,wBAAgB,mBAAmB,IAAI,OAAO,CAgE7C"}
@@ -1,7 +1,8 @@
1
- import { readdir, readFile, writeFile } from 'node:fs/promises';
1
+ import { access, readdir, readFile, unlink, writeFile } from 'node:fs/promises';
2
2
  import { basename, join, relative, resolve } from 'node:path';
3
- import { loadConfig, loadGithubCache, migrateRecordGithub, writeGithubCacheEntry, } from '@grove-dev/core';
3
+ import { blueprintKind, loadConfig, loadGithubCache, migrateRecordGithub, splitFrontmatter, writeGithubCacheEntry, yamlRecordToMarkdown, } from '@grove-dev/core';
4
4
  import { Command } from 'commander';
5
+ import { parse as parseYaml } from 'yaml';
5
6
  /**
6
7
  * Move every record's inline `github` / `health` into the GitHub sync
7
8
  * cache and strip them from the record, leaving the rest of each YAML
@@ -37,6 +38,93 @@ export async function migrateGithubCache(options) {
37
38
  }
38
39
  return { migrated, conflicts, cacheDir: cache.dir };
39
40
  }
41
+ async function exists(path) {
42
+ return access(path).then(() => true, () => false);
43
+ }
44
+ /**
45
+ * Convert every YAML record (`paths.recordsDir/<slug>.yml`) into a
46
+ * Markdown record (`paths.bodiesDir/<slug>.md`): YAML frontmatter, then
47
+ * the body its `content:` pointer names, byte-for-byte. A record is
48
+ * refused, and left as it is, when its target `.md` exists but is not
49
+ * its own body, when its body lives somewhere else or has frontmatter
50
+ * of its own, or when {@link yamlRecordToMarkdown} refuses it. The
51
+ * Markdown file is written before the YAML is deleted, so an
52
+ * interrupted run leaves a `duplicate_slug_format` error, never a lost
53
+ * record.
54
+ */
55
+ export async function migrateMarkdownRecords(options) {
56
+ const { cwd, config, write } = options;
57
+ const recordsDir = resolve(cwd, config.paths.recordsDir);
58
+ const bodiesDir = resolve(cwd, config.paths.bodiesDir ?? 'content/records');
59
+ const kind = blueprintKind[config.blueprint];
60
+ const labelKey = kind === 'resource' ? 'title' : 'name';
61
+ const files = (await readdir(recordsDir).catch(() => []))
62
+ .filter((file) => file.endsWith('.yml'))
63
+ .sort();
64
+ const run = { migrated: [], refused: [] };
65
+ for (const file of files) {
66
+ const slug = basename(file, '.yml');
67
+ const path = join(recordsDir, file);
68
+ const target = join(bodiesDir, `${slug}.md`);
69
+ const refuse = (reason) => run.refused.push({ slug, file: relative(cwd, path), reason });
70
+ const text = await readFile(path, 'utf8');
71
+ let pointer;
72
+ try {
73
+ pointer = parseYaml(text, { schema: 'core' })?.content;
74
+ }
75
+ catch (err) {
76
+ refuse(`YAML does not parse: ${err.message}`);
77
+ continue;
78
+ }
79
+ let body = '';
80
+ if (typeof pointer === 'string' && pointer) {
81
+ // Resolved the way the normalizer resolves it.
82
+ const candidates = [resolve(cwd, pointer), resolve(cwd, 'apps', 'example', pointer)];
83
+ let found;
84
+ for (const candidate of candidates) {
85
+ if (await exists(candidate)) {
86
+ found = candidate;
87
+ break;
88
+ }
89
+ }
90
+ if (!found) {
91
+ refuse(`content "${pointer}" does not resolve to a file`);
92
+ continue;
93
+ }
94
+ if (found !== target) {
95
+ refuse(`its body is ${relative(cwd, found)}, not ${relative(cwd, target)}; move the body there first`);
96
+ continue;
97
+ }
98
+ body = await readFile(found, 'utf8');
99
+ if (splitFrontmatter(body).hasFrontmatter) {
100
+ refuse(`${relative(cwd, found)} already has frontmatter; merge it by hand`);
101
+ continue;
102
+ }
103
+ }
104
+ else if (await exists(target)) {
105
+ // Some other document (or a body no record points at) owns the name.
106
+ refuse(`${relative(cwd, target)} already exists and is not this record's body`);
107
+ continue;
108
+ }
109
+ const result = yamlRecordToMarkdown(slug, text, { kind, labelKey, body });
110
+ if (!result.ok) {
111
+ refuse(result.reason);
112
+ continue;
113
+ }
114
+ run.migrated.push({
115
+ slug,
116
+ from: relative(cwd, path),
117
+ to: relative(cwd, target),
118
+ body: body !== '',
119
+ dropped: result.dropped,
120
+ });
121
+ if (!write)
122
+ continue;
123
+ await writeFile(target, result.text, 'utf8');
124
+ await unlink(path);
125
+ }
126
+ return run;
127
+ }
40
128
  export function buildMigrateCommand() {
41
129
  const cmd = new Command('migrate');
42
130
  cmd.description('One-off data migrations between Grove versions.');
@@ -63,6 +151,26 @@ export function buildMigrateCommand() {
63
151
  }
64
152
  console.log(`[migrate github-cache] moved ${run.migrated.length} record(s) into ${cacheDir}/ (${run.conflicts.length} kept an existing cache entry)`);
65
153
  });
154
+ cmd
155
+ .command('markdown-records')
156
+ .description('Turn each YAML record (and its content: body) into one Markdown record in paths.bodiesDir.')
157
+ .option('--check', 'Write nothing; list what would change and exit 1 while YAML records remain.')
158
+ .action(async (opts) => {
159
+ const cwd = process.cwd();
160
+ const config = await loadConfig(cwd);
161
+ const run = await migrateMarkdownRecords({ cwd, config, write: !opts.check });
162
+ const verb = opts.check ? 'would move' : 'moved';
163
+ for (const entry of run.migrated) {
164
+ const dropped = entry.dropped.length > 0 ? ` (dropped ${entry.dropped.join(', ')})` : '';
165
+ console.log(`[migrate markdown-records] ${entry.from} → ${entry.to}${dropped}`);
166
+ }
167
+ for (const { file, reason } of run.refused) {
168
+ console.warn(`[migrate markdown-records] kept ${file}: ${reason}`);
169
+ }
170
+ console.log(`[migrate markdown-records] ${verb} ${run.migrated.length} record(s) to Markdown; ${run.refused.length} left as YAML.`);
171
+ if (run.refused.length > 0 || (opts.check && run.migrated.length > 0))
172
+ process.exitCode = 1;
173
+ });
66
174
  return cmd;
67
175
  }
68
176
  //# sourceMappingURL=migrate-cli.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"migrate-cli.js","sourceRoot":"","sources":["../src/migrate-cli.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAChE,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC9D,OAAO,EAEL,UAAU,EACV,eAAe,EACf,mBAAmB,EACnB,qBAAqB,GACtB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAUpC;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,kBAAkB,CAAC,OAIxC;IACC,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,OAAO,CAAC;IACvC,MAAM,UAAU,GAAG,OAAO,CAAC,GAAG,EAAE,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;IACzD,MAAM,KAAK,GAAG,CAAC,MAAM,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;IACzF,MAAM,KAAK,GAAG,MAAM,eAAe,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IACjD,IAAI,KAAK,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC5B,8DAA8D;QAC9D,MAAM,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC,GAAG,IAAI,K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CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,IAAI,GAAG,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC;YAAE,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;IAC9F,CAAC,CAAC,CAAC;IAEL,OAAO,GAAG,CAAC;AACb,CAAC"}
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@grove-dev/cli",
3
- "version": "0.15.0",
3
+ "version": "0.17.0",
4
4
  "type": "module",
5
5
  "description": "Grove CLI — scaffolds Grove-powered spaces and orchestrates @grove-dev/core commands.",
6
6
  "license": "MIT",
package/dist/r/about.json CHANGED
@@ -17,7 +17,7 @@
17
17
  ],
18
18
  "meta": {
19
19
  "version": "1.3.0",
20
- "requiresGrove": "0.15.0"
20
+ "requiresGrove": "0.17.0"
21
21
  },
22
22
  "type": "registry:block"
23
23
  }
@@ -35,13 +35,19 @@
35
35
  },
36
36
  {
37
37
  "path": "default/components/grove/directory-browse.astro",
38
- "content": "---\n/**\n * DirectoryBrowse — the browse page body, shared by the two routes\n * that render it: `/{slug}/` (page 1) and `/{slug}/page/{n}/`.\n *\n * Layout, top to bottom:\n * - PageHeader (the only place the page names itself)\n * - Search + Sort on one row\n * - Every facet filter on the next row\n * - Applied-filter chips + Clear all on their own row\n * - Result count / sort / page line\n * - Card grid, then pagination\n *\n * Navigation model: **pages are real paths.** Each route prerenders\n * only its own 20 records, so an unfiltered directory of any size is\n * crawlable, works without JavaScript, and never ships the whole\n * catalogue as DOM.\n *\n * Filtering stays client-side: these routes are PRERENDERED, so at\n * build time `Astro.url.searchParams` is empty. `DirectoryIndexClient`\n * re-reads `location.search` and re-derives the result list, chips,\n * pagination, and facet intersection counts with the same\n * `@grove-dev/core/directory` functions the server used. Filtered views\n * paginate with `?page=N` on the base route.\n */\nimport siteConfig from '@grove/generated/site-config.json';\nimport { SORT_OPTIONS, sortDisplay } from '@grove-dev/astro';\nimport {\n getDirectoryIndexModel,\n itemLabel,\n itemLabelPlural,\n seoTitle,\n taxonomy,\n titleCaseFirst,\n} from '@grove-dev/astro/server';\nimport { formatCount } from '@grove-dev/core';\nimport BaseLayout from '../../layouts/base-layout.astro';\nimport { chipClass } from '../../lib/classnames.ts';\nimport Button from '../ui/button.astro';\nimport FilterDrawer from '../ui/filter-drawer.astro';\nimport PageHeader from '../ui/page-header.astro';\nimport SearchField from '../ui/search-field.astro';\nimport CardGrid from './card-grid.astro';\nimport DirectoryIndexClient from './directory-index-client.astro';\nimport IndexRow from './index-row.astro';\nimport Pagination from './pagination.astro';\nimport RefinePanel from './refine-panel.astro';\nimport SmartLensTabs from './smart-lens-tabs.astro';\n\ninterface Props {\n /** 1-based page this route renders. */\n routePage?: number;\n}\n\nconst { routePage = 1 } = Astro.props;\nconst slug = siteConfig.blueprintConfig?.routeSlug ?? 'projects';\nconst {\n total,\n filters,\n facetGroups,\n searchPlaceholder,\n sort,\n sorted,\n pageItems,\n pages,\n page,\n chips,\n clearFiltersHref,\n hrefForResultPage,\n seo,\n} = getDirectoryIndexModel(Astro.url.searchParams, siteConfig, { page: routePage });\n\n// Page 2+ gets a distinct title and skips the ItemList JSON-LD so the\n// list markup isn't duplicated across every paginated route. The\n// per-page description is built inside `getDirectoryIndexModel` so it\n// fits inside the 160-char cap; this view just forwards `seo.title`.\nconst title =\n page > 1\n ? seoTitle(`Browse ${titleCaseFirst(itemLabelPlural())} — Page ${page}`, siteConfig.name)\n : seo.title;\nconst description = seo.description;\n---\n\n<BaseLayout\n title={title}\n description={description}\n image={seo.image}\n jsonLd={page > 1 ? undefined : seo.jsonLd}\n site={siteConfig}\n submitHref=\"/submit\"\n submitLabel={`Submit ${itemLabel()}`}\n>\n <section class=\"border-b border-border bg-background\">\n <div class=\"mx-auto w-full max-w-container px-5 pt-10 sm:px-7 sm:pt-12\">\n <PageHeader\n eyebrow={slug}\n title={`Browse ${slug}`}\n description={`Search, filter, and explore ${formatCount(total, { singular: itemLabel(), plural: itemLabelPlural() })} in this directory.`}\n />\n\n {/* Curated views. Real links (not a JS-driven control) — the\n same server-and-client filter pipeline (@grove-dev/core's\n filtersFromSearchParams/filterRecords) already understands\n `?lens=`, so this works with JS disabled too. */}\n <SmartLensTabs\n currentParams={Astro.url.searchParams}\n pathPrefix={`/${slug}`}\n lensIds={[\"all\", \"hot\", \"new\", \"mature\"]}\n class=\"mt-6\"\n />\n\n {/* Row 1 — search and sort. Search filters as you type (see\n DirectoryIndexClient); the submit button is sr-only so Enter\n still works when JavaScript never arrives. */}\n <form\n method=\"get\"\n action={`/${slug}`}\n id=\"search-form\"\n class=\"mt-6 flex flex-col gap-2 sm:flex-row\"\n role=\"search\"\n >\n <SearchField\n class=\"flex-1\"\n label={`Search ${itemLabelPlural()}`}\n value={filters.q ?? \"\"}\n placeholder={searchPlaceholder}\n shortcut\n />\n <label class=\"relative\">\n <span class=\"sr-only\">{`Sort ${itemLabelPlural()}`}</span>\n <select\n id=\"sort-select\"\n name=\"sort\"\n class=\"h-10 w-full cursor-pointer appearance-none rounded-md border border-input bg-background py-1.5 pl-3 pr-8 text-sm font-medium text-foreground transition-colors hover:border-ring focus:border-ring focus:outline-none focus:ring-2 focus:ring-ring/20 sm:w-auto\"\n >\n {SORT_OPTIONS.map((o) => (\n <option value={o.value} selected={o.value === sort}>{o.label}</option>\n ))}\n </select>\n <svg\n viewBox=\"0 0 16 16\"\n width=\"11\"\n height=\"11\"\n aria-hidden=\"true\"\n class=\"pointer-events-none absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground\"\n fill=\"currentColor\"\n >\n <path d=\"M4.22 6.22a.75.75 0 0 1 1.06 0L8 8.94l2.72-2.72a.75.75 0 1 1 1.06 1.06l-3.25 3.25a.75.75 0 0 1-1.06 0L4.22 7.28a.75.75 0 0 1 0-1.06Z\" />\n </svg>\n </label>\n <button type=\"submit\" class=\"sr-only\">Search</button>\n </form>\n\n {/* Row 2 — every filter on one line. On mobile they collapse into\n a full-width \"Filters (n)\" button opening a bottom sheet.\n Filters apply live in both places. The sheet's footer button\n (\"Show 12 apps\") just closes it and moves focus to the\n results heading. */}\n <div class=\"mt-3\">\n <FilterDrawer\n label=\"Filters\"\n activeCount={chips.length}\n clearHref={clearFiltersHref}\n resultsLabel={`Show ${sorted.length} ${sorted.length === 1 ? itemLabel() : itemLabelPlural()}`}\n resultsTarget=\"#results-heading\"\n >\n {/* The applied chips again, inside the sheet: on mobile the\n row above the list is behind the sheet. On desktop the\n filters render inline right above that row, so this copy\n stays hidden. DirectoryIndexClient fills both. The sheet's\n header already has \"Clear all\", so this row leaves it out. */}\n <div\n data-active-filters\n data-without-clear\n class:list={[\"mb-3 flex flex-wrap items-center gap-1.5 md:hidden\", chips.length === 0 && \"hidden\"]}\n aria-label=\"Active filters\"\n ></div>\n <RefinePanel\n class=\"max-md:flex-col max-md:items-stretch\"\n groups={facetGroups}\n initial={filters}\n pathPrefix={`/${slug}`}\n hide={[\"sort\"]}\n />\n </FilterDrawer>\n </div>\n\n {/* Row 3 — what is currently narrowing the list, and one way out\n of all of it. Server-rendered empty on this prerendered route;\n the client fills it from the live query string. */}\n <div\n id=\"active-filters\"\n data-active-filters\n class:list={[\"mt-3 flex flex-wrap items-center gap-1.5 pb-6\", chips.length === 0 && \"hidden\"]}\n aria-label=\"Active filters\"\n >\n {chips.map((chip) => (\n <a href={chip.href} class={chipClass()} aria-label={`Remove filter: ${chip.label}`}>\n {chip.label} <span aria-hidden=\"true\">×</span>\n </a>\n ))}\n {chips.length > 0 && (\n <a\n href={clearFiltersHref}\n class=\"text-2xs font-medium text-ink-500 underline decoration-border underline-offset-2 hover:text-ink-900 dark:hover:text-ink-100\"\n aria-label=\"Clear all active filters\"\n >\n Clear all\n </a>\n )}\n </div>\n {chips.length === 0 && <div class=\"pb-6\"></div>}\n </div>\n </section>\n\n <section class=\"py-10 sm:py-12\">\n <div class=\"mx-auto w-full max-w-container px-5 sm:px-7\">\n {/* The count line IS the results heading — it carries a fact,\n which \"All projects / Every item in the directory\" did not,\n and it keeps the document's heading order intact above the\n cards' own h3s. */}\n {/* `tabindex=\"-1\"` lets the drawer's \"Show N\" button and the\n focus fallbacks in DirectoryIndexClient move focus here. */}\n <h2\n id=\"results-heading\"\n tabindex=\"-1\"\n class=\"m-0 mb-5 scroll-mt-4 text-2xs font-normal text-ink-500 dark:text-ink-400\"\n >\n <span id=\"results-count\" class=\"font-mono font-semibold text-ink-900 dark:text-ink-100\">\n {sorted.length} {sorted.length === 1 ? itemLabel() : itemLabelPlural()}\n </span>\n <span id=\"results-sort\">{` · sorted by ${sortDisplay(sort)}`}</span>\n <span id=\"results-page\">{pages > 1 ? ` · page ${page} of ${pages}` : \"\"}</span>\n </h2>\n\n {/* Screen readers hear the result count here, debounced by\n DirectoryIndexClient so rapid toggles make one announcement.\n The visible count above is deliberately not a live region,\n or every change would be announced twice. */}\n <p id=\"results-status\" class=\"sr-only\" role=\"status\" aria-live=\"polite\" aria-atomic=\"true\"></p>\n\n <CardGrid id=\"results-list\">\n {pageItems.map((item, i) => (\n <li class=\"m-0 p-0\" data-record-slug={item.slug}>\n <IndexRow\n record={item as Parameters<typeof IndexRow>[0][\"record\"]}\n detailHref={`/${slug}/${item.slug}/`}\n eager={i < 3}\n />\n </li>\n ))}\n </CardGrid>\n\n <div id=\"empty-state\" class:list={[\"py-12 text-center\", sorted.length > 0 && \"hidden\"]}>\n <p class=\"m-0 text-sm font-medium text-ink-700 dark:text-ink-200\">\n {`No ${itemLabelPlural()} match these filters.`}\n </p>\n {/* The client keeps this href in step with the live query, so\n clearing keeps the chosen sort. */}\n <Button href={clearFiltersHref} variant=\"secondary\" size=\"sm\" class=\"mt-4\" data-empty-reset>Clear filters</Button>\n </div>\n {/* Plain div wrapper — Pagination renders its own\n <nav aria-label=\"Pagination\">, so a nav here would nest two\n identical landmarks. */}\n <div id=\"results-pagination\" class=\"mt-8 flex flex-wrap items-center justify-center gap-1.5\">\n <Pagination current={page} total={pages} hrefFor={hrefForResultPage} />\n </div>\n </div>\n </section>\n\n <section class=\"border-t border-ink-200 dark:border-ink-800\">\n <div class=\"mx-auto w-full max-w-container px-5 sm:px-7\">\n <div class=\"flex flex-col items-center gap-3 py-12 text-center\">\n <h2 class=\"m-0 text-xl font-semibold tracking-tight text-ink-900 dark:text-ink-100\">\n {`Know a real ${itemLabel()} that belongs here?`}\n </h2>\n <p class=\"m-0 max-w-2xl text-sm text-ink-500 dark:text-ink-400\">\n {`Open a pull request with a YAML file. We review every submission against the bar — no marketing, no tutorials.`}\n </p>\n <Button href=\"/submit\" variant=\"primary\" size=\"sm\" class=\"mt-2\">\n {`Submit ${itemLabel()}`}\n </Button>\n\n </div>\n </div>\n </section>\n\n <DirectoryIndexClient\n slug={slug}\n singular={itemLabel()}\n plural={itemLabelPlural()}\n taxonomy={taxonomy}\n routePage={page}\n />\n</BaseLayout>\n",
38
+ "content": "---\n/**\n * DirectoryBrowse — the browse page body, shared by the two routes\n * that render it: `/{slug}/` (page 1) and `/{slug}/page/{n}/`.\n *\n * Layout, top to bottom:\n * - PageHeader (the only place the page names itself) and lens tabs\n * - `DirectoryBrowseView`: search + sort, facet filters, applied\n * chips, the result count line, the card grid and pagination\n * - The submit call to action\n *\n * Navigation model: **pages are real paths.** Each route prerenders\n * only its own 20 records, so an unfiltered directory of any size is\n * crawlable, works without JavaScript, and never ships the whole\n * catalogue as DOM.\n *\n * Filtering stays client-side: these routes are PRERENDERED, so at\n * build time `Astro.url.searchParams` is empty. `DirectoryIndexClient`\n * (rendered by `DirectoryBrowseView`) re-reads `location.search` and\n * re-derives the result list, chips, pagination, and facet\n * intersection counts with the same `@grove-dev/core/directory`\n * functions the server used. Filtered views paginate with `?page=N` on\n * the base route. Taxonomy pages render the same view with a `scope`.\n */\nimport siteConfig from '@grove/generated/site-config.json';\nimport {\n getDirectoryIndexModel,\n itemLabel,\n itemLabelPlural,\n seoTitle,\n titleCaseFirst,\n} from '@grove-dev/astro/server';\nimport { formatCount } from '@grove-dev/core';\nimport BaseLayout from '../../layouts/base-layout.astro';\nimport Button from '../ui/button.astro';\nimport PageHeader from '../ui/page-header.astro';\nimport DirectoryBrowseView from './directory-browse-view.astro';\nimport SmartLensTabs from './smart-lens-tabs.astro';\n\ninterface Props {\n /** 1-based page this route renders. */\n routePage?: number;\n}\n\nconst { routePage = 1 } = Astro.props;\nconst slug = siteConfig.blueprintConfig?.routeSlug ?? 'projects';\nconst { total, page, seo } = getDirectoryIndexModel(Astro.url.searchParams, siteConfig, {\n page: routePage,\n});\n\n// Page 2+ gets a distinct title and skips the ItemList JSON-LD so the\n// list markup isn't duplicated across every paginated route. The\n// per-page description is built inside `getDirectoryIndexModel` so it\n// fits inside the 160-char cap; this view just forwards `seo.title`.\nconst title =\n page > 1\n ? seoTitle(`Browse ${titleCaseFirst(itemLabelPlural())} — Page ${page}`, siteConfig.name)\n : seo.title;\nconst description = seo.description;\n---\n\n<BaseLayout\n title={title}\n description={description}\n image={seo.image}\n jsonLd={page > 1 ? undefined : seo.jsonLd}\n site={siteConfig}\n submitHref=\"/submit\"\n submitLabel={`Submit ${itemLabel()}`}\n>\n <DirectoryBrowseView routePage={routePage}>\n <Fragment slot=\"header\">\n <PageHeader\n eyebrow={slug}\n title={`Browse ${slug}`}\n description={`Search, filter, and explore ${formatCount(total, { singular: itemLabel(), plural: itemLabelPlural() })} in this directory.`}\n />\n\n {/* Curated views. Real links (not a JS-driven control) — the\n same server-and-client filter pipeline (@grove-dev/core's\n filtersFromSearchParams/filterRecords) already understands\n `?lens=`, so this works with JS disabled too. */}\n <SmartLensTabs\n currentParams={Astro.url.searchParams}\n pathPrefix={`/${slug}`}\n lensIds={[\"all\", \"hot\", \"new\", \"mature\"]}\n class=\"mt-6\"\n />\n </Fragment>\n </DirectoryBrowseView>\n\n <section class=\"border-t border-ink-200 dark:border-ink-800\">\n <div class=\"mx-auto w-full max-w-container px-5 sm:px-7\">\n <div class=\"flex flex-col items-center gap-3 py-12 text-center\">\n <h2 class=\"m-0 text-xl font-semibold tracking-tight text-ink-900 dark:text-ink-100\">\n {`Know a real ${itemLabel()} that belongs here?`}\n </h2>\n <p class=\"m-0 max-w-2xl text-sm text-ink-500 dark:text-ink-400\">\n {`Open a pull request with a YAML file. We review every submission against the bar — no marketing, no tutorials.`}\n </p>\n <Button href=\"/submit\" variant=\"primary\" size=\"sm\" class=\"mt-2\">\n {`Submit ${itemLabel()}`}\n </Button>\n\n </div>\n </div>\n </section>\n</BaseLayout>\n",
39
39
  "type": "registry:component",
40
40
  "target": "~/src/components/grove/directory-browse.astro"
41
41
  },
42
+ {
43
+ "path": "default/components/grove/directory-browse-view.astro",
44
+ "content": "---\n/**\n * DirectoryBrowseView — the browse engine's body: search and sort, the\n * facet filters, the applied-filter chips, the results, and the client\n * controller that keeps all of it in step with the query string.\n *\n * Two kinds of page render it:\n * - `DirectoryBrowse` (`/{slug}/`, `/{slug}/page/{n}/`), which puts\n * its page header and lens tabs in the `header` slot.\n * - `TaxonomyList` (`/stacks/<id>/`, `/categories/<id>/`, …), which\n * passes a `scope` and its own `pathPrefix`.\n *\n * `scope` is an immutable slice of the directory, such as\n * `{ stacks: ['flutter'] }`. It is merged into every query, so results\n * and facet counts only ever come from the scoped set. It is never a\n * chip, its facet group is not rendered, and it never goes in the URL:\n * the page's own path already says it. Filters, sort and the query\n * live in that page's query string (`/stacks/flutter/?platform=ios`),\n * and \"Clear all\" or the zero-results reset lead back to the page\n * itself, so nothing can drop the scope.\n *\n * A scoped list is not paginated. The host page has no `/page/{n}/`\n * routes, so one prerendered document carries every record in the\n * scope, which keeps all of them linked without JavaScript. That is\n * what taxonomy pages rendered before they had filters.\n *\n * With no `scope` this renders exactly what `/{slug}/` always did.\n */\nimport siteConfig from '@grove/generated/site-config.json';\nimport { SORT_OPTIONS, sortDisplay } from '@grove-dev/astro';\nimport {\n getDirectoryIndexModel,\n itemLabel,\n itemLabelPlural,\n taxonomy,\n} from '@grove-dev/astro/server';\nimport { searchParamsFromFilters } from '@grove-dev/core';\nimport { chipClass } from '../../lib/classnames.ts';\nimport { type DirectoryScope, scopedGroups } from '../../lib/live-filters.ts';\nimport Button from '../ui/button.astro';\nimport FilterDrawer from '../ui/filter-drawer.astro';\nimport SearchField from '../ui/search-field.astro';\nimport CardGrid from './card-grid.astro';\nimport DirectoryIndexClient from './directory-index-client.astro';\nimport IndexRow from './index-row.astro';\nimport Pagination from './pagination.astro';\nimport RefinePanel from './refine-panel.astro';\n\ninterface Props {\n /** 1-based page this route renders. Ignored when `scope` is set. */\n routePage?: number;\n /**\n * Fixed filters for every query on this page, e.g.\n * `{ categories: ['productivity'] }`. Omit on the directory itself.\n */\n scope?: DirectoryScope;\n /**\n * Path the filtered URLs are built on, without a trailing slash.\n * Default: the directory route (`/{slug}`). A scoped page passes its\n * own path (`/stacks/flutter`).\n */\n pathPrefix?: string;\n}\n\nconst slug = siteConfig.blueprintConfig?.routeSlug ?? 'projects';\nconst { routePage = 1, scope, pathPrefix = `/${slug}` } = Astro.props;\nconst fixed = scopedGroups(scope);\nconst scoped = fixed.length > 0;\n\n// A scoped page asks the same model the directory uses, with the scope\n// as its query. Every facet's intersection count then already excludes\n// records outside the scope, and `sorted` is the scoped set. On an\n// unscoped page the build never sees a query, so this is empty.\nconst query = scoped\n ? searchParamsFromFilters(\n Object.fromEntries(fixed.map((group) => [group, [...(scope?.[group] ?? [])]])),\n )\n : Astro.url.searchParams;\nconst model = getDirectoryIndexModel(query, siteConfig, { page: scoped ? 1 : routePage });\nconst { filters, searchPlaceholder, sort, sorted } = model;\n\n// The scoped group is the page itself, not a choice: no facet for it,\n// and no chip. Nothing else the visitor picked exists at build time.\nconst facetGroups = model.facetGroups.filter(\n (group) => !fixed.includes(group.filterKey as (typeof fixed)[number]),\n);\nconst chips = scoped ? [] : model.chips;\nconst clearFiltersHref = scoped ? `${pathPrefix}/` : model.clearFiltersHref;\nconst pageItems = scoped ? sorted : model.pageItems;\nconst pages = scoped ? 1 : model.pages;\nconst page = scoped ? 1 : model.page;\nconst { hrefForResultPage } = model;\n---\n\n<section class=\"border-b border-border bg-background\">\n <div class:list={[\"mx-auto w-full max-w-container px-5 sm:px-7\", Astro.slots.has(\"header\") && \"pt-10 sm:pt-12\"]}>\n <slot name=\"header\" />\n\n {/* Row 1 — search and sort. Search filters as you type (see\n DirectoryIndexClient); the submit button is sr-only so Enter\n still works when JavaScript never arrives. */}\n <form\n method=\"get\"\n action={pathPrefix}\n id=\"search-form\"\n class:list={[\"flex flex-col gap-2 sm:flex-row\", Astro.slots.has(\"header\") && \"mt-6\"]}\n role=\"search\"\n >\n <SearchField\n class=\"flex-1\"\n label={`Search ${itemLabelPlural()}`}\n value={filters.q ?? \"\"}\n placeholder={searchPlaceholder}\n shortcut\n />\n <label class=\"relative\">\n <span class=\"sr-only\">{`Sort ${itemLabelPlural()}`}</span>\n <select\n id=\"sort-select\"\n name=\"sort\"\n class=\"h-10 w-full cursor-pointer appearance-none rounded-md border border-input bg-background py-1.5 pl-3 pr-8 text-sm font-medium text-foreground transition-colors hover:border-ring focus:border-ring focus:outline-none focus:ring-2 focus:ring-ring/20 sm:w-auto\"\n >\n {SORT_OPTIONS.map((o) => (\n <option value={o.value} selected={o.value === sort}>{o.label}</option>\n ))}\n </select>\n <svg\n viewBox=\"0 0 16 16\"\n width=\"11\"\n height=\"11\"\n aria-hidden=\"true\"\n class=\"pointer-events-none absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground\"\n fill=\"currentColor\"\n >\n <path d=\"M4.22 6.22a.75.75 0 0 1 1.06 0L8 8.94l2.72-2.72a.75.75 0 1 1 1.06 1.06l-3.25 3.25a.75.75 0 0 1-1.06 0L4.22 7.28a.75.75 0 0 1 0-1.06Z\" />\n </svg>\n </label>\n <button type=\"submit\" class=\"sr-only\">Search</button>\n </form>\n\n {/* Row 2 — every filter on one line. On mobile they collapse into\n a full-width \"Filters (n)\" button opening a bottom sheet.\n Filters apply live in both places. The sheet's footer button\n (\"Show 12 apps\") just closes it and moves focus to the\n results heading. */}\n <div class=\"mt-3\">\n <FilterDrawer\n label=\"Filters\"\n activeCount={chips.length}\n clearHref={clearFiltersHref}\n resultsLabel={`Show ${sorted.length} ${sorted.length === 1 ? itemLabel() : itemLabelPlural()}`}\n resultsTarget=\"#results-heading\"\n >\n {/* The applied chips again, inside the sheet: on mobile the\n row above the list is behind the sheet. On desktop the\n filters render inline right above that row, so this copy\n stays hidden. DirectoryIndexClient fills both. The sheet's\n header already has \"Clear all\", so this row leaves it out. */}\n <div\n data-active-filters\n data-without-clear\n class:list={[\"mb-3 flex flex-wrap items-center gap-1.5 md:hidden\", chips.length === 0 && \"hidden\"]}\n aria-label=\"Active filters\"\n ></div>\n <RefinePanel\n class=\"max-md:flex-col max-md:items-stretch\"\n groups={facetGroups}\n initial={filters}\n pathPrefix={pathPrefix}\n hide={[\"sort\"]}\n />\n </FilterDrawer>\n </div>\n\n {/* Row 3 — what is currently narrowing the list, and one way out\n of all of it. Server-rendered empty on this prerendered route;\n the client fills it from the live query string. */}\n <div\n id=\"active-filters\"\n data-active-filters\n class:list={[\"mt-3 flex flex-wrap items-center gap-1.5 pb-6\", chips.length === 0 && \"hidden\"]}\n aria-label=\"Active filters\"\n >\n {chips.map((chip) => (\n <a href={chip.href} class={chipClass()} aria-label={`Remove filter: ${chip.label}`}>\n {chip.label} <span aria-hidden=\"true\">×</span>\n </a>\n ))}\n {chips.length > 0 && (\n <a\n href={clearFiltersHref}\n class=\"text-2xs font-medium text-ink-500 underline decoration-border underline-offset-2 hover:text-ink-900 dark:hover:text-ink-100\"\n aria-label=\"Clear all active filters\"\n >\n Clear all\n </a>\n )}\n </div>\n {chips.length === 0 && <div class=\"pb-6\"></div>}\n </div>\n</section>\n\n<section class=\"py-10 sm:py-12\">\n <div class=\"mx-auto w-full max-w-container px-5 sm:px-7\">\n {/* The count line IS the results heading — it carries a fact,\n which \"All projects / Every item in the directory\" did not,\n and it keeps the document's heading order intact above the\n cards' own h3s. */}\n {/* `tabindex=\"-1\"` lets the drawer's \"Show N\" button and the\n focus fallbacks in DirectoryIndexClient move focus here. */}\n <h2\n id=\"results-heading\"\n tabindex=\"-1\"\n class=\"m-0 mb-5 scroll-mt-4 text-2xs font-normal text-ink-500 dark:text-ink-400\"\n >\n <span id=\"results-count\" class=\"font-mono font-semibold text-ink-900 dark:text-ink-100\">\n {sorted.length} {sorted.length === 1 ? itemLabel() : itemLabelPlural()}\n </span>\n <span id=\"results-sort\">{` · sorted by ${sortDisplay(sort)}`}</span>\n <span id=\"results-page\">{pages > 1 ? ` · page ${page} of ${pages}` : \"\"}</span>\n </h2>\n\n {/* Screen readers hear the result count here, debounced by\n DirectoryIndexClient so rapid toggles make one announcement.\n The visible count above is deliberately not a live region,\n or every change would be announced twice. */}\n <p id=\"results-status\" class=\"sr-only\" role=\"status\" aria-live=\"polite\" aria-atomic=\"true\"></p>\n\n <CardGrid id=\"results-list\">\n {pageItems.map((item, i) => (\n <li class=\"m-0 p-0\" data-record-slug={item.slug}>\n <IndexRow\n record={item as Parameters<typeof IndexRow>[0][\"record\"]}\n detailHref={`/${slug}/${item.slug}/`}\n eager={i < 3}\n />\n </li>\n ))}\n </CardGrid>\n\n <div id=\"empty-state\" class:list={[\"py-12 text-center\", sorted.length > 0 && \"hidden\"]}>\n <p class=\"m-0 text-sm font-medium text-ink-700 dark:text-ink-200\">\n {`No ${itemLabelPlural()} match these filters.`}\n </p>\n {/* The client keeps this href in step with the live query, so\n clearing keeps the chosen sort, and on a scoped page it stays\n on that page. */}\n <Button href={clearFiltersHref} variant=\"secondary\" size=\"sm\" class=\"mt-4\" data-empty-reset>Clear filters</Button>\n </div>\n {/* Plain div wrapper — Pagination renders its own\n <nav aria-label=\"Pagination\">, so a nav here would nest two\n identical landmarks. */}\n <div id=\"results-pagination\" class=\"mt-8 flex flex-wrap items-center justify-center gap-1.5\">\n <Pagination current={page} total={pages} hrefFor={hrefForResultPage} />\n </div>\n </div>\n</section>\n\n<DirectoryIndexClient\n slug={slug}\n singular={itemLabel()}\n plural={itemLabelPlural()}\n taxonomy={taxonomy}\n routePage={page}\n scope={scoped ? scope : undefined}\n pathPrefix={pathPrefix}\n/>\n",
45
+ "type": "registry:component",
46
+ "target": "~/src/components/grove/directory-browse-view.astro"
47
+ },
42
48
  {
43
49
  "path": "default/components/grove/directory-index-client.astro",
44
- "content": "---\n/**\n * DirectoryIndexClient — the browse page's client controller.\n *\n * The browse routes are prerendered per page (`/{slug}/`,\n * `/{slug}/page/2/`), so the server never sees a query string. This\n * script re-reads `location.search` and re-derives results, chips,\n * facet counts, and pagination with the same `@grove-dev/core/directory`\n * functions the server used.\n *\n * Two modes, one list:\n * - **No filters** — the server-rendered page slice is already right.\n * Pagination links stay the real `/page/n/` paths.\n * - **Filtered** — the whole record set is filtered here, the page\n * re-renders from `clientItemsJson`, and pagination switches to\n * `?page=N` on the base route.\n *\n * Filters apply live. Changes made while a facet popover or the mobile\n * drawer is open replace the current history entry, and closing the\n * last one pushes a single entry (see `FilterHistorySession`), so Back\n * skips the individual checkboxes. The result count goes to a\n * debounced polite live region, and re-renders never leave keyboard\n * focus stranded on `<body>`.\n */\ninterface Props {\n slug: string;\n singular: string;\n plural: string;\n taxonomy: Record<string, unknown>;\n /** Page this route prerendered; the client starts from it. */\n routePage?: number;\n}\n\nconst { slug, singular, plural, taxonomy, routePage = 1 } = Astro.props;\nconst clientConfigJson = JSON.stringify({ slug, singular, plural, taxonomy, routePage }).replace(\n /</g,\n '\\\\u003c',\n);\n---\n\n<script is:inline id=\"grove-index-config\" type=\"application/json\" set:html={clientConfigJson}></script>\n<script>\n import type { IndexRecord } from \"@grove-dev/core\";\n import type { DirectoryFilterGroupKey } from \"@grove-dev/core/directory\";\n import {\n PAGE_SIZE,\n activeFilterChips,\n applySort,\n buildFacets,\n DIRECTORY_FILTER_KEYS,\n DIRECTORY_FILTER_LABELS,\n DIRECTORY_TAXONOMY_KINDS,\n effectivePage,\n effectiveSort,\n filterRecords,\n filtersFromSearchParams,\n hasAnyFilter,\n isDirectoryFilterGroupKey,\n hrefForClearedFilters,\n hrefForFilters,\n pagePathHref,\n paginationPageList,\n searchParamsFromFilters,\n sortDisplay,\n totalPages,\n } from \"@grove-dev/core/directory\";\n import {\n PAGINATION_DISABLED,\n PAGINATION_EXTRA,\n buttonClass,\n chipClass,\n filterTriggerClass,\n } from \"../../lib/classnames.ts\";\n import {\n FilterHistorySession,\n canAdoptInPlace,\n countLabel,\n debounce as debounced,\n focusIndexAfterRender,\n resultsAnnouncement,\n showResultsLabel,\n } from \"../../lib/live-filters.ts\";\n\n (() => {\n const configSource = document.querySelector(\"#grove-index-config\");\n const listNode = document.querySelector<HTMLElement>(\"#results-list\");\n if (!configSource || !listNode) return;\n // Closures below cannot see the guard above; bind the narrowed type once.\n const list = listNode;\n\n const { slug, singular, plural, taxonomy, routePage } = JSON.parse(\n configSource.textContent || \"{}\",\n );\n // Filled by `loadRecords()`. Until then the page shows what the\n // server rendered, which for an unfiltered view is already right.\n let items: IndexRecord[] = [];\n const pathPrefix = `/${slug}`;\n\n // Cards for this page came with the document. A filtered view can\n // surface any record in the directory, so the rest are fetched\n // once from `/{slug}/page/cards/` — rendered there by the same\n // server component, which is what keeps the card to a single\n // definition instead of a second one written in JavaScript.\n const nodes = new Map<string, HTMLElement>();\n for (const node of list.querySelectorAll(\":scope > [data-record-slug]\")) {\n const key = (node as HTMLElement).dataset.recordSlug;\n if (key) nodes.set(key, node as HTMLElement);\n }\n\n // The record index — everything filtering, sorting, and facet\n // counting reads. Fetched rather than inlined so a paginated page\n // does not carry the whole directory in its HTML.\n let recordSource: Promise<void> | null = null;\n let recordsSettled = false;\n function loadRecords(): Promise<void> {\n if (!recordSource) {\n recordSource = fetch(`${pathPrefix}/page/records.json`)\n .then((response) => (response.ok ? response.json() : []))\n .then((data) => {\n items = Array.isArray(data) ? data : [];\n })\n .catch(() => {\n items = [];\n })\n .then(() => {\n // Settled either way: a failed fetch must not leave the\n // page retrying forever behind a busy list.\n recordsSettled = true;\n });\n }\n return recordSource;\n }\n\n let cardSource: Promise<void> | null = null;\n let cardsSettled = false;\n function loadAllCards(): Promise<void> {\n if (!cardSource) {\n cardSource = fetch(`${pathPrefix}/page/cards/`)\n .then((response) => (response.ok ? response.text() : \"\"))\n .then((html) => {\n if (!html) return;\n const parsed = new DOMParser().parseFromString(html, \"text/html\");\n for (const node of parsed.querySelectorAll(\"#grove-index-cards > [data-record-slug]\")) {\n const key = (node as HTMLElement).dataset.recordSlug;\n if (key && !nodes.has(key)) nodes.set(key, document.adoptNode(node) as HTMLElement);\n }\n })\n .catch(() => {\n // Offline or a stale deploy: the page keeps working with\n // the records it already has.\n })\n .then(() => {\n cardsSettled = true;\n });\n }\n return cardSource;\n }\n /** Everything a filtered view needs: the index and the cards. */\n const loadAll = () => Promise.all([loadRecords(), loadAllCards()]);\n\n // Warm on the first sign of intent — a pointer or focus reaching\n // the controls — rather than on idle. Prefetching a whole\n // directory during load competes with the page itself for\n // bandwidth on a phone, and most visitors never filter at all.\n const controls = document.querySelector(\"#search-form\")?.parentElement ?? document;\n for (const type of [\"pointerdown\", \"focusin\", \"keydown\"]) {\n controls.addEventListener(type, () => loadAll(), { once: true, passive: true });\n }\n\n let params = new URLSearchParams(location.search);\n let filters = filtersFromSearchParams(params);\n let sort = effectiveSort(filters);\n\n /**\n * True when the URL asks for something the prerendered document\n * does not already show. `hasAnyFilter` deliberately ignores\n * `sort`, but a sorted view is just as much a client view: the\n * `/page/N/` documents are all built with the default sort, so\n * paging out of `?sort=most-starred` onto one of them would\n * silently re-sort the list mid-journey.\n */\n const isClientView = () => hasAnyFilter(filters) || Boolean(filters.sort);\n\n /** Client views own the page number; prerendered ones use the path. */\n const currentPage = () => (isClientView() ? effectivePage(filters) : routePage || 1);\n\n const heading = document.querySelector<HTMLElement>(\"#results-heading\");\n const drawerResults = document.querySelector<HTMLElement>(\"[data-drawer-results]\");\n\n // The count is announced once rapid toggles settle. One message\n // per burst, not one per checkbox.\n const status = document.querySelector(\"#results-status\");\n const announce = debounced((text: string) => {\n if (!status) return;\n // Assistive tech skips a live region whose text did not change.\n // A trailing no-break space makes a repeat count heard again.\n status.textContent = status.textContent === text ? `${text}\\u00a0` : text;\n }, 500);\n /** Set by user-driven re-renders. The first render stays silent. */\n let announceNext = false;\n\n /** Busy while a change waits on the record index. */\n function setPending(pending: boolean) {\n if (pending) list.setAttribute(\"aria-busy\", \"true\");\n else list.removeAttribute(\"aria-busy\");\n list.classList.toggle(\"opacity-60\", pending);\n if (drawerResults) {\n if (pending) {\n drawerResults.setAttribute(\"aria-busy\", \"true\");\n drawerResults.textContent = showResultsLabel(0, singular, plural, true);\n } else {\n drawerResults.removeAttribute(\"aria-busy\");\n }\n }\n }\n\n /**\n * Where focus goes when the element that had it disappears in a\n * re-render. Inside the open drawer it stays in the drawer, because\n * the page behind a modal dialog is inert. Everywhere else it goes\n * to the results heading.\n */\n function focusFallback(lost: Element | null) {\n const dialog = lost?.closest(\"dialog[open]\");\n const target = dialog\n ? dialog.querySelector<HTMLElement>(\".grove-filter-trigger, [data-drawer-close]\")\n : heading;\n target?.focus({ preventScroll: true });\n }\n\n /**\n * Run a re-render, and if it removed or hid the focused element,\n * move focus somewhere sensible instead of <body>. Focus is only\n * moved when the re-render lost it, never taken from elsewhere.\n */\n function keepingFocus(render: () => void) {\n const before = document.activeElement;\n render();\n if (!(before instanceof HTMLElement) || before === document.body) return;\n const now = document.activeElement;\n const lost =\n !before.isConnected ||\n Boolean(before.closest(\".hidden, [hidden]\")) ||\n now === null ||\n now === document.body;\n if (lost && (now === null || now === document.body || now === before)) focusFallback(before);\n }\n\n const hrefForResultPage = (target: number) =>\n isClientView()\n ? hrefForFilters({ ...filters, page: target }, pathPrefix)\n : pagePathHref(pathPrefix, target);\n\n /** Move the page's cards into the list, in result order. */\n function renderList(visible: { slug: string }[]) {\n const next: HTMLElement[] = [];\n let missing = false;\n for (const record of visible) {\n const node = nodes.get(record.slug);\n if (node) next.push(node);\n else missing = true;\n }\n list.replaceChildren(...next);\n // A record whose card has not arrived yet: render what we have\n // and finish the moment the card source lands. Only while the\n // fetch is still outstanding — once it has settled, a missing\n // card is missing, and retrying would spin.\n if (missing && !cardsSettled) loadAllCards().then(() => applyClientFilters());\n }\n\n function applyClientFilters() {\n const filtered = applySort(filterRecords(items, filters), sort);\n const pageCount = totalPages(filtered.length);\n const page = Math.min(Math.max(1, currentPage()), pageCount);\n renderList(filtered.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE));\n\n const count = document.querySelector(\"#results-count\");\n const pageLabel = document.querySelector(\"#results-page\");\n const empty = document.querySelector(\"#empty-state\");\n if (count) count.textContent = countLabel(filtered.length, singular, plural);\n if (drawerResults) drawerResults.textContent = showResultsLabel(filtered.length, singular, plural);\n if (announceNext) {\n announceNext = false;\n announce(resultsAnnouncement(filtered.length, singular, plural));\n }\n // The zero-results reset keeps the chosen sort, like \"Clear all\".\n const emptyReset = document.querySelector(\"[data-empty-reset]\");\n if (emptyReset instanceof HTMLAnchorElement) {\n emptyReset.href = hrefForClearedFilters(filters, pathPrefix);\n }\n const sortLabel = document.querySelector(\"#results-sort\");\n if (sortLabel) sortLabel.textContent = ` · sorted by ${sortDisplay(sort)}`;\n if (pageLabel) pageLabel.textContent = pageCount > 1 ? ` · page ${page} of ${pageCount}` : \"\";\n if (empty) empty.classList.toggle(\"hidden\", filtered.length > 0);\n\n // Rebuild the pagination controls, mirroring the server-rendered\n // `Pagination.astro` (Previous/Next + windowed page list via the\n // shared `paginationPageList`) so client filtering never degrades\n // the affordances of the initial render.\n const pagination = document.querySelector(\"#results-pagination\");\n if (pagination) {\n pagination.innerHTML = \"\";\n if (pageCount > 1) {\n const linkClass = buttonClass(\"secondary\", \"sm\", PAGINATION_EXTRA);\n const nav = document.createElement(\"nav\");\n nav.className = \"flex flex-wrap items-center justify-center gap-1.5\";\n nav.setAttribute(\"aria-label\", \"Pagination\");\n const control = (label: string, target: number | null, rel?: string) => {\n if (target === null) {\n const span = document.createElement(\"span\");\n span.className = `${linkClass} ${PAGINATION_DISABLED}`;\n span.textContent = label;\n return span;\n }\n const link = document.createElement(\"a\");\n link.href = hrefForResultPage(target);\n link.textContent = label;\n link.className = linkClass;\n if (rel) link.rel = rel;\n return link;\n };\n nav.append(control(\"Previous\", page > 1 ? page - 1 : null, \"prev\"));\n for (const entry of paginationPageList(page, pageCount)) {\n if (entry === \"ellipsis\") {\n const dots = document.createElement(\"span\");\n dots.className = \"px-1 text-2xs text-ink-400\";\n dots.setAttribute(\"aria-hidden\", \"true\");\n dots.textContent = \"...\";\n nav.append(dots);\n continue;\n }\n const link = control(String(entry), entry);\n link.setAttribute(\"aria-label\", `Page ${entry}`);\n if (entry === page) {\n link.setAttribute(\"aria-current\", \"page\");\n link.className = buttonClass(\"selected\", \"sm\", PAGINATION_EXTRA);\n }\n nav.append(link);\n }\n nav.append(control(\"Next\", page < pageCount ? page + 1 : null, \"next\"));\n pagination.append(nav);\n }\n }\n }\n\n const searchInput = document.querySelector(\"#search-input\");\n const searchClear = document.querySelector(\"[data-search-clear]\");\n if (searchInput instanceof HTMLInputElement) searchInput.value = filters.q || \"\";\n document.querySelectorAll('select[name=\"sort\"]').forEach((select) => {\n if (select instanceof HTMLSelectElement) select.value = sort;\n });\n\n const filterKeys = DIRECTORY_FILTER_KEYS;\n const filterLabels = DIRECTORY_FILTER_LABELS;\n const taxonomyKinds = DIRECTORY_TAXONOMY_KINDS;\n const taxonomyName = (groupKey: DirectoryFilterGroupKey, value: string) =>\n (taxonomy[taxonomyKinds[groupKey]] || []).find(\n (entry: { id: string; name: string }) => entry.id === value,\n )?.name ?? value;\n\n /**\n * Chip labels and remove hrefs come from core — one definition.\n * The same chips render in every `[data-active-filters]` row:\n * above the results, and inside the mobile filter sheet.\n */\n function renderChips() {\n const chips = activeFilterChips(filters, { taxonomy, pathPrefix });\n document.querySelectorAll<HTMLElement>(\"[data-active-filters]\").forEach((row) => {\n // Removing a chip removes the link that had focus. Remember\n // its position and give focus to whatever takes its place.\n const focused = document.activeElement;\n const focusIndex =\n focused instanceof HTMLAnchorElement && row.contains(focused)\n ? [...row.querySelectorAll(\"a\")].indexOf(focused)\n : -1;\n\n row.innerHTML = \"\";\n for (const chip of chips) {\n const link = document.createElement(\"a\");\n link.href = chip.href;\n // The whole anchor is the remove control; the visible label\n // announces the filter value, and the aria-label spells out\n // the action for assistive tech.\n link.setAttribute(\"aria-label\", `Remove filter: ${chip.label}`);\n link.className = chipClass();\n link.append(document.createTextNode(`${chip.label} `));\n const close = document.createElement(\"span\");\n close.setAttribute(\"aria-hidden\", \"true\");\n close.textContent = \"×\";\n link.append(close);\n row.append(link);\n }\n if (chips.length && !row.hasAttribute(\"data-without-clear\")) {\n const clear = document.createElement(\"a\");\n clear.href = hrefForClearedFilters(filters, pathPrefix);\n clear.className =\n \"text-2xs font-medium text-ink-500 underline decoration-border underline-offset-2 hover:text-ink-900 dark:hover:text-ink-100\";\n clear.setAttribute(\"aria-label\", \"Clear all active filters\");\n clear.textContent = \"Clear all\";\n row.append(clear);\n }\n row.classList.toggle(\"hidden\", chips.length === 0);\n\n if (focusIndex >= 0) {\n const links = row.querySelectorAll(\"a\");\n const next = focusIndexAfterRender(focusIndex, links.length);\n if (next >= 0) links[next]?.focus({ preventScroll: true });\n else focusFallback(row);\n }\n });\n\n // Mobile filter-drawer badge + its clear-all mirror the chips.\n const drawerCount = document.querySelector(\"[data-drawer-count]\");\n if (drawerCount) {\n drawerCount.textContent = String(chips.length);\n drawerCount.classList.toggle(\"hidden\", chips.length === 0);\n }\n const drawerClear = document.querySelector(\"[data-drawer-clear]\");\n if (drawerClear instanceof HTMLAnchorElement) {\n drawerClear.href = hrefForClearedFilters(filters, pathPrefix);\n drawerClear.classList.toggle(\"hidden\", chips.length === 0);\n }\n }\n\n function renderFilterTriggers() {\n const values = (key: string) => params.getAll(key).filter(Boolean);\n document.querySelectorAll(\".grove-filter\").forEach((group) => {\n if (!(group instanceof HTMLElement)) return;\n const groupKey = group.dataset.filterGroupKey;\n if (!groupKey || !isDirectoryFilterGroupKey(groupKey)) return;\n const selected = values(filterKeys[groupKey]);\n group.querySelectorAll(\".grove-filter-input\").forEach((input) => {\n if (input instanceof HTMLInputElement) {\n input.checked = selected.includes(input.dataset.filterValue || \"\");\n }\n });\n const triggerButton = group.querySelector(\".grove-filter-trigger\");\n const trigger = triggerButton?.querySelector(\"span\");\n const label = filterLabels[groupKey];\n if (trigger) {\n trigger.textContent = selected.length\n ? `${label}: ${\n selected.length === 1\n ? taxonomyName(groupKey, selected[0] ?? \"\")\n : `${selected.length} selected`\n }`\n : `${label}: Any`;\n }\n if (triggerButton) {\n // Same builder the server render used — the class string is\n // reassigned wholesale so the two can never drift.\n triggerButton.className = filterTriggerClass(selected.length > 0);\n }\n group.querySelector(\".grove-filter-clear\")?.classList.toggle(\"hidden\", selected.length === 0);\n });\n }\n\n // Facet counts were rendered at build time from the UNFILTERED\n // record set (the route is prerendered, so the server never sees\n // the live query string). Recompute intersection counts against\n // the current filters and patch each count span in place —\n // never re-render the option lists, which would destroy\n // checkbox, focus, and scroll state.\n function renderFacetCounts() {\n const liveFacets: Record<string, { value: string; count: number }[]> = buildFacets(items, {\n filters,\n curatedTagIds: (taxonomy.topics || []).map((topic: { id: string }) => topic.id),\n });\n document.querySelectorAll(\"[data-facet-count]\").forEach((span) => {\n if (!(span instanceof HTMLElement)) return;\n const options = liveFacets[span.dataset.facet ?? \"\"] ?? [];\n const count = options.find((option) => option.value === span.dataset.value)?.count ?? 0;\n span.textContent = String(count);\n const row = span.closest(\"label\");\n const input = row?.querySelector(\".grove-filter-input\");\n const checked = input instanceof HTMLInputElement && input.checked;\n // A zero-count option can't narrow anything — dim and disable\n // it unless it's the currently selected value (which must stay\n // interactive so the user can un-select it).\n // The focused option is never disabled under the user; that\n // would drop keyboard focus to <body>.\n const inert = count === 0 && !checked && input !== document.activeElement;\n row?.classList.toggle(\"opacity-45\", inert);\n if (input instanceof HTMLInputElement) input.disabled = inert;\n });\n }\n\n function renderAll() {\n renderChips();\n renderFilterTriggers();\n if (searchClear instanceof HTMLElement) searchClear.hidden = !(filters.q || \"\").length;\n\n if (recordsSettled) {\n renderFacetCounts();\n applyClientFilters();\n setPending(false);\n return;\n }\n // Nothing to filter with yet. A plain view of this page is\n // already correct as the server rendered it; anything the URL\n // asks for beyond that — a filter, a search, a sort — waits for\n // the index and the cards, and says so while it does.\n if (!isClientView()) return;\n setPending(true);\n loadAll().then(() => {\n setPending(false);\n keepingFocus(renderAll);\n });\n }\n\n /**\n * Adopt a URL without a navigation, then re-render from it.\n *\n * A URL with no query is a prerendered document — clearing the\n * last filter lands on `/{slug}/`, which on page 2+ is a\n * *different* document than the one on screen. Adopting it there\n * would leave records 21–40 rendered under the page-1 URL, so\n * that case navigates for real.\n */\n function adopt(url: string, mode: \"push\" | \"replace\") {\n const next = new URL(url, location.origin);\n if (!canAdoptInPlace(next, location.pathname, routePage || 1)) {\n location.assign(next.toString());\n return;\n }\n const state = { grove: true, scrollY: window.scrollY };\n // Re-selecting the URL already on screen (the header's Browse\n // link on an unfiltered page 1) must not add a Back step.\n if (mode === \"push\" && next.href !== location.href) history.pushState(state, \"\", next);\n else history.replaceState(state, \"\", next);\n params = new URLSearchParams(next.search);\n filters = filtersFromSearchParams(params);\n sort = effectiveSort(filters);\n // A chip, \"Clear all\" or the zero-results reset can drop the\n // query. Keep the box in step, but never rewrite it while the\n // user is typing in it.\n if (searchInput instanceof HTMLInputElement && document.activeElement !== searchInput) {\n searchInput.value = filters.q || \"\";\n }\n announceNext = true;\n keepingFocus(renderAll);\n }\n\n /** The current URL as the history session compares it. */\n const here = () => `${location.pathname}${location.search}`;\n\n // One history entry per filter session. A popover or the drawer\n // opening starts a session. While it is open, changes replace the\n // current entry. When the last surface closes, the starting URL is\n // put back on this entry and the final URL is pushed once.\n const session = new FilterHistorySession();\n document.addEventListener(\"grove:filter-surface\", (event) => {\n const detail = (event as CustomEvent<{ surface: string; open: boolean }>).detail;\n if (!detail?.surface) return;\n if (detail.open) {\n session.open(detail.surface, { url: here(), scrollY: window.scrollY });\n return;\n }\n const commit = session.close(detail.surface, here());\n if (!commit) return;\n history.replaceState({ grove: true, scrollY: commit.start.scrollY }, \"\", commit.start.url);\n history.pushState({ grove: true, scrollY: window.scrollY }, \"\", commit.end);\n });\n\n // Search filters as you type. `replaceState` keeps a search\n // session out of the history stack — Back should return to the\n // previous result set, not to the previous keystroke.\n let debounce = 0;\n searchInput?.addEventListener(\"input\", () => {\n window.clearTimeout(debounce);\n debounce = window.setTimeout(() => {\n const query = searchInput instanceof HTMLInputElement ? searchInput.value.trim() : \"\";\n adopt(hrefForFilters({ ...filters, q: query || undefined, page: 1 }, pathPrefix), \"replace\");\n // Only reclaim focus when the re-render dropped it. If the\n // user has already moved on (tabbed to a filter) focus stays\n // where they put it.\n if (searchInput instanceof HTMLInputElement && document.activeElement === document.body) {\n searchInput.focus();\n }\n }, 150);\n });\n searchClear?.addEventListener(\"click\", () => {\n if (searchInput instanceof HTMLInputElement) {\n searchInput.value = \"\";\n searchInput.focus();\n }\n adopt(hrefForFilters({ ...filters, q: undefined, page: 1 }, pathPrefix), \"replace\");\n });\n document.querySelector(\"#search-form\")?.addEventListener(\"submit\", (event) => {\n // Enter already has its answer on screen; submitting would only\n // reload the same state.\n event.preventDefault();\n });\n\n // RefinePanel asks before it navigates; cancelling means \"this\n // page can apply the URL in place\".\n document.addEventListener(\"grove:navigate\", (event) => {\n const url = (event as CustomEvent<{ url: string }>).detail?.url;\n if (!url) return;\n event.preventDefault();\n // Inside an open popover or drawer, replace; the session pushes\n // once on close. Outside one (the sort select), push.\n adopt(url, session.modeForChange());\n });\n\n // Filtered navigation is a real step: Back returns to the\n // previous result set and its scroll position.\n //\n // Links that carry a query are adopted. A link to the bare list\n // (`/{slug}/` from \"Clear all\", the last chip, or the \"1\"\n // pagination link) is adopted only from page 1 of that list,\n // where it is the document already on screen. That keeps focus and\n // an open filter drawer in place. From `/{slug}/page/2/` it is a\n // different prerendered document and must actually navigate.\n // Swallowing it there left page 2's records rendered under the\n // page-1 URL. Hash links (the skip link) are never ours.\n document.addEventListener(\"click\", (event) => {\n const link = (event.target as HTMLElement | null)?.closest(\"a\");\n if (!(link instanceof HTMLAnchorElement)) return;\n if (event.defaultPrevented || event.metaKey || event.ctrlKey || event.shiftKey) return;\n if (link.target === \"_blank\" || !link.href.startsWith(location.origin)) return;\n const url = new URL(link.href);\n if (url.hash) return;\n const isListUrl = url.pathname === `${pathPrefix}/` || url.pathname === pathPrefix;\n if (!isListUrl || !canAdoptInPlace(url, location.pathname, routePage || 1)) return;\n event.preventDefault();\n // A chip removed inside the open drawer is part of that filter\n // session. It replaces, and the page does not jump under the sheet.\n if (session.active) {\n adopt(url.toString(), \"replace\");\n return;\n }\n history.replaceState({ grove: true, scrollY: window.scrollY }, \"\");\n adopt(url.toString(), \"push\");\n window.scrollTo({ top: 0, behavior: \"instant\" as ScrollBehavior });\n });\n\n window.addEventListener(\"popstate\", (event) => {\n params = new URLSearchParams(location.search);\n filters = filtersFromSearchParams(params);\n sort = effectiveSort(filters);\n if (searchInput instanceof HTMLInputElement) searchInput.value = filters.q || \"\";\n document.querySelectorAll('select[name=\"sort\"]').forEach((select) => {\n if (select instanceof HTMLSelectElement) select.value = sort;\n });\n // Back/Forward with a popover or the drawer still open: this\n // entry becomes where that session started.\n session.rebase({ url: here(), scrollY: window.scrollY });\n announceNext = true;\n keepingFocus(renderAll);\n const state = event.state as { scrollY?: number } | null;\n if (typeof state?.scrollY === \"number\") {\n window.scrollTo({ top: state.scrollY, behavior: \"instant\" as ScrollBehavior });\n }\n });\n\n renderAll();\n })();\n</script>\n",
50
+ "content": "---\n/**\n * DirectoryIndexClient — the browse page's client controller.\n *\n * The browse routes are prerendered per page (`/{slug}/`,\n * `/{slug}/page/2/`), so the server never sees a query string. This\n * script re-reads `location.search` and re-derives results, chips,\n * facet counts, and pagination with the same `@grove-dev/core/directory`\n * functions the server used.\n *\n * Two modes, one list:\n * - **No filters** — the server-rendered page slice is already right.\n * Pagination links stay the real `/page/n/` paths.\n * - **Filtered** — the whole record set is filtered here, the page\n * re-renders from `clientItemsJson`, and pagination switches to\n * `?page=N` on the base route.\n *\n * Filters apply live. Changes made while a facet popover or the mobile\n * drawer is open replace the current history entry, and closing the\n * last one pushes a single entry (see `FilterHistorySession`), so Back\n * skips the individual checkboxes. The result count goes to a\n * debounced polite live region, and re-renders never leave keyboard\n * focus stranded on `<body>`.\n *\n * With a `scope` (a taxonomy page), the record index is narrowed to the\n * scope before anything else, the scoped groups are stripped from the\n * URL's filters, and every URL is built on the page's own\n * `pathPrefix`. A scoped list is one page long: it has no prerendered\n * `/page/{n}/` routes to hand off to.\n */\nimport type { DirectoryScope } from '../../lib/live-filters.ts';\n\ninterface Props {\n /** Directory route slug: where the record index and cards live. */\n slug: string;\n singular: string;\n plural: string;\n taxonomy: Record<string, unknown>;\n /** Page this route prerendered; the client starts from it. */\n routePage?: number;\n /** Immutable filters merged into every query (see DirectoryBrowseView). */\n scope?: DirectoryScope | undefined;\n /** Path filtered URLs are built on. Default: `/{slug}`. */\n pathPrefix?: string;\n}\n\nconst {\n slug,\n singular,\n plural,\n taxonomy,\n routePage = 1,\n scope,\n pathPrefix = `/${slug}`,\n} = Astro.props;\nconst clientConfigJson = JSON.stringify({\n slug,\n singular,\n plural,\n taxonomy,\n routePage,\n scope: scope ?? null,\n pathPrefix,\n}).replace(/</g, '\\\\u003c');\n---\n\n<script is:inline id=\"grove-index-config\" type=\"application/json\" set:html={clientConfigJson}></script>\n<script>\n import type { IndexFilters, IndexRecord } from \"@grove-dev/core\";\n import type { DirectoryFilterGroupKey } from \"@grove-dev/core/directory\";\n import {\n PAGE_SIZE,\n activeFilterChips,\n applySort,\n buildFacets,\n DIRECTORY_FILTER_KEYS,\n DIRECTORY_FILTER_LABELS,\n DIRECTORY_TAXONOMY_KINDS,\n effectivePage,\n effectiveSort,\n filterRecords,\n filtersFromSearchParams,\n hasAnyFilter,\n isDirectoryFilterGroupKey,\n hrefForClearedFilters,\n hrefForFilters,\n pagePathHref,\n paginationPageList,\n searchParamsFromFilters,\n sortDisplay,\n totalPages,\n } from \"@grove-dev/core/directory\";\n import {\n PAGINATION_DISABLED,\n PAGINATION_EXTRA,\n buttonClass,\n chipClass,\n filterTriggerClass,\n } from \"../../lib/classnames.ts\";\n import {\n FilterHistorySession,\n canAdoptInPlace,\n countLabel,\n debounce as debounced,\n focusIndexAfterRender,\n resultsAnnouncement,\n scopedGroups,\n searchWithoutScope,\n showResultsLabel,\n withoutScope,\n } from \"../../lib/live-filters.ts\";\n import type { DirectoryScope } from \"../../lib/live-filters.ts\";\n\n (() => {\n const configSource = document.querySelector(\"#grove-index-config\");\n const listNode = document.querySelector<HTMLElement>(\"#results-list\");\n if (!configSource || !listNode) return;\n // Closures below cannot see the guard above; bind the narrowed type once.\n const list = listNode;\n\n const config = JSON.parse(configSource.textContent || \"{}\");\n const { slug, singular, plural, taxonomy, routePage, pathPrefix: listPath } = config;\n const scope: DirectoryScope | null = config.scope ?? null;\n const scoped = scopedGroups(scope).length > 0;\n // Filled by `loadRecords()`. Until then the page shows what the\n // server rendered, which for an unfiltered view is already right.\n let items: IndexRecord[] = [];\n // The record index and the cards always live under the directory.\n // The URLs this page builds live under its own path, which is the\n // same thing except on a scoped page.\n const dataPrefix = `/${slug}`;\n const pathPrefix: string = listPath || dataPrefix;\n\n /** URL filters, minus anything the scope already fixes. */\n const readFilters = (source: URLSearchParams) =>\n withoutScope(filtersFromSearchParams(source), scope);\n\n // Cards for this page came with the document. A filtered view can\n // surface any record in the directory, so the rest are fetched\n // once from `/{slug}/page/cards/` — rendered there by the same\n // server component, which is what keeps the card to a single\n // definition instead of a second one written in JavaScript.\n const nodes = new Map<string, HTMLElement>();\n for (const node of list.querySelectorAll(\":scope > [data-record-slug]\")) {\n const key = (node as HTMLElement).dataset.recordSlug;\n if (key) nodes.set(key, node as HTMLElement);\n }\n\n // The record index — everything filtering, sorting, and facet\n // counting reads. Fetched rather than inlined so a paginated page\n // does not carry the whole directory in its HTML.\n let recordSource: Promise<void> | null = null;\n let recordsSettled = false;\n function loadRecords(): Promise<void> {\n if (!recordSource) {\n recordSource = fetch(`${dataPrefix}/page/records.json`)\n .then((response) => (response.ok ? response.json() : []))\n .then((data) => {\n const all: IndexRecord[] = Array.isArray(data) ? data : [];\n // The scope is applied once, here. Everything downstream\n // (results, facet counts) only ever sees the scoped set.\n items = scope ? filterRecords(all, scope as IndexFilters) : all;\n })\n .catch(() => {\n items = [];\n })\n .then(() => {\n // Settled either way: a failed fetch must not leave the\n // page retrying forever behind a busy list.\n recordsSettled = true;\n });\n }\n return recordSource;\n }\n\n let cardSource: Promise<void> | null = null;\n let cardsSettled = false;\n function loadAllCards(): Promise<void> {\n if (!cardSource) {\n cardSource = fetch(`${dataPrefix}/page/cards/`)\n .then((response) => (response.ok ? response.text() : \"\"))\n .then((html) => {\n if (!html) return;\n const parsed = new DOMParser().parseFromString(html, \"text/html\");\n for (const node of parsed.querySelectorAll(\"#grove-index-cards > [data-record-slug]\")) {\n const key = (node as HTMLElement).dataset.recordSlug;\n if (key && !nodes.has(key)) nodes.set(key, document.adoptNode(node) as HTMLElement);\n }\n })\n .catch(() => {\n // Offline or a stale deploy: the page keeps working with\n // the records it already has.\n })\n .then(() => {\n cardsSettled = true;\n });\n }\n return cardSource;\n }\n /** Everything a filtered view needs: the index and the cards. */\n const loadAll = () => Promise.all([loadRecords(), loadAllCards()]);\n\n // Warm on the first sign of intent — a pointer or focus reaching\n // the controls — rather than on idle. Prefetching a whole\n // directory during load competes with the page itself for\n // bandwidth on a phone, and most visitors never filter at all.\n const controls = document.querySelector(\"#search-form\")?.parentElement ?? document;\n for (const type of [\"pointerdown\", \"focusin\", \"keydown\"]) {\n controls.addEventListener(type, () => loadAll(), { once: true, passive: true });\n }\n\n // A hand-written `/stacks/flutter/?stack=react` names the scope\n // in the query. The scope wins, so tidy the URL to match what the\n // page shows.\n const tidied = searchWithoutScope(location.search, scope, DIRECTORY_FILTER_KEYS);\n if (tidied !== null) {\n history.replaceState(history.state, \"\", `${location.pathname}${tidied}${location.hash}`);\n }\n\n let params = new URLSearchParams(location.search);\n let filters = readFilters(params);\n let sort = effectiveSort(filters);\n\n /**\n * True when the URL asks for something the prerendered document\n * does not already show. `hasAnyFilter` deliberately ignores\n * `sort`, but a sorted view is just as much a client view: the\n * `/page/N/` documents are all built with the default sort, so\n * paging out of `?sort=most-starred` onto one of them would\n * silently re-sort the list mid-journey.\n */\n const isClientView = () => hasAnyFilter(filters) || Boolean(filters.sort);\n\n /** Client views own the page number; prerendered ones use the path. */\n const currentPage = () => (isClientView() ? effectivePage(filters) : routePage || 1);\n\n /** A scoped list is one page, like its prerendered document. */\n const pageSizeFor = (count: number) => (scoped ? Math.max(count, 1) : PAGE_SIZE);\n\n const heading = document.querySelector<HTMLElement>(\"#results-heading\");\n const drawerResults = document.querySelector<HTMLElement>(\"[data-drawer-results]\");\n\n // The count is announced once rapid toggles settle. One message\n // per burst, not one per checkbox.\n const status = document.querySelector(\"#results-status\");\n const announce = debounced((text: string) => {\n if (!status) return;\n // Assistive tech skips a live region whose text did not change.\n // A trailing no-break space makes a repeat count heard again.\n status.textContent = status.textContent === text ? `${text}\\u00a0` : text;\n }, 500);\n /** Set by user-driven re-renders. The first render stays silent. */\n let announceNext = false;\n\n /** Busy while a change waits on the record index. */\n function setPending(pending: boolean) {\n if (pending) list.setAttribute(\"aria-busy\", \"true\");\n else list.removeAttribute(\"aria-busy\");\n list.classList.toggle(\"opacity-60\", pending);\n if (drawerResults) {\n if (pending) {\n drawerResults.setAttribute(\"aria-busy\", \"true\");\n drawerResults.textContent = showResultsLabel(0, singular, plural, true);\n } else {\n drawerResults.removeAttribute(\"aria-busy\");\n }\n }\n }\n\n /**\n * Where focus goes when the element that had it disappears in a\n * re-render. Inside the open drawer it stays in the drawer, because\n * the page behind a modal dialog is inert. Everywhere else it goes\n * to the results heading.\n */\n function focusFallback(lost: Element | null) {\n const dialog = lost?.closest(\"dialog[open]\");\n const target = dialog\n ? dialog.querySelector<HTMLElement>(\".grove-filter-trigger, [data-drawer-close]\")\n : heading;\n target?.focus({ preventScroll: true });\n }\n\n /**\n * Run a re-render, and if it removed or hid the focused element,\n * move focus somewhere sensible instead of <body>. Focus is only\n * moved when the re-render lost it, never taken from elsewhere.\n */\n function keepingFocus(render: () => void) {\n const before = document.activeElement;\n render();\n if (!(before instanceof HTMLElement) || before === document.body) return;\n const now = document.activeElement;\n const lost =\n !before.isConnected ||\n Boolean(before.closest(\".hidden, [hidden]\")) ||\n now === null ||\n now === document.body;\n if (lost && (now === null || now === document.body || now === before)) focusFallback(before);\n }\n\n const hrefForResultPage = (target: number) =>\n isClientView()\n ? hrefForFilters({ ...filters, page: target }, pathPrefix)\n : pagePathHref(pathPrefix, target);\n\n /** Move the page's cards into the list, in result order. */\n function renderList(visible: { slug: string }[]) {\n const next: HTMLElement[] = [];\n let missing = false;\n for (const record of visible) {\n const node = nodes.get(record.slug);\n if (node) next.push(node);\n else missing = true;\n }\n list.replaceChildren(...next);\n // A record whose card has not arrived yet: render what we have\n // and finish the moment the card source lands. Only while the\n // fetch is still outstanding — once it has settled, a missing\n // card is missing, and retrying would spin.\n if (missing && !cardsSettled) loadAllCards().then(() => applyClientFilters());\n }\n\n function applyClientFilters() {\n const filtered = applySort(filterRecords(items, filters), sort);\n const pageSize = pageSizeFor(filtered.length);\n const pageCount = totalPages(filtered.length, pageSize);\n const page = Math.min(Math.max(1, currentPage()), pageCount);\n renderList(filtered.slice((page - 1) * pageSize, page * pageSize));\n\n const count = document.querySelector(\"#results-count\");\n const pageLabel = document.querySelector(\"#results-page\");\n const empty = document.querySelector(\"#empty-state\");\n if (count) count.textContent = countLabel(filtered.length, singular, plural);\n if (drawerResults) drawerResults.textContent = showResultsLabel(filtered.length, singular, plural);\n if (announceNext) {\n announceNext = false;\n announce(resultsAnnouncement(filtered.length, singular, plural));\n }\n // The zero-results reset keeps the chosen sort, like \"Clear all\".\n const emptyReset = document.querySelector(\"[data-empty-reset]\");\n if (emptyReset instanceof HTMLAnchorElement) {\n emptyReset.href = hrefForClearedFilters(filters, pathPrefix);\n }\n const sortLabel = document.querySelector(\"#results-sort\");\n if (sortLabel) sortLabel.textContent = ` · sorted by ${sortDisplay(sort)}`;\n if (pageLabel) pageLabel.textContent = pageCount > 1 ? ` · page ${page} of ${pageCount}` : \"\";\n if (empty) empty.classList.toggle(\"hidden\", filtered.length > 0);\n\n // Rebuild the pagination controls, mirroring the server-rendered\n // `Pagination.astro` (Previous/Next + windowed page list via the\n // shared `paginationPageList`) so client filtering never degrades\n // the affordances of the initial render.\n const pagination = document.querySelector(\"#results-pagination\");\n if (pagination) {\n pagination.innerHTML = \"\";\n if (pageCount > 1) {\n const linkClass = buttonClass(\"secondary\", \"sm\", PAGINATION_EXTRA);\n const nav = document.createElement(\"nav\");\n nav.className = \"flex flex-wrap items-center justify-center gap-1.5\";\n nav.setAttribute(\"aria-label\", \"Pagination\");\n const control = (label: string, target: number | null, rel?: string) => {\n if (target === null) {\n const span = document.createElement(\"span\");\n span.className = `${linkClass} ${PAGINATION_DISABLED}`;\n span.textContent = label;\n return span;\n }\n const link = document.createElement(\"a\");\n link.href = hrefForResultPage(target);\n link.textContent = label;\n link.className = linkClass;\n if (rel) link.rel = rel;\n return link;\n };\n nav.append(control(\"Previous\", page > 1 ? page - 1 : null, \"prev\"));\n for (const entry of paginationPageList(page, pageCount)) {\n if (entry === \"ellipsis\") {\n const dots = document.createElement(\"span\");\n dots.className = \"px-1 text-2xs text-ink-400\";\n dots.setAttribute(\"aria-hidden\", \"true\");\n dots.textContent = \"...\";\n nav.append(dots);\n continue;\n }\n const link = control(String(entry), entry);\n link.setAttribute(\"aria-label\", `Page ${entry}`);\n if (entry === page) {\n link.setAttribute(\"aria-current\", \"page\");\n link.className = buttonClass(\"selected\", \"sm\", PAGINATION_EXTRA);\n }\n nav.append(link);\n }\n nav.append(control(\"Next\", page < pageCount ? page + 1 : null, \"next\"));\n pagination.append(nav);\n }\n }\n }\n\n const searchInput = document.querySelector(\"#search-input\");\n const searchClear = document.querySelector(\"[data-search-clear]\");\n if (searchInput instanceof HTMLInputElement) searchInput.value = filters.q || \"\";\n document.querySelectorAll('select[name=\"sort\"]').forEach((select) => {\n if (select instanceof HTMLSelectElement) select.value = sort;\n });\n\n const filterKeys = DIRECTORY_FILTER_KEYS;\n const filterLabels = DIRECTORY_FILTER_LABELS;\n const taxonomyKinds = DIRECTORY_TAXONOMY_KINDS;\n const taxonomyName = (groupKey: DirectoryFilterGroupKey, value: string) =>\n (taxonomy[taxonomyKinds[groupKey]] || []).find(\n (entry: { id: string; name: string }) => entry.id === value,\n )?.name ?? value;\n\n /**\n * Chip labels and remove hrefs come from core — one definition.\n * The same chips render in every `[data-active-filters]` row:\n * above the results, and inside the mobile filter sheet.\n */\n function renderChips() {\n const chips = activeFilterChips(filters, { taxonomy, pathPrefix });\n document.querySelectorAll<HTMLElement>(\"[data-active-filters]\").forEach((row) => {\n // Removing a chip removes the link that had focus. Remember\n // its position and give focus to whatever takes its place.\n const focused = document.activeElement;\n const focusIndex =\n focused instanceof HTMLAnchorElement && row.contains(focused)\n ? [...row.querySelectorAll(\"a\")].indexOf(focused)\n : -1;\n\n row.innerHTML = \"\";\n for (const chip of chips) {\n const link = document.createElement(\"a\");\n link.href = chip.href;\n // The whole anchor is the remove control; the visible label\n // announces the filter value, and the aria-label spells out\n // the action for assistive tech.\n link.setAttribute(\"aria-label\", `Remove filter: ${chip.label}`);\n link.className = chipClass();\n link.append(document.createTextNode(`${chip.label} `));\n const close = document.createElement(\"span\");\n close.setAttribute(\"aria-hidden\", \"true\");\n close.textContent = \"×\";\n link.append(close);\n row.append(link);\n }\n if (chips.length && !row.hasAttribute(\"data-without-clear\")) {\n const clear = document.createElement(\"a\");\n clear.href = hrefForClearedFilters(filters, pathPrefix);\n clear.className =\n \"text-2xs font-medium text-ink-500 underline decoration-border underline-offset-2 hover:text-ink-900 dark:hover:text-ink-100\";\n clear.setAttribute(\"aria-label\", \"Clear all active filters\");\n clear.textContent = \"Clear all\";\n row.append(clear);\n }\n row.classList.toggle(\"hidden\", chips.length === 0);\n\n if (focusIndex >= 0) {\n const links = row.querySelectorAll(\"a\");\n const next = focusIndexAfterRender(focusIndex, links.length);\n if (next >= 0) links[next]?.focus({ preventScroll: true });\n else focusFallback(row);\n }\n });\n\n // Mobile filter-drawer badge + its clear-all mirror the chips.\n const drawerCount = document.querySelector(\"[data-drawer-count]\");\n if (drawerCount) {\n drawerCount.textContent = String(chips.length);\n drawerCount.classList.toggle(\"hidden\", chips.length === 0);\n }\n const drawerClear = document.querySelector(\"[data-drawer-clear]\");\n if (drawerClear instanceof HTMLAnchorElement) {\n drawerClear.href = hrefForClearedFilters(filters, pathPrefix);\n drawerClear.classList.toggle(\"hidden\", chips.length === 0);\n }\n }\n\n function renderFilterTriggers() {\n const values = (key: string) => params.getAll(key).filter(Boolean);\n document.querySelectorAll(\".grove-filter\").forEach((group) => {\n if (!(group instanceof HTMLElement)) return;\n const groupKey = group.dataset.filterGroupKey;\n if (!groupKey || !isDirectoryFilterGroupKey(groupKey)) return;\n const selected = values(filterKeys[groupKey]);\n group.querySelectorAll(\".grove-filter-input\").forEach((input) => {\n if (input instanceof HTMLInputElement) {\n input.checked = selected.includes(input.dataset.filterValue || \"\");\n }\n });\n const triggerButton = group.querySelector(\".grove-filter-trigger\");\n const trigger = triggerButton?.querySelector(\"span\");\n const label = filterLabels[groupKey];\n if (trigger) {\n trigger.textContent = selected.length\n ? `${label}: ${\n selected.length === 1\n ? taxonomyName(groupKey, selected[0] ?? \"\")\n : `${selected.length} selected`\n }`\n : `${label}: Any`;\n }\n if (triggerButton) {\n // Same builder the server render used — the class string is\n // reassigned wholesale so the two can never drift.\n triggerButton.className = filterTriggerClass(selected.length > 0);\n }\n group.querySelector(\".grove-filter-clear\")?.classList.toggle(\"hidden\", selected.length === 0);\n });\n }\n\n // Facet counts were rendered at build time from the UNFILTERED\n // record set (the route is prerendered, so the server never sees\n // the live query string). Recompute intersection counts against\n // the current filters and patch each count span in place —\n // never re-render the option lists, which would destroy\n // checkbox, focus, and scroll state.\n function renderFacetCounts() {\n const liveFacets: Record<string, { value: string; count: number }[]> = buildFacets(items, {\n filters,\n curatedTagIds: (taxonomy.topics || []).map((topic: { id: string }) => topic.id),\n });\n document.querySelectorAll(\"[data-facet-count]\").forEach((span) => {\n if (!(span instanceof HTMLElement)) return;\n const options = liveFacets[span.dataset.facet ?? \"\"] ?? [];\n const count = options.find((option) => option.value === span.dataset.value)?.count ?? 0;\n span.textContent = String(count);\n const row = span.closest(\"label\");\n const input = row?.querySelector(\".grove-filter-input\");\n const checked = input instanceof HTMLInputElement && input.checked;\n // A zero-count option can't narrow anything — dim and disable\n // it unless it's the currently selected value (which must stay\n // interactive so the user can un-select it).\n // The focused option is never disabled under the user; that\n // would drop keyboard focus to <body>.\n const inert = count === 0 && !checked && input !== document.activeElement;\n row?.classList.toggle(\"opacity-45\", inert);\n if (input instanceof HTMLInputElement) input.disabled = inert;\n });\n }\n\n function renderAll() {\n renderChips();\n renderFilterTriggers();\n if (searchClear instanceof HTMLElement) searchClear.hidden = !(filters.q || \"\").length;\n\n if (recordsSettled) {\n renderFacetCounts();\n applyClientFilters();\n setPending(false);\n return;\n }\n // Nothing to filter with yet. A plain view of this page is\n // already correct as the server rendered it; anything the URL\n // asks for beyond that — a filter, a search, a sort — waits for\n // the index and the cards, and says so while it does.\n if (!isClientView()) return;\n setPending(true);\n loadAll().then(() => {\n setPending(false);\n keepingFocus(renderAll);\n });\n }\n\n /**\n * Adopt a URL without a navigation, then re-render from it.\n *\n * A URL with no query is a prerendered document — clearing the\n * last filter lands on `/{slug}/`, which on page 2+ is a\n * *different* document than the one on screen. Adopting it there\n * would leave records 21–40 rendered under the page-1 URL, so\n * that case navigates for real.\n */\n function adopt(url: string, mode: \"push\" | \"replace\") {\n const next = new URL(url, location.origin);\n if (!canAdoptInPlace(next, location.pathname, routePage || 1)) {\n location.assign(next.toString());\n return;\n }\n const state = { grove: true, scrollY: window.scrollY };\n // Re-selecting the URL already on screen (the header's Browse\n // link on an unfiltered page 1) must not add a Back step.\n if (mode === \"push\" && next.href !== location.href) history.pushState(state, \"\", next);\n else history.replaceState(state, \"\", next);\n params = new URLSearchParams(next.search);\n filters = readFilters(params);\n sort = effectiveSort(filters);\n // A chip, \"Clear all\" or the zero-results reset can drop the\n // query. Keep the box in step, but never rewrite it while the\n // user is typing in it.\n if (searchInput instanceof HTMLInputElement && document.activeElement !== searchInput) {\n searchInput.value = filters.q || \"\";\n }\n announceNext = true;\n keepingFocus(renderAll);\n }\n\n /** The current URL as the history session compares it. */\n const here = () => `${location.pathname}${location.search}`;\n\n // One history entry per filter session. A popover or the drawer\n // opening starts a session. While it is open, changes replace the\n // current entry. When the last surface closes, the starting URL is\n // put back on this entry and the final URL is pushed once.\n const session = new FilterHistorySession();\n document.addEventListener(\"grove:filter-surface\", (event) => {\n const detail = (event as CustomEvent<{ surface: string; open: boolean }>).detail;\n if (!detail?.surface) return;\n if (detail.open) {\n session.open(detail.surface, { url: here(), scrollY: window.scrollY });\n return;\n }\n const commit = session.close(detail.surface, here());\n if (!commit) return;\n history.replaceState({ grove: true, scrollY: commit.start.scrollY }, \"\", commit.start.url);\n history.pushState({ grove: true, scrollY: window.scrollY }, \"\", commit.end);\n });\n\n // Search filters as you type. `replaceState` keeps a search\n // session out of the history stack — Back should return to the\n // previous result set, not to the previous keystroke.\n let debounce = 0;\n searchInput?.addEventListener(\"input\", () => {\n window.clearTimeout(debounce);\n debounce = window.setTimeout(() => {\n const query = searchInput instanceof HTMLInputElement ? searchInput.value.trim() : \"\";\n adopt(hrefForFilters({ ...filters, q: query || undefined, page: 1 }, pathPrefix), \"replace\");\n // Only reclaim focus when the re-render dropped it. If the\n // user has already moved on (tabbed to a filter) focus stays\n // where they put it.\n if (searchInput instanceof HTMLInputElement && document.activeElement === document.body) {\n searchInput.focus();\n }\n }, 150);\n });\n searchClear?.addEventListener(\"click\", () => {\n if (searchInput instanceof HTMLInputElement) {\n searchInput.value = \"\";\n searchInput.focus();\n }\n adopt(hrefForFilters({ ...filters, q: undefined, page: 1 }, pathPrefix), \"replace\");\n });\n document.querySelector(\"#search-form\")?.addEventListener(\"submit\", (event) => {\n // Enter already has its answer on screen; submitting would only\n // reload the same state.\n event.preventDefault();\n });\n\n // RefinePanel asks before it navigates; cancelling means \"this\n // page can apply the URL in place\".\n document.addEventListener(\"grove:navigate\", (event) => {\n const url = (event as CustomEvent<{ url: string }>).detail?.url;\n if (!url) return;\n event.preventDefault();\n // Inside an open popover or drawer, replace; the session pushes\n // once on close. Outside one (the sort select), push.\n adopt(url, session.modeForChange());\n });\n\n // Filtered navigation is a real step: Back returns to the\n // previous result set and its scroll position.\n //\n // Links that carry a query are adopted. A link to the bare list\n // (`/{slug}/` from \"Clear all\", the last chip, or the \"1\"\n // pagination link) is adopted only from page 1 of that list,\n // where it is the document already on screen. That keeps focus and\n // an open filter drawer in place. From `/{slug}/page/2/` it is a\n // different prerendered document and must actually navigate.\n // Swallowing it there left page 2's records rendered under the\n // page-1 URL. Hash links (the skip link) are never ours.\n document.addEventListener(\"click\", (event) => {\n const link = (event.target as HTMLElement | null)?.closest(\"a\");\n if (!(link instanceof HTMLAnchorElement)) return;\n if (event.defaultPrevented || event.metaKey || event.ctrlKey || event.shiftKey) return;\n if (link.target === \"_blank\" || !link.href.startsWith(location.origin)) return;\n const url = new URL(link.href);\n if (url.hash) return;\n const isListUrl = url.pathname === `${pathPrefix}/` || url.pathname === pathPrefix;\n if (!isListUrl || !canAdoptInPlace(url, location.pathname, routePage || 1)) return;\n event.preventDefault();\n // A chip removed inside the open drawer is part of that filter\n // session. It replaces, and the page does not jump under the sheet.\n if (session.active) {\n adopt(url.toString(), \"replace\");\n return;\n }\n history.replaceState({ grove: true, scrollY: window.scrollY }, \"\");\n adopt(url.toString(), \"push\");\n window.scrollTo({ top: 0, behavior: \"instant\" as ScrollBehavior });\n });\n\n window.addEventListener(\"popstate\", (event) => {\n params = new URLSearchParams(location.search);\n filters = readFilters(params);\n sort = effectiveSort(filters);\n if (searchInput instanceof HTMLInputElement) searchInput.value = filters.q || \"\";\n document.querySelectorAll('select[name=\"sort\"]').forEach((select) => {\n if (select instanceof HTMLSelectElement) select.value = sort;\n });\n // Back/Forward with a popover or the drawer still open: this\n // entry becomes where that session started.\n session.rebase({ url: here(), scrollY: window.scrollY });\n announceNext = true;\n keepingFocus(renderAll);\n const state = event.state as { scrollY?: number } | null;\n if (typeof state?.scrollY === \"number\") {\n window.scrollTo({ top: state.scrollY, behavior: \"instant\" as ScrollBehavior });\n }\n });\n\n renderAll();\n })();\n</script>\n",
45
51
  "type": "registry:component",
46
52
  "target": "~/src/components/grove/directory-index-client.astro"
47
53
  },
@@ -83,14 +89,14 @@
83
89
  },
84
90
  {
85
91
  "path": "default/lib/live-filters.ts",
86
- "content": "/**\n * Live-filter logic for the browse page. These are the pieces of\n * behaviour that do not need a DOM: URL building, the history-session\n * decision, the labels the page speaks, a debounce and the focus\n * fallback index.\n *\n * They live here, not inline in the `.astro` scripts, so they can be\n * unit-tested. RefinePanel, FilterDrawer and DirectoryIndexClient\n * import them.\n */\n\n/**\n * URL for one facet group's new selection. Every other parameter in\n * `search` is kept, so the query, other groups, sort and lens survive.\n * The group's key is rewritten and `page` is dropped, because a\n * different result set starts on page 1.\n *\n * This is the same URL shape the page has always used: a repeated key\n * per value. Existing links keep working.\n */\nexport function hrefForGroupSelection(\n search: string,\n pathPrefix: string,\n paramKey: string,\n values: readonly string[],\n): string {\n const params = new URLSearchParams(search);\n params.delete(paramKey);\n params.delete('page');\n for (const value of values) if (value) params.append(paramKey, value);\n const query = params.toString();\n return query ? `${pathPrefix}?${query}` : pathPrefix;\n}\n\n/**\n * Whether the browse page can show `target` in place, or must really\n * navigate to it.\n *\n * A URL with a query is always a client view of the list, so it can\n * be shown in place. A URL with no query is a prerendered document.\n * On page 1 of the same list that is the document already on screen,\n * so clearing the last filter can still happen in place, keeping focus\n * and an open drawer. From `/{slug}/page/2/`, or for a different path,\n * it is a different document and has to load for real. Otherwise page\n * 2's records would sit under the page-1 URL.\n */\nexport function canAdoptInPlace(\n target: { pathname: string; search: string },\n currentPathname: string,\n routePage: number,\n): boolean {\n if (target.search) return true;\n const strip = (path: string) => path.replace(/\\/$/, '');\n return strip(target.pathname) === strip(currentPathname) && routePage <= 1;\n}\n\n/** What a filter change does to the history stack. */\nexport type HistoryMode = 'push' | 'replace';\n\n/** Where the history stood when a filter session opened. */\nexport interface HistorySnapshot {\n url: string;\n scrollY: number;\n}\n\n/**\n * The history entries a closing session has to write: put `start` back\n * on the current entry, then push `end`.\n */\nexport interface HistoryCommit {\n start: HistorySnapshot;\n end: string;\n}\n\n/**\n * One \"filter session\": the time a filter surface (a facet popover or\n * the mobile drawer) is open.\n *\n * While a session is open, each change replaces the current history\n * entry, so ticking five checkboxes does not leave five Back steps.\n * When the last surface closes and the URL has changed, the caller\n * restores the starting URL on the current entry and pushes the final\n * one. That is one pushState per session, and Back goes to the result\n * set from before the session.\n *\n * Surfaces nest: a popover can open inside the drawer. The session\n * only ends when every surface has closed.\n */\nexport class FilterHistorySession {\n #open = new Set<string>();\n #start: HistorySnapshot | null = null;\n\n /** True while at least one filter surface is open. */\n get active(): boolean {\n return this.#open.size > 0;\n }\n\n /** A surface opened. The first one records where history stood. */\n open(surface: string, snapshot: HistorySnapshot): void {\n if (this.#open.size === 0) this.#start = snapshot;\n this.#open.add(surface);\n }\n\n /** How a filter change made now should write to history. */\n modeForChange(): HistoryMode {\n return this.active ? 'replace' : 'push';\n }\n\n /**\n * A surface closed. Returns the commit to write when this ended the\n * session and the URL changed during it. Otherwise returns `null`:\n * another surface is still open, the surface was not open, or\n * nothing changed.\n */\n close(surface: string, currentUrl: string): HistoryCommit | null {\n if (!this.#open.delete(surface) || this.#open.size > 0) return null;\n const start = this.#start;\n this.#start = null;\n if (!start || sameUrl(start.url, currentUrl)) return null;\n return { start, end: currentUrl };\n }\n\n /**\n * Back/Forward moved to another entry while a surface was open. The\n * new entry becomes the session's starting point: later changes\n * replace it, and closing pushes one entry after it. When no session\n * is open this does nothing.\n */\n rebase(snapshot: HistorySnapshot): void {\n if (this.active) this.#start = snapshot;\n }\n}\n\n/** Compare two same-origin URLs, ignoring a trailing slash on the path. */\nfunction sameUrl(a: string, b: string): boolean {\n const left = new URL(a, 'https://grove.invalid');\n const right = new URL(b, 'https://grove.invalid');\n const path = (url: URL) => url.pathname.replace(/\\/$/, '');\n return path(left) === path(right) && left.search === right.search;\n}\n\n/** `1 app`, `12 apps`. */\nexport function countLabel(count: number, singular: string, plural: string): string {\n return `${count} ${count === 1 ? singular : plural}`;\n}\n\n/**\n * What the polite live region says after the results change. It is a\n * whole sentence because a screen reader hears it without the visible\n * heading around it.\n */\nexport function resultsAnnouncement(count: number, singular: string, plural: string): string {\n if (count === 0) return `No ${plural} match these filters.`;\n return `${countLabel(count, singular, plural)} found.`;\n}\n\n/**\n * Label for the mobile drawer's results button. The button shows the\n * results. It does not apply anything, because every change has\n * already applied.\n */\nexport function showResultsLabel(\n count: number,\n singular: string,\n plural: string,\n pending = false,\n): string {\n if (pending) return 'Updating results…';\n if (count === 0) return `No ${plural} match`;\n return `Show ${countLabel(count, singular, plural)}`;\n}\n\n/** A trailing-edge debounce that can also be cancelled. */\nexport interface Debounced<Args extends unknown[]> {\n (...args: Args): void;\n cancel(): void;\n}\n\nexport function debounce<Args extends unknown[]>(\n fn: (...args: Args) => void,\n wait: number,\n): Debounced<Args> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const debounced = (...args: Args) => {\n if (timer !== undefined) clearTimeout(timer);\n timer = setTimeout(() => {\n timer = undefined;\n fn(...args);\n }, wait);\n };\n debounced.cancel = () => {\n if (timer !== undefined) clearTimeout(timer);\n timer = undefined;\n };\n return debounced;\n}\n\n/**\n * When a list re-renders under a focused item (for example, removing\n * the focused chip), this picks which item gets focus next. The answer\n * is the item that took the old one's place, or the new last item.\n * Returns `-1` when the list is empty and the caller has to fall back\n * to something else.\n */\nexport function focusIndexAfterRender(previousIndex: number, length: number): number {\n if (length <= 0) return -1;\n return Math.min(Math.max(previousIndex, 0), length - 1);\n}\n",
92
+ "content": "/**\n * Live-filter logic for the browse page. These are the pieces of\n * behaviour that do not need a DOM: URL building, the history-session\n * decision, the labels the page speaks, a debounce and the focus\n * fallback index.\n *\n * They live here, not inline in the `.astro` scripts, so they can be\n * unit-tested. RefinePanel, FilterDrawer and DirectoryIndexClient\n * import them.\n */\n\n/** The facet groups a scope can fix (core's `DirectoryFilterGroupKey`). */\nexport type ScopeGroup = 'stacks' | 'platforms' | 'categories' | 'tags' | 'licenses';\n\n/**\n * A fixed slice of the directory that a page browses inside, keyed by\n * facet group: `{ stacks: ['flutter'] }` on `/stacks/flutter/`,\n * `{ categories: ['productivity'] }` on `/categories/productivity/`.\n *\n * A scope is not a filter the visitor chose. It is merged into every\n * query, but it never shows as a chip or a facet, and it never goes in\n * the URL: the page's own path already says it. So clearing filters,\n * the zero-results reset and Back/Forward can never drop it.\n */\nexport type DirectoryScope = Partial<Record<ScopeGroup, readonly string[]>>;\n\n/** The facet groups a scope fixes. Groups with no values do not count. */\nexport function scopedGroups(scope: DirectoryScope | null | undefined): ScopeGroup[] {\n if (!scope) return [];\n return (Object.keys(scope) as ScopeGroup[]).filter((key) => (scope[key]?.length ?? 0) > 0);\n}\n\n/**\n * Drop the scoped groups from a filter state read off the URL. On\n * `/stacks/flutter/?stack=react` the `stack` parameter is ignored:\n * the page is Flutter, whatever the query says.\n */\nexport function withoutScope<F extends Partial<Record<ScopeGroup, unknown>>>(\n filters: F,\n scope: DirectoryScope | null | undefined,\n): F {\n const groups = scopedGroups(scope);\n if (groups.length === 0) return filters;\n const next = { ...filters };\n for (const group of groups) delete next[group];\n return next;\n}\n\n/**\n * The query string with the scoped groups' parameters removed, or\n * `null` when there was nothing to remove. The page uses it to tidy a\n * hand-written URL like `/stacks/flutter/?stack=react&platform=ios`.\n *\n * `paramKeys` maps a group to its URL key. Callers pass core's\n * `DIRECTORY_FILTER_KEYS`, so this file needs no package import.\n */\nexport function searchWithoutScope(\n search: string,\n scope: DirectoryScope | null | undefined,\n paramKeys: Readonly<Record<ScopeGroup, string>>,\n): string | null {\n const groups = scopedGroups(scope);\n const params = new URLSearchParams(search);\n let changed = false;\n for (const group of groups) {\n const key = paramKeys[group];\n if (params.has(key)) {\n params.delete(key);\n changed = true;\n }\n }\n if (!changed) return null;\n const query = params.toString();\n return query ? `?${query}` : '';\n}\n\n/**\n * URL for one facet group's new selection. Every other parameter in\n * `search` is kept, so the query, other groups, sort and lens survive.\n * The group's key is rewritten and `page` is dropped, because a\n * different result set starts on page 1.\n *\n * This is the same URL shape the page has always used: a repeated key\n * per value. Existing links keep working.\n */\nexport function hrefForGroupSelection(\n search: string,\n pathPrefix: string,\n paramKey: string,\n values: readonly string[],\n): string {\n const params = new URLSearchParams(search);\n params.delete(paramKey);\n params.delete('page');\n for (const value of values) if (value) params.append(paramKey, value);\n const query = params.toString();\n return query ? `${pathPrefix}?${query}` : pathPrefix;\n}\n\n/**\n * Whether the browse page can show `target` in place, or must really\n * navigate to it.\n *\n * A URL with a query is always a client view of the list, so it can\n * be shown in place. A URL with no query is a prerendered document.\n * On page 1 of the same list that is the document already on screen,\n * so clearing the last filter can still happen in place, keeping focus\n * and an open drawer. From `/{slug}/page/2/`, or for a different path,\n * it is a different document and has to load for real. Otherwise page\n * 2's records would sit under the page-1 URL.\n */\nexport function canAdoptInPlace(\n target: { pathname: string; search: string },\n currentPathname: string,\n routePage: number,\n): boolean {\n if (target.search) return true;\n const strip = (path: string) => path.replace(/\\/$/, '');\n return strip(target.pathname) === strip(currentPathname) && routePage <= 1;\n}\n\n/** What a filter change does to the history stack. */\nexport type HistoryMode = 'push' | 'replace';\n\n/** Where the history stood when a filter session opened. */\nexport interface HistorySnapshot {\n url: string;\n scrollY: number;\n}\n\n/**\n * The history entries a closing session has to write: put `start` back\n * on the current entry, then push `end`.\n */\nexport interface HistoryCommit {\n start: HistorySnapshot;\n end: string;\n}\n\n/**\n * One \"filter session\": the time a filter surface (a facet popover or\n * the mobile drawer) is open.\n *\n * While a session is open, each change replaces the current history\n * entry, so ticking five checkboxes does not leave five Back steps.\n * When the last surface closes and the URL has changed, the caller\n * restores the starting URL on the current entry and pushes the final\n * one. That is one pushState per session, and Back goes to the result\n * set from before the session.\n *\n * Surfaces nest: a popover can open inside the drawer. The session\n * only ends when every surface has closed.\n */\nexport class FilterHistorySession {\n #open = new Set<string>();\n #start: HistorySnapshot | null = null;\n\n /** True while at least one filter surface is open. */\n get active(): boolean {\n return this.#open.size > 0;\n }\n\n /** A surface opened. The first one records where history stood. */\n open(surface: string, snapshot: HistorySnapshot): void {\n if (this.#open.size === 0) this.#start = snapshot;\n this.#open.add(surface);\n }\n\n /** How a filter change made now should write to history. */\n modeForChange(): HistoryMode {\n return this.active ? 'replace' : 'push';\n }\n\n /**\n * A surface closed. Returns the commit to write when this ended the\n * session and the URL changed during it. Otherwise returns `null`:\n * another surface is still open, the surface was not open, or\n * nothing changed.\n */\n close(surface: string, currentUrl: string): HistoryCommit | null {\n if (!this.#open.delete(surface) || this.#open.size > 0) return null;\n const start = this.#start;\n this.#start = null;\n if (!start || sameUrl(start.url, currentUrl)) return null;\n return { start, end: currentUrl };\n }\n\n /**\n * Back/Forward moved to another entry while a surface was open. The\n * new entry becomes the session's starting point: later changes\n * replace it, and closing pushes one entry after it. When no session\n * is open this does nothing.\n */\n rebase(snapshot: HistorySnapshot): void {\n if (this.active) this.#start = snapshot;\n }\n}\n\n/** Compare two same-origin URLs, ignoring a trailing slash on the path. */\nfunction sameUrl(a: string, b: string): boolean {\n const left = new URL(a, 'https://grove.invalid');\n const right = new URL(b, 'https://grove.invalid');\n const path = (url: URL) => url.pathname.replace(/\\/$/, '');\n return path(left) === path(right) && left.search === right.search;\n}\n\n/** `1 app`, `12 apps`. */\nexport function countLabel(count: number, singular: string, plural: string): string {\n return `${count} ${count === 1 ? singular : plural}`;\n}\n\n/**\n * What the polite live region says after the results change. It is a\n * whole sentence because a screen reader hears it without the visible\n * heading around it.\n */\nexport function resultsAnnouncement(count: number, singular: string, plural: string): string {\n if (count === 0) return `No ${plural} match these filters.`;\n return `${countLabel(count, singular, plural)} found.`;\n}\n\n/**\n * Label for the mobile drawer's results button. The button shows the\n * results. It does not apply anything, because every change has\n * already applied.\n */\nexport function showResultsLabel(\n count: number,\n singular: string,\n plural: string,\n pending = false,\n): string {\n if (pending) return 'Updating results…';\n if (count === 0) return `No ${plural} match`;\n return `Show ${countLabel(count, singular, plural)}`;\n}\n\n/** A trailing-edge debounce that can also be cancelled. */\nexport interface Debounced<Args extends unknown[]> {\n (...args: Args): void;\n cancel(): void;\n}\n\nexport function debounce<Args extends unknown[]>(\n fn: (...args: Args) => void,\n wait: number,\n): Debounced<Args> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const debounced = (...args: Args) => {\n if (timer !== undefined) clearTimeout(timer);\n timer = setTimeout(() => {\n timer = undefined;\n fn(...args);\n }, wait);\n };\n debounced.cancel = () => {\n if (timer !== undefined) clearTimeout(timer);\n timer = undefined;\n };\n return debounced;\n}\n\n/**\n * When a list re-renders under a focused item (for example, removing\n * the focused chip), this picks which item gets focus next. The answer\n * is the item that took the old one's place, or the new last item.\n * Returns `-1` when the list is empty and the caller has to fall back\n * to something else.\n */\nexport function focusIndexAfterRender(previousIndex: number, length: number): number {\n if (length <= 0) return -1;\n return Math.min(Math.max(previousIndex, 0), length - 1);\n}\n",
87
93
  "type": "registry:file",
88
94
  "target": "~/src/lib/live-filters.ts"
89
95
  }
90
96
  ],
91
97
  "meta": {
92
98
  "version": "1.3.0",
93
- "requiresGrove": "0.15.0"
99
+ "requiresGrove": "0.17.0"
94
100
  },
95
101
  "type": "registry:block"
96
102
  }
@@ -54,7 +54,7 @@
54
54
  ],
55
55
  "meta": {
56
56
  "version": "1.3.0",
57
- "requiresGrove": "0.15.0"
57
+ "requiresGrove": "0.17.0"
58
58
  },
59
59
  "type": "registry:block"
60
60
  }
@@ -17,7 +17,7 @@
17
17
  ],
18
18
  "meta": {
19
19
  "version": "1.3.0",
20
- "requiresGrove": "0.15.0"
20
+ "requiresGrove": "0.17.0"
21
21
  },
22
22
  "type": "registry:block"
23
23
  }