@grove-dev/cli 1.2.0 → 1.3.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.
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@grove-dev/cli",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
4
4
  "type": "module",
5
5
  "description": "Grove CLI — scaffolds Grove-powered spaces and orchestrates @grove-dev/core commands.",
6
6
  "license": "MIT",
@@ -52,7 +52,7 @@
52
52
  "@grove-dev/core": "workspace:*",
53
53
  "chrome-launcher": "^1.2.1",
54
54
  "commander": "^15.0.0",
55
- "lighthouse": "^12.8.2",
55
+ "lighthouse": "^13.5.0",
56
56
  "typescript": "^5.9.3",
57
57
  "yaml": "^2.6.0"
58
58
  },
package/dist/r/about.json CHANGED
@@ -17,7 +17,7 @@
17
17
  ],
18
18
  "meta": {
19
19
  "version": "1.6.0",
20
- "requiresGrove": "1.2.0"
20
+ "requiresGrove": "1.3.0"
21
21
  },
22
22
  "type": "registry:block"
23
23
  }
@@ -35,7 +35,7 @@
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) 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",
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 allLabel={`All ${itemLabelPlural()}`}\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
  },
@@ -47,7 +47,7 @@
47
47
  },
48
48
  {
49
49
  "path": "default/components/grove/directory-index-client.astro",
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",
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, LensId } 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 hrefForLens,\n isLensActive,\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 lensTabClass,\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 /**\n * The lens tabs are prerendered for the bare URL, so \"All\" is the\n * one marked current in the HTML whatever the query says. Re-mark\n * them from the live params, and carry the current filters into\n * each tab's link the way the server render would.\n */\n function renderLensTabs() {\n document.querySelectorAll<HTMLAnchorElement>(\".grove-lens-tabs a[data-lens-id]\").forEach((tab) => {\n // Rendered from the LENSES registry by SmartLensTabs.\n const id = (tab.dataset.lensId ?? \"all\") as LensId;\n const active = isLensActive(id, params);\n tab.href = hrefForLens(id, params, pathPrefix);\n tab.className = lensTabClass(active);\n if (active) tab.setAttribute(\"aria-current\", \"page\");\n else tab.removeAttribute(\"aria-current\");\n });\n }\n\n function renderAll() {\n renderLensTabs();\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",
51
51
  "type": "registry:component",
52
52
  "target": "~/src/components/grove/directory-index-client.astro"
53
53
  },
@@ -96,7 +96,7 @@
96
96
  ],
97
97
  "meta": {
98
98
  "version": "1.6.0",
99
- "requiresGrove": "1.2.0"
99
+ "requiresGrove": "1.3.0"
100
100
  },
101
101
  "type": "registry:block"
102
102
  }
@@ -84,7 +84,7 @@
84
84
  ],
85
85
  "meta": {
86
86
  "version": "1.6.0",
87
- "requiresGrove": "1.2.0"
87
+ "requiresGrove": "1.3.0"
88
88
  },
89
89
  "type": "registry:block"
90
90
  }
@@ -17,7 +17,7 @@
17
17
  ],
18
18
  "meta": {
19
19
  "version": "1.6.0",
20
- "requiresGrove": "1.2.0"
20
+ "requiresGrove": "1.3.0"
21
21
  },
22
22
  "type": "registry:block"
23
23
  }
@@ -342,7 +342,7 @@
342
342
  },
343
343
  {
344
344
  "path": "default/components/grove/directory-browse.astro",
345
- "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",
345
+ "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 allLabel={`All ${itemLabelPlural()}`}\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",
346
346
  "type": "registry:component",
347
347
  "target": "~/src/components/grove/directory-browse.astro"
348
348
  },
@@ -354,7 +354,7 @@
354
354
  },
355
355
  {
356
356
  "path": "default/components/grove/directory-index-client.astro",
357
- "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",
357
+ "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, LensId } 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 hrefForLens,\n isLensActive,\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 lensTabClass,\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 /**\n * The lens tabs are prerendered for the bare URL, so \"All\" is the\n * one marked current in the HTML whatever the query says. Re-mark\n * them from the live params, and carry the current filters into\n * each tab's link the way the server render would.\n */\n function renderLensTabs() {\n document.querySelectorAll<HTMLAnchorElement>(\".grove-lens-tabs a[data-lens-id]\").forEach((tab) => {\n // Rendered from the LENSES registry by SmartLensTabs.\n const id = (tab.dataset.lensId ?? \"all\") as LensId;\n const active = isLensActive(id, params);\n tab.href = hrefForLens(id, params, pathPrefix);\n tab.className = lensTabClass(active);\n if (active) tab.setAttribute(\"aria-current\", \"page\");\n else tab.removeAttribute(\"aria-current\");\n });\n }\n\n function renderAll() {\n renderLensTabs();\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",
358
358
  "type": "registry:component",
359
359
  "target": "~/src/components/grove/directory-index-client.astro"
360
360
  },
@@ -499,7 +499,7 @@
499
499
  ],
500
500
  "meta": {
501
501
  "version": "1.6.0",
502
- "requiresGrove": "1.2.0"
502
+ "requiresGrove": "1.3.0"
503
503
  },
504
504
  "type": "registry:block"
505
505
  }
package/dist/r/home.json CHANGED
@@ -68,7 +68,7 @@
68
68
  ],
69
69
  "meta": {
70
70
  "version": "1.6.0",
71
- "requiresGrove": "1.2.0"
71
+ "requiresGrove": "1.3.0"
72
72
  },
73
73
  "type": "registry:block"
74
74
  }
@@ -17,7 +17,7 @@
17
17
  ],
18
18
  "meta": {
19
19
  "version": "1.6.0",
20
- "requiresGrove": "1.2.0"
20
+ "requiresGrove": "1.3.0"
21
21
  },
22
22
  "type": "registry:block"
23
23
  }
@@ -43,7 +43,7 @@
43
43
  ],
44
44
  "meta": {
45
45
  "version": "1.6.0",
46
- "requiresGrove": "1.2.0"
46
+ "requiresGrove": "1.3.0"
47
47
  },
48
48
  "type": "registry:block"
49
49
  }
@@ -72,7 +72,7 @@
72
72
  ],
73
73
  "meta": {
74
74
  "version": "1.6.0",
75
- "requiresGrove": "1.2.0"
75
+ "requiresGrove": "1.3.0"
76
76
  },
77
77
  "type": "registry:block"
78
78
  }
@@ -47,7 +47,7 @@
47
47
  ],
48
48
  "meta": {
49
49
  "version": "1.6.0",
50
- "requiresGrove": "1.2.0"
50
+ "requiresGrove": "1.3.0"
51
51
  }
52
52
  },
53
53
  {
@@ -113,7 +113,7 @@
113
113
  ],
114
114
  "meta": {
115
115
  "version": "1.6.0",
116
- "requiresGrove": "1.2.0"
116
+ "requiresGrove": "1.3.0"
117
117
  }
118
118
  },
119
119
  {
@@ -155,7 +155,7 @@
155
155
  ],
156
156
  "meta": {
157
157
  "version": "1.6.0",
158
- "requiresGrove": "1.2.0"
158
+ "requiresGrove": "1.3.0"
159
159
  }
160
160
  },
161
161
  {
@@ -213,7 +213,7 @@
213
213
  ],
214
214
  "meta": {
215
215
  "version": "1.6.0",
216
- "requiresGrove": "1.2.0"
216
+ "requiresGrove": "1.3.0"
217
217
  }
218
218
  },
219
219
  {
@@ -290,7 +290,7 @@
290
290
  ],
291
291
  "meta": {
292
292
  "version": "1.6.0",
293
- "requiresGrove": "1.2.0"
293
+ "requiresGrove": "1.3.0"
294
294
  }
295
295
  },
296
296
  {
@@ -354,7 +354,7 @@
354
354
  ],
355
355
  "meta": {
356
356
  "version": "1.6.0",
357
- "requiresGrove": "1.2.0"
357
+ "requiresGrove": "1.3.0"
358
358
  }
359
359
  },
360
360
  {
@@ -441,7 +441,7 @@
441
441
  ],
442
442
  "meta": {
443
443
  "version": "1.6.0",
444
- "requiresGrove": "1.2.0"
444
+ "requiresGrove": "1.3.0"
445
445
  }
446
446
  },
447
447
  {
@@ -508,7 +508,7 @@
508
508
  ],
509
509
  "meta": {
510
510
  "version": "1.6.0",
511
- "requiresGrove": "1.2.0"
511
+ "requiresGrove": "1.3.0"
512
512
  }
513
513
  },
514
514
  {
@@ -534,7 +534,7 @@
534
534
  ],
535
535
  "meta": {
536
536
  "version": "1.6.0",
537
- "requiresGrove": "1.2.0"
537
+ "requiresGrove": "1.3.0"
538
538
  }
539
539
  },
540
540
  {
@@ -555,7 +555,7 @@
555
555
  ],
556
556
  "meta": {
557
557
  "version": "1.6.0",
558
- "requiresGrove": "1.2.0"
558
+ "requiresGrove": "1.3.0"
559
559
  }
560
560
  },
561
561
  {
@@ -576,7 +576,7 @@
576
576
  ],
577
577
  "meta": {
578
578
  "version": "1.6.0",
579
- "requiresGrove": "1.2.0"
579
+ "requiresGrove": "1.3.0"
580
580
  }
581
581
  },
582
582
  {
@@ -597,7 +597,7 @@
597
597
  ],
598
598
  "meta": {
599
599
  "version": "1.6.0",
600
- "requiresGrove": "1.2.0"
600
+ "requiresGrove": "1.3.0"
601
601
  }
602
602
  },
603
603
  {
@@ -1020,7 +1020,7 @@
1020
1020
  ],
1021
1021
  "meta": {
1022
1022
  "version": "1.6.0",
1023
- "requiresGrove": "1.2.0"
1023
+ "requiresGrove": "1.3.0"
1024
1024
  }
1025
1025
  }
1026
1026
  ]
package/dist/r/shell.json CHANGED
@@ -70,7 +70,7 @@
70
70
  ],
71
71
  "meta": {
72
72
  "version": "1.6.0",
73
- "requiresGrove": "1.2.0"
73
+ "requiresGrove": "1.3.0"
74
74
  },
75
75
  "type": "registry:block"
76
76
  }
@@ -23,7 +23,7 @@
23
23
  ],
24
24
  "meta": {
25
25
  "version": "1.6.0",
26
- "requiresGrove": "1.2.0"
26
+ "requiresGrove": "1.3.0"
27
27
  },
28
28
  "type": "registry:block"
29
29
  }
@@ -61,7 +61,7 @@
61
61
  ],
62
62
  "meta": {
63
63
  "version": "1.6.0",
64
- "requiresGrove": "1.2.0"
64
+ "requiresGrove": "1.3.0"
65
65
  },
66
66
  "type": "registry:block"
67
67
  }
package/dist/r/ui.json CHANGED
@@ -49,7 +49,7 @@
49
49
  ],
50
50
  "meta": {
51
51
  "version": "1.6.0",
52
- "requiresGrove": "1.2.0"
52
+ "requiresGrove": "1.3.0"
53
53
  },
54
54
  "type": "registry:ui"
55
55
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@grove-dev/cli",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
4
4
  "type": "module",
5
5
  "description": "Grove CLI — scaffolds Grove-powered spaces and orchestrates @grove-dev/core commands.",
6
6
  "license": "MIT",
@@ -45,10 +45,10 @@
45
45
  "dependencies": {
46
46
  "chrome-launcher": "^1.2.1",
47
47
  "commander": "^15.0.0",
48
- "lighthouse": "^12.8.2",
48
+ "lighthouse": "^13.5.0",
49
49
  "typescript": "^5.9.3",
50
50
  "yaml": "^2.6.0",
51
- "@grove-dev/core": "1.2.0"
51
+ "@grove-dev/core": "1.3.0"
52
52
  },
53
53
  "devDependencies": {
54
54
  "tsx": "^4.23.0",