@grove-dev/cli 0.11.0 → 0.13.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/index.js +21 -89
- package/dist/index.js.map +1 -1
- package/dist/migrate-cli.d.ts +25 -0
- package/dist/migrate-cli.d.ts.map +1 -0
- package/dist/migrate-cli.js +68 -0
- package/dist/migrate-cli.js.map +1 -0
- package/dist/package.json +1 -1
- package/dist/r/about.json +1 -1
- package/dist/r/browse.json +11 -5
- package/dist/r/collections.json +1 -1
- package/dist/r/contributors.json +1 -1
- package/dist/r/default.json +12 -6
- package/dist/r/home.json +1 -1
- package/dist/r/not-found.json +1 -1
- package/dist/r/project-card.json +1 -1
- package/dist/r/record.json +1 -1
- package/dist/r/registry.json +23 -13
- package/dist/r/shell.json +1 -1
- package/dist/r/submit.json +1 -1
- package/dist/r/taxonomy.json +1 -1
- package/dist/r/ui.json +2 -2
- package/dist/readme-cli.d.ts.map +1 -1
- package/dist/readme-cli.js +33 -19
- package/dist/readme-cli.js.map +1 -1
- package/dist/sync-github.d.ts +30 -0
- package/dist/sync-github.d.ts.map +1 -0
- package/dist/sync-github.js +127 -0
- package/dist/sync-github.js.map +1 -0
- package/dist/sync-summary.d.ts +42 -0
- package/dist/sync-summary.d.ts.map +1 -0
- package/dist/sync-summary.js +90 -0
- package/dist/sync-summary.js.map +1 -0
- package/package.json +2 -2
package/dist/r/default.json
CHANGED
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
},
|
|
31
31
|
{
|
|
32
32
|
"path": "default/components/ui/filter-drawer.astro",
|
|
33
|
-
"content": "---\n/**\n * FilterDrawer — mobile filter surface built on native `<dialog>`.\n *\n * `showModal()` gives focus trapping, Escape handling, and the\n * top-layer backdrop for free — no dependency, no hand-rolled trap.\n * On viewports ≥ md the trigger button hides and the slotted filter\n * controls render inline through the same slot used on desktop, so\n * there is exactly one copy of the filter markup.\n *\n * No-JS fallback: the slot content stays in normal flow (the dialog\n * only wraps it once the client script moves it), so filters remain\n * usable without JavaScript.\n */\nimport { buttonClass } from '../../lib/classnames.ts';\n\ninterface Props {\n /** Trigger button label. */\n label?: string;\n /** Count of active filters shown on the trigger. */\n activeCount?: number;\n /** URL that clears every filter — offered inside the sheet. */\n clearHref?: string;\n class?: string;\n}\n\nconst { label = 'Filters', activeCount = 0, clearHref, class: className = '' } = Astro.props;\n---\n\n<div class={`grove-filter-drawer ${className}`} data-grove-filter-drawer>\n <button\n type=\"button\"\n data-drawer-open\n class={buttonClass(\"secondary\", \"md\", \"w-full md:hidden\")}\n aria-haspopup=\"dialog\"\n >\n {label}\n {/* Always in the DOM (hidden at zero) so the client script can\n update it from the live URL state on this prerendered page. */}\n <span\n data-drawer-count\n class:list={[\n \"inline-flex min-w-5 items-center justify-center rounded-full bg-selected px-1.5 py-0.5 font-mono text-2xs leading-none text-selected-foreground\",\n activeCount === 0 && \"hidden\",\n ]}\n >\n {activeCount}\n </span>\n </button>\n\n {/* On mobile the client script moves this content into the dialog;\n on ≥ md it stays inline. Not hidden by CSS — without JS the\n filters must remain visible in flow on every viewport. */}\n <div data-drawer-content class=\"md:contents\">\n <slot />\n </div>\n\n <dialog\n data-drawer-dialog\n class=\"m-0 mt-auto w-full max-w-none rounded-t-[calc(var(--radius)+0.5rem)] border-0 bg-surface-overlay p-0 text-foreground backdrop:bg-black/40 md:hidden\"\n aria-label={label}\n >\n <div class=\"flex items-center justify-between gap-3 border-b border-border px-4 py-3\">\n <p class=\"m-0 text-sm font-semibold\">{label}</p>\n <div class=\"flex items-center gap-2\">\n {clearHref && (\n /* Clearing from inside the sheet is the only way out of a\n stack of filters on mobile — the chips row is behind it. */\n <a\n href={clearHref}\n data-drawer-clear\n class:list={[buttonClass(\"ghost\", \"sm\"), activeCount === 0 && \"hidden\"]}\n >\n Clear all\n </a>\n )}\n <button type=\"button\" data-drawer-close class={buttonClass(\"ghost\", \"sm\")}>\n
|
|
33
|
+
"content": "---\n/**\n * FilterDrawer — mobile filter surface built on native `<dialog>`.\n *\n * `showModal()` gives focus trapping, Escape handling, and the\n * top-layer backdrop for free — no dependency, no hand-rolled trap.\n * On viewports ≥ md the trigger button hides and the slotted filter\n * controls render inline through the same slot used on desktop, so\n * there is exactly one copy of the filter markup.\n *\n * No-JS fallback: the slot content stays in normal flow (the dialog\n * only wraps it once the client script moves it), so filters remain\n * usable without JavaScript.\n *\n * Filters inside the sheet apply live, so the page behind it is\n * already showing the real results. The sticky footer button\n * (\"Show 12 apps\") closes the sheet and moves focus to\n * `resultsTarget`. It is a way back to the results, not an apply\n * step. The page's controller keeps its label current: it sets the\n * text on `[data-drawer-results]`, and sets `aria-busy=\"true\"` while\n * the results are still loading.\n *\n * The sheet announces itself with a `grove:filter-surface` event on\n * the document when it opens and closes. The page uses this to group\n * the changes made in one sitting into a single history entry.\n */\nimport { buttonClass } from '../../lib/classnames.ts';\n\ninterface Props {\n /** Trigger button label. */\n label?: string;\n /** Count of active filters shown on the trigger. */\n activeCount?: number;\n /** URL that clears every filter — offered inside the sheet. */\n clearHref?: string;\n /** Footer button label before the page's controller updates it. */\n resultsLabel?: string;\n /**\n * Selector for the element that receives focus when the footer\n * button closes the sheet, usually the results heading. It needs\n * `tabindex=\"-1\"` if it is not focusable on its own.\n */\n resultsTarget?: string;\n class?: string;\n}\n\nconst { label = 'Filters', activeCount = 0, clearHref, class: className = '' } = Astro.props;\n---\n\n<div class={`grove-filter-drawer ${className}`} data-grove-filter-drawer data-results-target={Astro.props.resultsTarget}>\n <button\n type=\"button\"\n data-drawer-open\n class={buttonClass(\"secondary\", \"md\", \"w-full md:hidden\")}\n aria-haspopup=\"dialog\"\n >\n {label}\n {/* Always in the DOM (hidden at zero) so the client script can\n update it from the live URL state on this prerendered page. */}\n <span\n data-drawer-count\n class:list={[\n \"inline-flex min-w-5 items-center justify-center rounded-full bg-selected px-1.5 py-0.5 font-mono text-2xs leading-none text-selected-foreground\",\n activeCount === 0 && \"hidden\",\n ]}\n >\n {activeCount}\n </span>\n </button>\n\n {/* On mobile the client script moves this content into the dialog;\n on ≥ md it stays inline. Not hidden by CSS — without JS the\n filters must remain visible in flow on every viewport. */}\n <div data-drawer-content class=\"md:contents\">\n <slot />\n </div>\n\n <dialog\n data-drawer-dialog\n class=\"m-0 mt-auto max-h-[85dvh] w-full max-w-none rounded-t-[calc(var(--radius)+0.5rem)] border-0 bg-surface-overlay p-0 text-foreground backdrop:bg-black/40 open:flex open:flex-col md:hidden\"\n aria-label={label}\n >\n <div class=\"flex items-center justify-between gap-3 border-b border-border px-4 py-3\">\n <p class=\"m-0 text-sm font-semibold\">{label}</p>\n <div class=\"flex items-center gap-2\">\n {clearHref && (\n /* Clearing from inside the sheet is the only way out of a\n stack of filters on mobile — the chips row is behind it. */\n <a\n href={clearHref}\n data-drawer-clear\n class:list={[buttonClass(\"ghost\", \"sm\"), activeCount === 0 && \"hidden\"]}\n >\n Clear all\n </a>\n )}\n <button type=\"button\" data-drawer-close class={buttonClass(\"ghost\", \"sm\")}>\n Close\n </button>\n </div>\n </div>\n <div data-drawer-body class=\"min-h-0 flex-1 overflow-y-auto p-4\"></div>\n {/* Outside the scrolling body, so it stays pinned to the bottom of\n the sheet however long the filter list is. */}\n <div class=\"border-t border-border p-4\">\n <button\n type=\"button\"\n data-drawer-results\n class={buttonClass(\"primary\", \"md\", \"w-full aria-busy:opacity-70\")}\n >\n {Astro.props.resultsLabel ?? \"Show results\"}\n </button>\n </div>\n </dialog>\n</div>\n\n<script>\n document.querySelectorAll<HTMLElement>(\"[data-grove-filter-drawer]\").forEach((root) => {\n const dialog = root.querySelector<HTMLDialogElement>(\"[data-drawer-dialog]\");\n const content = root.querySelector<HTMLElement>(\"[data-drawer-content]\");\n const body = root.querySelector<HTMLElement>(\"[data-drawer-body]\");\n const open = root.querySelector<HTMLButtonElement>(\"[data-drawer-open]\");\n const close = root.querySelector<HTMLButtonElement>(\"[data-drawer-close]\");\n if (!dialog || !content || !body || !open) return;\n\n const mobile = window.matchMedia(\"(max-width: 47.999rem)\");\n const place = () => {\n // One copy of the filter markup, moved between the inline slot\n // (desktop) and the dialog body (mobile).\n if (mobile.matches) {\n body.append(...content.children);\n content.classList.add(\"hidden\");\n } else {\n if (dialog.open) dialog.close();\n content.append(...body.children);\n content.classList.remove(\"hidden\");\n }\n };\n place();\n mobile.addEventListener(\"change\", place);\n\n const results = root.querySelector<HTMLButtonElement>(\"[data-drawer-results]\");\n const surface = (isOpen: boolean) =>\n document.dispatchEvent(\n new CustomEvent(\"grove:filter-surface\", { detail: { surface: \"drawer\", open: isOpen } }),\n );\n\n open.addEventListener(\"click\", () => {\n dialog.showModal();\n surface(true);\n });\n // `close` fires however the sheet closes: a button, Escape, or the\n // backdrop.\n dialog.addEventListener(\"close\", () => surface(false));\n close?.addEventListener(\"click\", () => dialog.close());\n results?.addEventListener(\"click\", () => {\n dialog.close();\n // Closing the sheet puts focus back on the Filters button. The\n // results are what the user asked for, so move focus there. The\n // browser scrolls the target into view as part of focusing it.\n const selector = root.dataset.resultsTarget;\n const target = selector ? document.querySelector<HTMLElement>(selector) : null;\n target?.focus();\n });\n dialog.addEventListener(\"click\", (event) => {\n // Backdrop click closes: the dialog element itself is the\n // target only when the click lands outside the panel content.\n if (event.target === dialog) dialog.close();\n });\n });\n</script>\n",
|
|
34
34
|
"type": "registry:ui",
|
|
35
35
|
"target": "~/src/components/ui/filter-drawer.astro"
|
|
36
36
|
},
|
|
@@ -306,25 +306,25 @@
|
|
|
306
306
|
},
|
|
307
307
|
{
|
|
308
308
|
"path": "default/components/grove/directory-browse.astro",
|
|
309
|
-
"content": "---\n/**\n * DirectoryBrowse — the browse page body, shared by the two routes\n * that render it: `/{slug}/` (page 1) and `/{slug}/page/{n}/`.\n *\n * Layout, top to bottom:\n * - PageHeader (the only place the page names itself)\n * - Search + Sort on one row\n * - Every facet filter on the next row\n * - Applied-filter chips + Clear all on their own row\n * - Result count / sort / page line\n * - Card grid, then pagination\n *\n * Navigation model: **pages are real paths.** Each route prerenders\n * only its own 20 records, so an unfiltered directory of any size is\n * crawlable, works without JavaScript, and never ships the whole\n * catalogue as DOM.\n *\n * Filtering stays client-side: these routes are PRERENDERED, so at\n * build time `Astro.url.searchParams` is empty. `DirectoryIndexClient`\n * re-reads `location.search` and re-derives the result list, chips,\n * pagination, and facet intersection counts with the same\n * `@grove-dev/core/directory` functions the server used. Filtered views\n * paginate with `?page=N` on the base route.\n */\nimport siteConfig from '@grove/generated/site-config.json';\nimport { SORT_OPTIONS, sortDisplay } from '@grove-dev/astro';\nimport {\n getDirectoryIndexModel,\n itemLabel,\n itemLabelPlural,\n seoTitle,\n taxonomy,\n titleCaseFirst,\n} from '@grove-dev/astro/server';\nimport { formatCount } from '@grove-dev/core';\nimport BaseLayout from '../../layouts/base-layout.astro';\nimport { chipClass } from '../../lib/classnames.ts';\nimport Button from '../ui/button.astro';\nimport FilterDrawer from '../ui/filter-drawer.astro';\nimport PageHeader from '../ui/page-header.astro';\nimport SearchField from '../ui/search-field.astro';\nimport CardGrid from './card-grid.astro';\nimport DirectoryIndexClient from './directory-index-client.astro';\nimport IndexRow from './index-row.astro';\nimport Pagination from './pagination.astro';\nimport RefinePanel from './refine-panel.astro';\nimport SmartLensTabs from './smart-lens-tabs.astro';\n\ninterface Props {\n /** 1-based page this route renders. */\n routePage?: number;\n}\n\nconst { routePage = 1 } = Astro.props;\nconst slug = siteConfig.blueprintConfig?.routeSlug ?? 'projects';\nconst {\n total,\n filters,\n facetGroups,\n searchPlaceholder,\n sort,\n sorted,\n pageItems,\n pages,\n page,\n chips,\n clearFiltersHref,\n hrefForResultPage,\n seo,\n} = getDirectoryIndexModel(Astro.url.searchParams, siteConfig, { page: routePage });\n\n// Page 2+ gets a distinct title and skips the ItemList JSON-LD so the\n// list markup isn't duplicated across every paginated route. The\n// per-page description is built inside `getDirectoryIndexModel` so it\n// fits inside the 160-char cap; this view just forwards `seo.title`.\nconst title =\n page > 1\n ? seoTitle(`Browse ${titleCaseFirst(itemLabelPlural())} — Page ${page}`, siteConfig.name)\n : seo.title;\nconst description = seo.description;\n---\n\n<BaseLayout\n title={title}\n description={description}\n image={seo.image}\n jsonLd={page > 1 ? undefined : seo.jsonLd}\n site={siteConfig}\n submitHref=\"/submit\"\n submitLabel={`Submit ${itemLabel()}`}\n>\n <section class=\"border-b border-border bg-background\">\n <div class=\"mx-auto w-full max-w-container px-5 pt-10 sm:px-7 sm:pt-12\">\n <PageHeader\n eyebrow={slug}\n title={`Browse ${slug}`}\n description={`Search, filter, and explore ${formatCount(total, { singular: itemLabel(), plural: itemLabelPlural() })} in this directory.`}\n />\n\n {/* Curated views. Real links (not a JS-driven control) — the\n same server-and-client filter pipeline (@grove-dev/core's\n filtersFromSearchParams/filterRecords) already understands\n `?lens=`, so this works with JS disabled too. */}\n <SmartLensTabs\n currentParams={Astro.url.searchParams}\n pathPrefix={`/${slug}`}\n lensIds={[\"all\", \"hot\", \"new\", \"mature\"]}\n class=\"mt-6\"\n />\n\n {/* Row 1 — search and sort. Search filters as you type (see\n DirectoryIndexClient); the submit button is sr-only so Enter\n still works when JavaScript never arrives. */}\n <form\n method=\"get\"\n action={`/${slug}`}\n id=\"search-form\"\n class=\"mt-6 flex flex-col gap-2 sm:flex-row\"\n role=\"search\"\n >\n <SearchField\n class=\"flex-1\"\n label={`Search ${itemLabelPlural()}`}\n value={filters.q ?? \"\"}\n placeholder={searchPlaceholder}\n shortcut\n />\n <label class=\"relative\">\n <span class=\"sr-only\">{`Sort ${itemLabelPlural()}`}</span>\n <select\n id=\"sort-select\"\n name=\"sort\"\n class=\"h-10 w-full cursor-pointer appearance-none rounded-md border border-input bg-background py-1.5 pl-3 pr-8 text-sm font-medium text-foreground transition-colors hover:border-ring focus:border-ring focus:outline-none focus:ring-2 focus:ring-ring/20 sm:w-auto\"\n >\n {SORT_OPTIONS.map((o) => (\n <option value={o.value} selected={o.value === sort}>{o.label}</option>\n ))}\n </select>\n <svg\n viewBox=\"0 0 16 16\"\n width=\"11\"\n height=\"11\"\n aria-hidden=\"true\"\n class=\"pointer-events-none absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground\"\n fill=\"currentColor\"\n >\n <path d=\"M4.22 6.22a.75.75 0 0 1 1.06 0L8 8.94l2.72-2.72a.75.75 0 1 1 1.06 1.06l-3.25 3.25a.75.75 0 0 1-1.06 0L4.22 7.28a.75.75 0 0 1 0-1.06Z\" />\n </svg>\n </label>\n <button type=\"submit\" class=\"sr-only\">Search</button>\n </form>\n\n {/* Row 2 — every filter on one line. On mobile they collapse into\n a full-width \"Filters (n)\" button opening a bottom sheet. */}\n <div class=\"mt-3\">\n <FilterDrawer label=\"Filters\" activeCount={chips.length} clearHref={clearFiltersHref}>\n <RefinePanel\n class=\"max-md:flex-col max-md:items-stretch\"\n groups={facetGroups}\n initial={filters}\n pathPrefix={`/${slug}`}\n hide={[\"sort\"]}\n />\n </FilterDrawer>\n </div>\n\n {/* Row 3 — what is currently narrowing the list, and one way out\n of all of it. Server-rendered empty on this prerendered route;\n the client fills it from the live query string. */}\n <div\n id=\"active-filters\"\n class:list={[\"mt-3 flex flex-wrap items-center gap-1.5 pb-6\", chips.length === 0 && \"hidden\"]}\n aria-label=\"Active filters\"\n >\n {chips.map((chip) => (\n <a href={chip.href} class={chipClass()} aria-label={`Remove filter: ${chip.label}`}>\n {chip.label} <span aria-hidden=\"true\">×</span>\n </a>\n ))}\n {chips.length > 0 && (\n <a\n href={clearFiltersHref}\n class=\"text-2xs font-medium text-ink-500 underline decoration-border underline-offset-2 hover:text-ink-900 dark:hover:text-ink-100\"\n aria-label=\"Clear all active filters\"\n >\n Clear all\n </a>\n )}\n </div>\n {chips.length === 0 && <div class=\"pb-6\"></div>}\n </div>\n </section>\n\n <section class=\"py-10 sm:py-12\">\n <div class=\"mx-auto w-full max-w-container px-5 sm:px-7\">\n {/* The count line IS the results heading — it carries a fact,\n which \"All projects / Every item in the directory\" did not,\n and it keeps the document's heading order intact above the\n cards' own h3s. */}\n <h2\n id=\"results-heading\"\n class=\"m-0 mb-5 text-2xs font-normal text-ink-500 dark:text-ink-400\"\n >\n <span id=\"results-count\" class=\"font-mono font-semibold text-ink-900 dark:text-ink-100\">\n {sorted.length} {sorted.length === 1 ? itemLabel() : itemLabelPlural()}\n </span>\n <span id=\"results-sort\">{` · sorted by ${sortDisplay(sort)}`}</span>\n <span id=\"results-page\">{pages > 1 ? ` · page ${page} of ${pages}` : \"\"}</span>\n </h2>\n\n <CardGrid id=\"results-list\">\n {pageItems.map((item, i) => (\n <li class=\"m-0 p-0\" data-record-slug={item.slug}>\n <IndexRow\n record={item as Parameters<typeof IndexRow>[0][\"record\"]}\n detailHref={`/${slug}/${item.slug}/`}\n eager={i < 3}\n />\n </li>\n ))}\n </CardGrid>\n\n <div id=\"empty-state\" class:list={[\"py-12 text-center\", sorted.length > 0 && \"hidden\"]}>\n <p class=\"m-0 text-sm font-medium text-ink-700 dark:text-ink-200\">\n {`No ${itemLabelPlural()} match these filters.`}\n </p>\n <Button href={clearFiltersHref} variant=\"secondary\" size=\"sm\" class=\"mt-4\">Clear filters</Button>\n </div>\n {/* Plain div wrapper — Pagination renders its own\n <nav aria-label=\"Pagination\">, so a nav here would nest two\n identical landmarks. */}\n <div id=\"results-pagination\" class=\"mt-8 flex flex-wrap items-center justify-center gap-1.5\">\n <Pagination current={page} total={pages} hrefFor={hrefForResultPage} />\n </div>\n </div>\n </section>\n\n <section class=\"border-t border-ink-200 dark:border-ink-800\">\n <div class=\"mx-auto w-full max-w-container px-5 sm:px-7\">\n <div class=\"flex flex-col items-center gap-3 py-12 text-center\">\n <h2 class=\"m-0 text-xl font-semibold tracking-tight text-ink-900 dark:text-ink-100\">\n {`Know a real ${itemLabel()} that belongs here?`}\n </h2>\n <p class=\"m-0 max-w-2xl text-sm text-ink-500 dark:text-ink-400\">\n {`Open a pull request with a YAML file. We review every submission against the bar — no marketing, no tutorials.`}\n </p>\n <Button href=\"/submit\" variant=\"primary\" size=\"sm\" class=\"mt-2\">\n {`Submit ${itemLabel()}`}\n </Button>\n\n </div>\n </div>\n </section>\n\n <DirectoryIndexClient\n slug={slug}\n singular={itemLabel()}\n plural={itemLabelPlural()}\n taxonomy={taxonomy}\n routePage={page}\n />\n</BaseLayout>\n",
|
|
309
|
+
"content": "---\n/**\n * DirectoryBrowse — the browse page body, shared by the two routes\n * that render it: `/{slug}/` (page 1) and `/{slug}/page/{n}/`.\n *\n * Layout, top to bottom:\n * - PageHeader (the only place the page names itself)\n * - Search + Sort on one row\n * - Every facet filter on the next row\n * - Applied-filter chips + Clear all on their own row\n * - Result count / sort / page line\n * - Card grid, then pagination\n *\n * Navigation model: **pages are real paths.** Each route prerenders\n * only its own 20 records, so an unfiltered directory of any size is\n * crawlable, works without JavaScript, and never ships the whole\n * catalogue as DOM.\n *\n * Filtering stays client-side: these routes are PRERENDERED, so at\n * build time `Astro.url.searchParams` is empty. `DirectoryIndexClient`\n * re-reads `location.search` and re-derives the result list, chips,\n * pagination, and facet intersection counts with the same\n * `@grove-dev/core/directory` functions the server used. Filtered views\n * paginate with `?page=N` on the base route.\n */\nimport siteConfig from '@grove/generated/site-config.json';\nimport { SORT_OPTIONS, sortDisplay } from '@grove-dev/astro';\nimport {\n getDirectoryIndexModel,\n itemLabel,\n itemLabelPlural,\n seoTitle,\n taxonomy,\n titleCaseFirst,\n} from '@grove-dev/astro/server';\nimport { formatCount } from '@grove-dev/core';\nimport BaseLayout from '../../layouts/base-layout.astro';\nimport { chipClass } from '../../lib/classnames.ts';\nimport Button from '../ui/button.astro';\nimport FilterDrawer from '../ui/filter-drawer.astro';\nimport PageHeader from '../ui/page-header.astro';\nimport SearchField from '../ui/search-field.astro';\nimport CardGrid from './card-grid.astro';\nimport DirectoryIndexClient from './directory-index-client.astro';\nimport IndexRow from './index-row.astro';\nimport Pagination from './pagination.astro';\nimport RefinePanel from './refine-panel.astro';\nimport SmartLensTabs from './smart-lens-tabs.astro';\n\ninterface Props {\n /** 1-based page this route renders. */\n routePage?: number;\n}\n\nconst { routePage = 1 } = Astro.props;\nconst slug = siteConfig.blueprintConfig?.routeSlug ?? 'projects';\nconst {\n total,\n filters,\n facetGroups,\n searchPlaceholder,\n sort,\n sorted,\n pageItems,\n pages,\n page,\n chips,\n clearFiltersHref,\n hrefForResultPage,\n seo,\n} = getDirectoryIndexModel(Astro.url.searchParams, siteConfig, { page: routePage });\n\n// Page 2+ gets a distinct title and skips the ItemList JSON-LD so the\n// list markup isn't duplicated across every paginated route. The\n// per-page description is built inside `getDirectoryIndexModel` so it\n// fits inside the 160-char cap; this view just forwards `seo.title`.\nconst title =\n page > 1\n ? seoTitle(`Browse ${titleCaseFirst(itemLabelPlural())} — Page ${page}`, siteConfig.name)\n : seo.title;\nconst description = seo.description;\n---\n\n<BaseLayout\n title={title}\n description={description}\n image={seo.image}\n jsonLd={page > 1 ? undefined : seo.jsonLd}\n site={siteConfig}\n submitHref=\"/submit\"\n submitLabel={`Submit ${itemLabel()}`}\n>\n <section class=\"border-b border-border bg-background\">\n <div class=\"mx-auto w-full max-w-container px-5 pt-10 sm:px-7 sm:pt-12\">\n <PageHeader\n eyebrow={slug}\n title={`Browse ${slug}`}\n description={`Search, filter, and explore ${formatCount(total, { singular: itemLabel(), plural: itemLabelPlural() })} in this directory.`}\n />\n\n {/* Curated views. Real links (not a JS-driven control) — the\n same server-and-client filter pipeline (@grove-dev/core's\n filtersFromSearchParams/filterRecords) already understands\n `?lens=`, so this works with JS disabled too. */}\n <SmartLensTabs\n currentParams={Astro.url.searchParams}\n pathPrefix={`/${slug}`}\n lensIds={[\"all\", \"hot\", \"new\", \"mature\"]}\n class=\"mt-6\"\n />\n\n {/* Row 1 — search and sort. Search filters as you type (see\n DirectoryIndexClient); the submit button is sr-only so Enter\n still works when JavaScript never arrives. */}\n <form\n method=\"get\"\n action={`/${slug}`}\n id=\"search-form\"\n class=\"mt-6 flex flex-col gap-2 sm:flex-row\"\n role=\"search\"\n >\n <SearchField\n class=\"flex-1\"\n label={`Search ${itemLabelPlural()}`}\n value={filters.q ?? \"\"}\n placeholder={searchPlaceholder}\n shortcut\n />\n <label class=\"relative\">\n <span class=\"sr-only\">{`Sort ${itemLabelPlural()}`}</span>\n <select\n id=\"sort-select\"\n name=\"sort\"\n class=\"h-10 w-full cursor-pointer appearance-none rounded-md border border-input bg-background py-1.5 pl-3 pr-8 text-sm font-medium text-foreground transition-colors hover:border-ring focus:border-ring focus:outline-none focus:ring-2 focus:ring-ring/20 sm:w-auto\"\n >\n {SORT_OPTIONS.map((o) => (\n <option value={o.value} selected={o.value === sort}>{o.label}</option>\n ))}\n </select>\n <svg\n viewBox=\"0 0 16 16\"\n width=\"11\"\n height=\"11\"\n aria-hidden=\"true\"\n class=\"pointer-events-none absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground\"\n fill=\"currentColor\"\n >\n <path d=\"M4.22 6.22a.75.75 0 0 1 1.06 0L8 8.94l2.72-2.72a.75.75 0 1 1 1.06 1.06l-3.25 3.25a.75.75 0 0 1-1.06 0L4.22 7.28a.75.75 0 0 1 0-1.06Z\" />\n </svg>\n </label>\n <button type=\"submit\" class=\"sr-only\">Search</button>\n </form>\n\n {/* Row 2 — every filter on one line. On mobile they collapse into\n a full-width \"Filters (n)\" button opening a bottom sheet.\n Filters apply live in both places. The sheet's footer button\n (\"Show 12 apps\") just closes it and moves focus to the\n results heading. */}\n <div class=\"mt-3\">\n <FilterDrawer\n label=\"Filters\"\n activeCount={chips.length}\n clearHref={clearFiltersHref}\n resultsLabel={`Show ${sorted.length} ${sorted.length === 1 ? itemLabel() : itemLabelPlural()}`}\n resultsTarget=\"#results-heading\"\n >\n {/* The applied chips again, inside the sheet: on mobile the\n row above the list is behind the sheet. On desktop the\n filters render inline right above that row, so this copy\n stays hidden. DirectoryIndexClient fills both. The sheet's\n header already has \"Clear all\", so this row leaves it out. */}\n <div\n data-active-filters\n data-without-clear\n class:list={[\"mb-3 flex flex-wrap items-center gap-1.5 md:hidden\", chips.length === 0 && \"hidden\"]}\n aria-label=\"Active filters\"\n ></div>\n <RefinePanel\n class=\"max-md:flex-col max-md:items-stretch\"\n groups={facetGroups}\n initial={filters}\n pathPrefix={`/${slug}`}\n hide={[\"sort\"]}\n />\n </FilterDrawer>\n </div>\n\n {/* Row 3 — what is currently narrowing the list, and one way out\n of all of it. Server-rendered empty on this prerendered route;\n the client fills it from the live query string. */}\n <div\n id=\"active-filters\"\n data-active-filters\n class:list={[\"mt-3 flex flex-wrap items-center gap-1.5 pb-6\", chips.length === 0 && \"hidden\"]}\n aria-label=\"Active filters\"\n >\n {chips.map((chip) => (\n <a href={chip.href} class={chipClass()} aria-label={`Remove filter: ${chip.label}`}>\n {chip.label} <span aria-hidden=\"true\">×</span>\n </a>\n ))}\n {chips.length > 0 && (\n <a\n href={clearFiltersHref}\n class=\"text-2xs font-medium text-ink-500 underline decoration-border underline-offset-2 hover:text-ink-900 dark:hover:text-ink-100\"\n aria-label=\"Clear all active filters\"\n >\n Clear all\n </a>\n )}\n </div>\n {chips.length === 0 && <div class=\"pb-6\"></div>}\n </div>\n </section>\n\n <section class=\"py-10 sm:py-12\">\n <div class=\"mx-auto w-full max-w-container px-5 sm:px-7\">\n {/* The count line IS the results heading — it carries a fact,\n which \"All projects / Every item in the directory\" did not,\n and it keeps the document's heading order intact above the\n cards' own h3s. */}\n {/* `tabindex=\"-1\"` lets the drawer's \"Show N\" button and the\n focus fallbacks in DirectoryIndexClient move focus here. */}\n <h2\n id=\"results-heading\"\n tabindex=\"-1\"\n class=\"m-0 mb-5 scroll-mt-4 text-2xs font-normal text-ink-500 dark:text-ink-400\"\n >\n <span id=\"results-count\" class=\"font-mono font-semibold text-ink-900 dark:text-ink-100\">\n {sorted.length} {sorted.length === 1 ? itemLabel() : itemLabelPlural()}\n </span>\n <span id=\"results-sort\">{` · sorted by ${sortDisplay(sort)}`}</span>\n <span id=\"results-page\">{pages > 1 ? ` · page ${page} of ${pages}` : \"\"}</span>\n </h2>\n\n {/* Screen readers hear the result count here, debounced by\n DirectoryIndexClient so rapid toggles make one announcement.\n The visible count above is deliberately not a live region,\n or every change would be announced twice. */}\n <p id=\"results-status\" class=\"sr-only\" role=\"status\" aria-live=\"polite\" aria-atomic=\"true\"></p>\n\n <CardGrid id=\"results-list\">\n {pageItems.map((item, i) => (\n <li class=\"m-0 p-0\" data-record-slug={item.slug}>\n <IndexRow\n record={item as Parameters<typeof IndexRow>[0][\"record\"]}\n detailHref={`/${slug}/${item.slug}/`}\n eager={i < 3}\n />\n </li>\n ))}\n </CardGrid>\n\n <div id=\"empty-state\" class:list={[\"py-12 text-center\", sorted.length > 0 && \"hidden\"]}>\n <p class=\"m-0 text-sm font-medium text-ink-700 dark:text-ink-200\">\n {`No ${itemLabelPlural()} match these filters.`}\n </p>\n {/* The client keeps this href in step with the live query, so\n clearing keeps the chosen sort. */}\n <Button href={clearFiltersHref} variant=\"secondary\" size=\"sm\" class=\"mt-4\" data-empty-reset>Clear filters</Button>\n </div>\n {/* Plain div wrapper — Pagination renders its own\n <nav aria-label=\"Pagination\">, so a nav here would nest two\n identical landmarks. */}\n <div id=\"results-pagination\" class=\"mt-8 flex flex-wrap items-center justify-center gap-1.5\">\n <Pagination current={page} total={pages} hrefFor={hrefForResultPage} />\n </div>\n </div>\n </section>\n\n <section class=\"border-t border-ink-200 dark:border-ink-800\">\n <div class=\"mx-auto w-full max-w-container px-5 sm:px-7\">\n <div class=\"flex flex-col items-center gap-3 py-12 text-center\">\n <h2 class=\"m-0 text-xl font-semibold tracking-tight text-ink-900 dark:text-ink-100\">\n {`Know a real ${itemLabel()} that belongs here?`}\n </h2>\n <p class=\"m-0 max-w-2xl text-sm text-ink-500 dark:text-ink-400\">\n {`Open a pull request with a YAML file. We review every submission against the bar — no marketing, no tutorials.`}\n </p>\n <Button href=\"/submit\" variant=\"primary\" size=\"sm\" class=\"mt-2\">\n {`Submit ${itemLabel()}`}\n </Button>\n\n </div>\n </div>\n </section>\n\n <DirectoryIndexClient\n slug={slug}\n singular={itemLabel()}\n plural={itemLabelPlural()}\n taxonomy={taxonomy}\n routePage={page}\n />\n</BaseLayout>\n",
|
|
310
310
|
"type": "registry:component",
|
|
311
311
|
"target": "~/src/components/grove/directory-browse.astro"
|
|
312
312
|
},
|
|
313
313
|
{
|
|
314
314
|
"path": "default/components/grove/directory-index-client.astro",
|
|
315
|
-
"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 */\ninterface Props {\n slug: string;\n singular: string;\n plural: string;\n taxonomy: Record<string, unknown>;\n /** Page this route prerendered; the client starts from it. */\n routePage?: number;\n}\n\nconst { slug, singular, plural, taxonomy, routePage = 1 } = Astro.props;\nconst clientConfigJson = JSON.stringify({ slug, singular, plural, taxonomy, routePage }).replace(\n /</g,\n '\\\\u003c',\n);\n---\n\n<script is:inline id=\"grove-index-config\" type=\"application/json\" set:html={clientConfigJson}></script>\n<script>\n import type { IndexRecord } from \"@grove-dev/core\";\n import type { DirectoryFilterGroupKey } from \"@grove-dev/core/directory\";\n import {\n PAGE_SIZE,\n activeFilterChips,\n applySort,\n buildFacets,\n DIRECTORY_FILTER_KEYS,\n DIRECTORY_FILTER_LABELS,\n DIRECTORY_TAXONOMY_KINDS,\n effectivePage,\n effectiveSort,\n filterRecords,\n filtersFromSearchParams,\n hasAnyFilter,\n isDirectoryFilterGroupKey,\n hrefForClearedFilters,\n hrefForFilters,\n pagePathHref,\n paginationPageList,\n searchParamsFromFilters,\n sortDisplay,\n totalPages,\n } from \"@grove-dev/core/directory\";\n import {\n PAGINATION_DISABLED,\n PAGINATION_EXTRA,\n buttonClass,\n chipClass,\n filterTriggerClass,\n } from \"../../lib/classnames.ts\";\n\n (() => {\n const configSource = document.querySelector(\"#grove-index-config\");\n const listNode = document.querySelector<HTMLElement>(\"#results-list\");\n if (!configSource || !listNode) return;\n // Closures below cannot see the guard above; bind the narrowed type once.\n const list = listNode;\n\n const { slug, singular, plural, taxonomy, routePage } = JSON.parse(\n configSource.textContent || \"{}\",\n );\n // Filled by `loadRecords()`. Until then the page shows what the\n // server rendered, which for an unfiltered view is already right.\n let items: IndexRecord[] = [];\n const pathPrefix = `/${slug}`;\n\n // Cards for this page came with the document. A filtered view can\n // surface any record in the directory, so the rest are fetched\n // once from `/{slug}/page/cards/` — rendered there by the same\n // server component, which is what keeps the card to a single\n // definition instead of a second one written in JavaScript.\n const nodes = new Map<string, HTMLElement>();\n for (const node of list.querySelectorAll(\":scope > [data-record-slug]\")) {\n const key = (node as HTMLElement).dataset.recordSlug;\n if (key) nodes.set(key, node as HTMLElement);\n }\n\n // The record index — everything filtering, sorting, and facet\n // counting reads. Fetched rather than inlined so a paginated page\n // does not carry the whole directory in its HTML.\n let recordSource: Promise<void> | null = null;\n let recordsSettled = false;\n function loadRecords(): Promise<void> {\n if (!recordSource) {\n recordSource = fetch(`${pathPrefix}/page/records.json`)\n .then((response) => (response.ok ? response.json() : []))\n .then((data) => {\n items = Array.isArray(data) ? data : [];\n })\n .catch(() => {\n items = [];\n })\n .then(() => {\n // Settled either way: a failed fetch must not leave the\n // page retrying forever behind a busy list.\n recordsSettled = true;\n });\n }\n return recordSource;\n }\n\n let cardSource: Promise<void> | null = null;\n let cardsSettled = false;\n function loadAllCards(): Promise<void> {\n if (!cardSource) {\n cardSource = fetch(`${pathPrefix}/page/cards/`)\n .then((response) => (response.ok ? response.text() : \"\"))\n .then((html) => {\n if (!html) return;\n const parsed = new DOMParser().parseFromString(html, \"text/html\");\n for (const node of parsed.querySelectorAll(\"#grove-index-cards > [data-record-slug]\")) {\n const key = (node as HTMLElement).dataset.recordSlug;\n if (key && !nodes.has(key)) nodes.set(key, document.adoptNode(node) as HTMLElement);\n }\n })\n .catch(() => {\n // Offline or a stale deploy: the page keeps working with\n // the records it already has.\n })\n .then(() => {\n cardsSettled = true;\n });\n }\n return cardSource;\n }\n /** Everything a filtered view needs: the index and the cards. */\n const loadAll = () => Promise.all([loadRecords(), loadAllCards()]);\n\n // Warm on the first sign of intent — a pointer or focus reaching\n // the controls — rather than on idle. Prefetching a whole\n // directory during load competes with the page itself for\n // bandwidth on a phone, and most visitors never filter at all.\n const controls = document.querySelector(\"#search-form\")?.parentElement ?? document;\n for (const type of [\"pointerdown\", \"focusin\", \"keydown\"]) {\n controls.addEventListener(type, () => loadAll(), { once: true, passive: true });\n }\n\n let params = new URLSearchParams(location.search);\n let filters = filtersFromSearchParams(params);\n let sort = effectiveSort(filters);\n\n /**\n * True when the URL asks for something the prerendered document\n * does not already show. `hasAnyFilter` deliberately ignores\n * `sort`, but a sorted view is just as much a client view: the\n * `/page/N/` documents are all built with the default sort, so\n * paging out of `?sort=most-starred` onto one of them would\n * silently re-sort the list mid-journey.\n */\n const isClientView = () => hasAnyFilter(filters) || Boolean(filters.sort);\n\n /** Client views own the page number; prerendered ones use the path. */\n const currentPage = () => (isClientView() ? effectivePage(filters) : routePage || 1);\n\n const hrefForResultPage = (target: number) =>\n isClientView()\n ? hrefForFilters({ ...filters, page: target }, pathPrefix)\n : pagePathHref(pathPrefix, target);\n\n /** Move the page's cards into the list, in result order. */\n function renderList(visible: { slug: string }[]) {\n const next: HTMLElement[] = [];\n let missing = false;\n for (const record of visible) {\n const node = nodes.get(record.slug);\n if (node) next.push(node);\n else missing = true;\n }\n list.replaceChildren(...next);\n // A record whose card has not arrived yet: render what we have\n // and finish the moment the card source lands. Only while the\n // fetch is still outstanding — once it has settled, a missing\n // card is missing, and retrying would spin.\n if (missing && !cardsSettled) loadAllCards().then(() => applyClientFilters());\n }\n\n function applyClientFilters() {\n const filtered = applySort(filterRecords(items, filters), sort);\n const pageCount = totalPages(filtered.length);\n const page = Math.min(Math.max(1, currentPage()), pageCount);\n renderList(filtered.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE));\n\n const count = document.querySelector(\"#results-count\");\n const pageLabel = document.querySelector(\"#results-page\");\n const empty = document.querySelector(\"#empty-state\");\n if (count) count.textContent = `${filtered.length} ${filtered.length === 1 ? singular : plural}`;\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 /** Chip labels and remove hrefs come from core — one definition. */\n function renderChips() {\n const activeFilters = document.querySelector(\"#active-filters\");\n const chips = activeFilterChips(filters, { taxonomy, pathPrefix });\n if (activeFilters) {\n activeFilters.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 activeFilters.append(link);\n }\n if (chips.length) {\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 activeFilters.append(clear);\n }\n activeFilters.classList.toggle(\"hidden\", chips.length === 0);\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 const inert = count === 0 && !checked;\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 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 list.setAttribute(\"aria-busy\", \"true\");\n loadAll().then(() => {\n list.removeAttribute(\"aria-busy\");\n 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 const samePath =\n next.pathname.replace(/\\/$/, \"\") === location.pathname.replace(/\\/$/, \"\");\n if (!next.search && (!samePath || (routePage || 1) > 1)) {\n location.assign(next.toString());\n return;\n }\n const state = { grove: true, scrollY: window.scrollY };\n if (mode === \"push\") history.pushState(state, \"\", next);\n else history.replaceState(state, \"\", next);\n params = new URLSearchParams(next.search);\n filters = filtersFromSearchParams(params);\n sort = effectiveSort(filters);\n renderAll();\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 if (searchInput instanceof HTMLInputElement) searchInput.focus();\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 adopt(url, \"push\");\n });\n\n // Filtered navigation is a real step: Back returns to the\n // previous result set and its scroll position.\n //\n // Only links that carry a query are adopted. Everything else that\n // points at this list — `/{slug}/` from \"Clear all\" or the \"1\"\n // pagination link, `/{slug}/page/2/`, the header's \"Browse\" nav —\n // is a prerendered document and must actually navigate;\n // swallowing those 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 || !url.search) return;\n event.preventDefault();\n history.replaceState({ grove: true, scrollY: window.scrollY }, \"\");\n adopt(url.toString(), \"push\");\n window.scrollTo({ top: 0, behavior: \"instant\" as ScrollBehavior });\n });\n\n window.addEventListener(\"popstate\", (event) => {\n params = new URLSearchParams(location.search);\n filters = filtersFromSearchParams(params);\n sort = effectiveSort(filters);\n if (searchInput instanceof HTMLInputElement) searchInput.value = filters.q || \"\";\n document.querySelectorAll('select[name=\"sort\"]').forEach((select) => {\n if (select instanceof HTMLSelectElement) select.value = sort;\n });\n 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",
|
|
315
|
+
"content": "---\n/**\n * DirectoryIndexClient — the browse page's client controller.\n *\n * The browse routes are prerendered per page (`/{slug}/`,\n * `/{slug}/page/2/`), so the server never sees a query string. This\n * script re-reads `location.search` and re-derives results, chips,\n * facet counts, and pagination with the same `@grove-dev/core/directory`\n * functions the server used.\n *\n * Two modes, one list:\n * - **No filters** — the server-rendered page slice is already right.\n * Pagination links stay the real `/page/n/` paths.\n * - **Filtered** — the whole record set is filtered here, the page\n * re-renders from `clientItemsJson`, and pagination switches to\n * `?page=N` on the base route.\n *\n * Filters apply live. Changes made while a facet popover or the mobile\n * drawer is open replace the current history entry, and closing the\n * last one pushes a single entry (see `FilterHistorySession`), so Back\n * skips the individual checkboxes. The result count goes to a\n * debounced polite live region, and re-renders never leave keyboard\n * focus stranded on `<body>`.\n */\ninterface Props {\n slug: string;\n singular: string;\n plural: string;\n taxonomy: Record<string, unknown>;\n /** Page this route prerendered; the client starts from it. */\n routePage?: number;\n}\n\nconst { slug, singular, plural, taxonomy, routePage = 1 } = Astro.props;\nconst clientConfigJson = JSON.stringify({ slug, singular, plural, taxonomy, routePage }).replace(\n /</g,\n '\\\\u003c',\n);\n---\n\n<script is:inline id=\"grove-index-config\" type=\"application/json\" set:html={clientConfigJson}></script>\n<script>\n import type { IndexRecord } from \"@grove-dev/core\";\n import type { DirectoryFilterGroupKey } from \"@grove-dev/core/directory\";\n import {\n PAGE_SIZE,\n activeFilterChips,\n applySort,\n buildFacets,\n DIRECTORY_FILTER_KEYS,\n DIRECTORY_FILTER_LABELS,\n DIRECTORY_TAXONOMY_KINDS,\n effectivePage,\n effectiveSort,\n filterRecords,\n filtersFromSearchParams,\n hasAnyFilter,\n isDirectoryFilterGroupKey,\n hrefForClearedFilters,\n hrefForFilters,\n pagePathHref,\n paginationPageList,\n searchParamsFromFilters,\n sortDisplay,\n totalPages,\n } from \"@grove-dev/core/directory\";\n import {\n PAGINATION_DISABLED,\n PAGINATION_EXTRA,\n buttonClass,\n chipClass,\n filterTriggerClass,\n } from \"../../lib/classnames.ts\";\n import {\n FilterHistorySession,\n canAdoptInPlace,\n countLabel,\n debounce as debounced,\n focusIndexAfterRender,\n resultsAnnouncement,\n showResultsLabel,\n } from \"../../lib/live-filters.ts\";\n\n (() => {\n const configSource = document.querySelector(\"#grove-index-config\");\n const listNode = document.querySelector<HTMLElement>(\"#results-list\");\n if (!configSource || !listNode) return;\n // Closures below cannot see the guard above; bind the narrowed type once.\n const list = listNode;\n\n const { slug, singular, plural, taxonomy, routePage } = JSON.parse(\n configSource.textContent || \"{}\",\n );\n // Filled by `loadRecords()`. Until then the page shows what the\n // server rendered, which for an unfiltered view is already right.\n let items: IndexRecord[] = [];\n const pathPrefix = `/${slug}`;\n\n // Cards for this page came with the document. A filtered view can\n // surface any record in the directory, so the rest are fetched\n // once from `/{slug}/page/cards/` — rendered there by the same\n // server component, which is what keeps the card to a single\n // definition instead of a second one written in JavaScript.\n const nodes = new Map<string, HTMLElement>();\n for (const node of list.querySelectorAll(\":scope > [data-record-slug]\")) {\n const key = (node as HTMLElement).dataset.recordSlug;\n if (key) nodes.set(key, node as HTMLElement);\n }\n\n // The record index — everything filtering, sorting, and facet\n // counting reads. Fetched rather than inlined so a paginated page\n // does not carry the whole directory in its HTML.\n let recordSource: Promise<void> | null = null;\n let recordsSettled = false;\n function loadRecords(): Promise<void> {\n if (!recordSource) {\n recordSource = fetch(`${pathPrefix}/page/records.json`)\n .then((response) => (response.ok ? response.json() : []))\n .then((data) => {\n items = Array.isArray(data) ? data : [];\n })\n .catch(() => {\n items = [];\n })\n .then(() => {\n // Settled either way: a failed fetch must not leave the\n // page retrying forever behind a busy list.\n recordsSettled = true;\n });\n }\n return recordSource;\n }\n\n let cardSource: Promise<void> | null = null;\n let cardsSettled = false;\n function loadAllCards(): Promise<void> {\n if (!cardSource) {\n cardSource = fetch(`${pathPrefix}/page/cards/`)\n .then((response) => (response.ok ? response.text() : \"\"))\n .then((html) => {\n if (!html) return;\n const parsed = new DOMParser().parseFromString(html, \"text/html\");\n for (const node of parsed.querySelectorAll(\"#grove-index-cards > [data-record-slug]\")) {\n const key = (node as HTMLElement).dataset.recordSlug;\n if (key && !nodes.has(key)) nodes.set(key, document.adoptNode(node) as HTMLElement);\n }\n })\n .catch(() => {\n // Offline or a stale deploy: the page keeps working with\n // the records it already has.\n })\n .then(() => {\n cardsSettled = true;\n });\n }\n return cardSource;\n }\n /** Everything a filtered view needs: the index and the cards. */\n const loadAll = () => Promise.all([loadRecords(), loadAllCards()]);\n\n // Warm on the first sign of intent — a pointer or focus reaching\n // the controls — rather than on idle. Prefetching a whole\n // directory during load competes with the page itself for\n // bandwidth on a phone, and most visitors never filter at all.\n const controls = document.querySelector(\"#search-form\")?.parentElement ?? document;\n for (const type of [\"pointerdown\", \"focusin\", \"keydown\"]) {\n controls.addEventListener(type, () => loadAll(), { once: true, passive: true });\n }\n\n let params = new URLSearchParams(location.search);\n let filters = filtersFromSearchParams(params);\n let sort = effectiveSort(filters);\n\n /**\n * True when the URL asks for something the prerendered document\n * does not already show. `hasAnyFilter` deliberately ignores\n * `sort`, but a sorted view is just as much a client view: the\n * `/page/N/` documents are all built with the default sort, so\n * paging out of `?sort=most-starred` onto one of them would\n * silently re-sort the list mid-journey.\n */\n const isClientView = () => hasAnyFilter(filters) || Boolean(filters.sort);\n\n /** Client views own the page number; prerendered ones use the path. */\n const currentPage = () => (isClientView() ? effectivePage(filters) : routePage || 1);\n\n const heading = document.querySelector<HTMLElement>(\"#results-heading\");\n const drawerResults = document.querySelector<HTMLElement>(\"[data-drawer-results]\");\n\n // The count is announced once rapid toggles settle. One message\n // per burst, not one per checkbox.\n const status = document.querySelector(\"#results-status\");\n const announce = debounced((text: string) => {\n if (!status) return;\n // Assistive tech skips a live region whose text did not change.\n // A trailing no-break space makes a repeat count heard again.\n status.textContent = status.textContent === text ? `${text}\\u00a0` : text;\n }, 500);\n /** Set by user-driven re-renders. The first render stays silent. */\n let announceNext = false;\n\n /** Busy while a change waits on the record index. */\n function setPending(pending: boolean) {\n if (pending) list.setAttribute(\"aria-busy\", \"true\");\n else list.removeAttribute(\"aria-busy\");\n list.classList.toggle(\"opacity-60\", pending);\n if (drawerResults) {\n if (pending) {\n drawerResults.setAttribute(\"aria-busy\", \"true\");\n drawerResults.textContent = showResultsLabel(0, singular, plural, true);\n } else {\n drawerResults.removeAttribute(\"aria-busy\");\n }\n }\n }\n\n /**\n * Where focus goes when the element that had it disappears in a\n * re-render. Inside the open drawer it stays in the drawer, because\n * the page behind a modal dialog is inert. Everywhere else it goes\n * to the results heading.\n */\n function focusFallback(lost: Element | null) {\n const dialog = lost?.closest(\"dialog[open]\");\n const target = dialog\n ? dialog.querySelector<HTMLElement>(\".grove-filter-trigger, [data-drawer-close]\")\n : heading;\n target?.focus({ preventScroll: true });\n }\n\n /**\n * Run a re-render, and if it removed or hid the focused element,\n * move focus somewhere sensible instead of <body>. Focus is only\n * moved when the re-render lost it, never taken from elsewhere.\n */\n function keepingFocus(render: () => void) {\n const before = document.activeElement;\n render();\n if (!(before instanceof HTMLElement) || before === document.body) return;\n const now = document.activeElement;\n const lost =\n !before.isConnected ||\n Boolean(before.closest(\".hidden, [hidden]\")) ||\n now === null ||\n now === document.body;\n if (lost && (now === null || now === document.body || now === before)) focusFallback(before);\n }\n\n const hrefForResultPage = (target: number) =>\n isClientView()\n ? hrefForFilters({ ...filters, page: target }, pathPrefix)\n : pagePathHref(pathPrefix, target);\n\n /** Move the page's cards into the list, in result order. */\n function renderList(visible: { slug: string }[]) {\n const next: HTMLElement[] = [];\n let missing = false;\n for (const record of visible) {\n const node = nodes.get(record.slug);\n if (node) next.push(node);\n else missing = true;\n }\n list.replaceChildren(...next);\n // A record whose card has not arrived yet: render what we have\n // and finish the moment the card source lands. Only while the\n // fetch is still outstanding — once it has settled, a missing\n // card is missing, and retrying would spin.\n if (missing && !cardsSettled) loadAllCards().then(() => applyClientFilters());\n }\n\n function applyClientFilters() {\n const filtered = applySort(filterRecords(items, filters), sort);\n const pageCount = totalPages(filtered.length);\n const page = Math.min(Math.max(1, currentPage()), pageCount);\n renderList(filtered.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE));\n\n const count = document.querySelector(\"#results-count\");\n const pageLabel = document.querySelector(\"#results-page\");\n const empty = document.querySelector(\"#empty-state\");\n if (count) count.textContent = countLabel(filtered.length, singular, plural);\n if (drawerResults) drawerResults.textContent = showResultsLabel(filtered.length, singular, plural);\n if (announceNext) {\n announceNext = false;\n announce(resultsAnnouncement(filtered.length, singular, plural));\n }\n // The zero-results reset keeps the chosen sort, like \"Clear all\".\n const emptyReset = document.querySelector(\"[data-empty-reset]\");\n if (emptyReset instanceof HTMLAnchorElement) {\n emptyReset.href = hrefForClearedFilters(filters, pathPrefix);\n }\n const sortLabel = document.querySelector(\"#results-sort\");\n if (sortLabel) sortLabel.textContent = ` · sorted by ${sortDisplay(sort)}`;\n if (pageLabel) pageLabel.textContent = pageCount > 1 ? ` · page ${page} of ${pageCount}` : \"\";\n if (empty) empty.classList.toggle(\"hidden\", filtered.length > 0);\n\n // Rebuild the pagination controls, mirroring the server-rendered\n // `Pagination.astro` (Previous/Next + windowed page list via the\n // shared `paginationPageList`) so client filtering never degrades\n // the affordances of the initial render.\n const pagination = document.querySelector(\"#results-pagination\");\n if (pagination) {\n pagination.innerHTML = \"\";\n if (pageCount > 1) {\n const linkClass = buttonClass(\"secondary\", \"sm\", PAGINATION_EXTRA);\n const nav = document.createElement(\"nav\");\n nav.className = \"flex flex-wrap items-center justify-center gap-1.5\";\n nav.setAttribute(\"aria-label\", \"Pagination\");\n const control = (label: string, target: number | null, rel?: string) => {\n if (target === null) {\n const span = document.createElement(\"span\");\n span.className = `${linkClass} ${PAGINATION_DISABLED}`;\n span.textContent = label;\n return span;\n }\n const link = document.createElement(\"a\");\n link.href = hrefForResultPage(target);\n link.textContent = label;\n link.className = linkClass;\n if (rel) link.rel = rel;\n return link;\n };\n nav.append(control(\"Previous\", page > 1 ? page - 1 : null, \"prev\"));\n for (const entry of paginationPageList(page, pageCount)) {\n if (entry === \"ellipsis\") {\n const dots = document.createElement(\"span\");\n dots.className = \"px-1 text-2xs text-ink-400\";\n dots.setAttribute(\"aria-hidden\", \"true\");\n dots.textContent = \"...\";\n nav.append(dots);\n continue;\n }\n const link = control(String(entry), entry);\n link.setAttribute(\"aria-label\", `Page ${entry}`);\n if (entry === page) {\n link.setAttribute(\"aria-current\", \"page\");\n link.className = buttonClass(\"selected\", \"sm\", PAGINATION_EXTRA);\n }\n nav.append(link);\n }\n nav.append(control(\"Next\", page < pageCount ? page + 1 : null, \"next\"));\n pagination.append(nav);\n }\n }\n }\n\n const searchInput = document.querySelector(\"#search-input\");\n const searchClear = document.querySelector(\"[data-search-clear]\");\n if (searchInput instanceof HTMLInputElement) searchInput.value = filters.q || \"\";\n document.querySelectorAll('select[name=\"sort\"]').forEach((select) => {\n if (select instanceof HTMLSelectElement) select.value = sort;\n });\n\n const filterKeys = DIRECTORY_FILTER_KEYS;\n const filterLabels = DIRECTORY_FILTER_LABELS;\n const taxonomyKinds = DIRECTORY_TAXONOMY_KINDS;\n const taxonomyName = (groupKey: DirectoryFilterGroupKey, value: string) =>\n (taxonomy[taxonomyKinds[groupKey]] || []).find(\n (entry: { id: string; name: string }) => entry.id === value,\n )?.name ?? value;\n\n /**\n * Chip labels and remove hrefs come from core — one definition.\n * The same chips render in every `[data-active-filters]` row:\n * above the results, and inside the mobile filter sheet.\n */\n function renderChips() {\n const chips = activeFilterChips(filters, { taxonomy, pathPrefix });\n document.querySelectorAll<HTMLElement>(\"[data-active-filters]\").forEach((row) => {\n // Removing a chip removes the link that had focus. Remember\n // its position and give focus to whatever takes its place.\n const focused = document.activeElement;\n const focusIndex =\n focused instanceof HTMLAnchorElement && row.contains(focused)\n ? [...row.querySelectorAll(\"a\")].indexOf(focused)\n : -1;\n\n row.innerHTML = \"\";\n for (const chip of chips) {\n const link = document.createElement(\"a\");\n link.href = chip.href;\n // The whole anchor is the remove control; the visible label\n // announces the filter value, and the aria-label spells out\n // the action for assistive tech.\n link.setAttribute(\"aria-label\", `Remove filter: ${chip.label}`);\n link.className = chipClass();\n link.append(document.createTextNode(`${chip.label} `));\n const close = document.createElement(\"span\");\n close.setAttribute(\"aria-hidden\", \"true\");\n close.textContent = \"×\";\n link.append(close);\n row.append(link);\n }\n if (chips.length && !row.hasAttribute(\"data-without-clear\")) {\n const clear = document.createElement(\"a\");\n clear.href = hrefForClearedFilters(filters, pathPrefix);\n clear.className =\n \"text-2xs font-medium text-ink-500 underline decoration-border underline-offset-2 hover:text-ink-900 dark:hover:text-ink-100\";\n clear.setAttribute(\"aria-label\", \"Clear all active filters\");\n clear.textContent = \"Clear all\";\n row.append(clear);\n }\n row.classList.toggle(\"hidden\", chips.length === 0);\n\n if (focusIndex >= 0) {\n const links = row.querySelectorAll(\"a\");\n const next = focusIndexAfterRender(focusIndex, links.length);\n if (next >= 0) links[next]?.focus({ preventScroll: true });\n else focusFallback(row);\n }\n });\n\n // Mobile filter-drawer badge + its clear-all mirror the chips.\n const drawerCount = document.querySelector(\"[data-drawer-count]\");\n if (drawerCount) {\n drawerCount.textContent = String(chips.length);\n drawerCount.classList.toggle(\"hidden\", chips.length === 0);\n }\n const drawerClear = document.querySelector(\"[data-drawer-clear]\");\n if (drawerClear instanceof HTMLAnchorElement) {\n drawerClear.href = hrefForClearedFilters(filters, pathPrefix);\n drawerClear.classList.toggle(\"hidden\", chips.length === 0);\n }\n }\n\n function renderFilterTriggers() {\n const values = (key: string) => params.getAll(key).filter(Boolean);\n document.querySelectorAll(\".grove-filter\").forEach((group) => {\n if (!(group instanceof HTMLElement)) return;\n const groupKey = group.dataset.filterGroupKey;\n if (!groupKey || !isDirectoryFilterGroupKey(groupKey)) return;\n const selected = values(filterKeys[groupKey]);\n group.querySelectorAll(\".grove-filter-input\").forEach((input) => {\n if (input instanceof HTMLInputElement) {\n input.checked = selected.includes(input.dataset.filterValue || \"\");\n }\n });\n const triggerButton = group.querySelector(\".grove-filter-trigger\");\n const trigger = triggerButton?.querySelector(\"span\");\n const label = filterLabels[groupKey];\n if (trigger) {\n trigger.textContent = selected.length\n ? `${label}: ${\n selected.length === 1\n ? taxonomyName(groupKey, selected[0] ?? \"\")\n : `${selected.length} selected`\n }`\n : `${label}: Any`;\n }\n if (triggerButton) {\n // Same builder the server render used — the class string is\n // reassigned wholesale so the two can never drift.\n triggerButton.className = filterTriggerClass(selected.length > 0);\n }\n group.querySelector(\".grove-filter-clear\")?.classList.toggle(\"hidden\", selected.length === 0);\n });\n }\n\n // Facet counts were rendered at build time from the UNFILTERED\n // record set (the route is prerendered, so the server never sees\n // the live query string). Recompute intersection counts against\n // the current filters and patch each count span in place —\n // never re-render the option lists, which would destroy\n // checkbox, focus, and scroll state.\n function renderFacetCounts() {\n const liveFacets: Record<string, { value: string; count: number }[]> = buildFacets(items, {\n filters,\n curatedTagIds: (taxonomy.topics || []).map((topic: { id: string }) => topic.id),\n });\n document.querySelectorAll(\"[data-facet-count]\").forEach((span) => {\n if (!(span instanceof HTMLElement)) return;\n const options = liveFacets[span.dataset.facet ?? \"\"] ?? [];\n const count = options.find((option) => option.value === span.dataset.value)?.count ?? 0;\n span.textContent = String(count);\n const row = span.closest(\"label\");\n const input = row?.querySelector(\".grove-filter-input\");\n const checked = input instanceof HTMLInputElement && input.checked;\n // A zero-count option can't narrow anything — dim and disable\n // it unless it's the currently selected value (which must stay\n // interactive so the user can un-select it).\n // The focused option is never disabled under the user; that\n // would drop keyboard focus to <body>.\n const inert = count === 0 && !checked && input !== document.activeElement;\n row?.classList.toggle(\"opacity-45\", inert);\n if (input instanceof HTMLInputElement) input.disabled = inert;\n });\n }\n\n function renderAll() {\n renderChips();\n renderFilterTriggers();\n if (searchClear instanceof HTMLElement) searchClear.hidden = !(filters.q || \"\").length;\n\n if (recordsSettled) {\n renderFacetCounts();\n applyClientFilters();\n setPending(false);\n return;\n }\n // Nothing to filter with yet. A plain view of this page is\n // already correct as the server rendered it; anything the URL\n // asks for beyond that — a filter, a search, a sort — waits for\n // the index and the cards, and says so while it does.\n if (!isClientView()) return;\n setPending(true);\n loadAll().then(() => {\n setPending(false);\n keepingFocus(renderAll);\n });\n }\n\n /**\n * Adopt a URL without a navigation, then re-render from it.\n *\n * A URL with no query is a prerendered document — clearing the\n * last filter lands on `/{slug}/`, which on page 2+ is a\n * *different* document than the one on screen. Adopting it there\n * would leave records 21–40 rendered under the page-1 URL, so\n * that case navigates for real.\n */\n function adopt(url: string, mode: \"push\" | \"replace\") {\n const next = new URL(url, location.origin);\n if (!canAdoptInPlace(next, location.pathname, routePage || 1)) {\n location.assign(next.toString());\n return;\n }\n const state = { grove: true, scrollY: window.scrollY };\n // Re-selecting the URL already on screen (the header's Browse\n // link on an unfiltered page 1) must not add a Back step.\n if (mode === \"push\" && next.href !== location.href) history.pushState(state, \"\", next);\n else history.replaceState(state, \"\", next);\n params = new URLSearchParams(next.search);\n filters = filtersFromSearchParams(params);\n sort = effectiveSort(filters);\n // A chip, \"Clear all\" or the zero-results reset can drop the\n // query. Keep the box in step, but never rewrite it while the\n // user is typing in it.\n if (searchInput instanceof HTMLInputElement && document.activeElement !== searchInput) {\n searchInput.value = filters.q || \"\";\n }\n announceNext = true;\n keepingFocus(renderAll);\n }\n\n /** The current URL as the history session compares it. */\n const here = () => `${location.pathname}${location.search}`;\n\n // One history entry per filter session. A popover or the drawer\n // opening starts a session. While it is open, changes replace the\n // current entry. When the last surface closes, the starting URL is\n // put back on this entry and the final URL is pushed once.\n const session = new FilterHistorySession();\n document.addEventListener(\"grove:filter-surface\", (event) => {\n const detail = (event as CustomEvent<{ surface: string; open: boolean }>).detail;\n if (!detail?.surface) return;\n if (detail.open) {\n session.open(detail.surface, { url: here(), scrollY: window.scrollY });\n return;\n }\n const commit = session.close(detail.surface, here());\n if (!commit) return;\n history.replaceState({ grove: true, scrollY: commit.start.scrollY }, \"\", commit.start.url);\n history.pushState({ grove: true, scrollY: window.scrollY }, \"\", commit.end);\n });\n\n // Search filters as you type. `replaceState` keeps a search\n // session out of the history stack — Back should return to the\n // previous result set, not to the previous keystroke.\n let debounce = 0;\n searchInput?.addEventListener(\"input\", () => {\n window.clearTimeout(debounce);\n debounce = window.setTimeout(() => {\n const query = searchInput instanceof HTMLInputElement ? searchInput.value.trim() : \"\";\n adopt(hrefForFilters({ ...filters, q: query || undefined, page: 1 }, pathPrefix), \"replace\");\n // Only reclaim focus when the re-render dropped it. If the\n // user has already moved on (tabbed to a filter) focus stays\n // where they put it.\n if (searchInput instanceof HTMLInputElement && document.activeElement === document.body) {\n searchInput.focus();\n }\n }, 150);\n });\n searchClear?.addEventListener(\"click\", () => {\n if (searchInput instanceof HTMLInputElement) {\n searchInput.value = \"\";\n searchInput.focus();\n }\n adopt(hrefForFilters({ ...filters, q: undefined, page: 1 }, pathPrefix), \"replace\");\n });\n document.querySelector(\"#search-form\")?.addEventListener(\"submit\", (event) => {\n // Enter already has its answer on screen; submitting would only\n // reload the same state.\n event.preventDefault();\n });\n\n // RefinePanel asks before it navigates; cancelling means \"this\n // page can apply the URL in place\".\n document.addEventListener(\"grove:navigate\", (event) => {\n const url = (event as CustomEvent<{ url: string }>).detail?.url;\n if (!url) return;\n event.preventDefault();\n // Inside an open popover or drawer, replace; the session pushes\n // once on close. Outside one (the sort select), push.\n adopt(url, session.modeForChange());\n });\n\n // Filtered navigation is a real step: Back returns to the\n // previous result set and its scroll position.\n //\n // Links that carry a query are adopted. A link to the bare list\n // (`/{slug}/` from \"Clear all\", the last chip, or the \"1\"\n // pagination link) is adopted only from page 1 of that list,\n // where it is the document already on screen. That keeps focus and\n // an open filter drawer in place. From `/{slug}/page/2/` it is a\n // different prerendered document and must actually navigate.\n // Swallowing it there left page 2's records rendered under the\n // page-1 URL. Hash links (the skip link) are never ours.\n document.addEventListener(\"click\", (event) => {\n const link = (event.target as HTMLElement | null)?.closest(\"a\");\n if (!(link instanceof HTMLAnchorElement)) return;\n if (event.defaultPrevented || event.metaKey || event.ctrlKey || event.shiftKey) return;\n if (link.target === \"_blank\" || !link.href.startsWith(location.origin)) return;\n const url = new URL(link.href);\n if (url.hash) return;\n const isListUrl = url.pathname === `${pathPrefix}/` || url.pathname === pathPrefix;\n if (!isListUrl || !canAdoptInPlace(url, location.pathname, routePage || 1)) return;\n event.preventDefault();\n // A chip removed inside the open drawer is part of that filter\n // session. It replaces, and the page does not jump under the sheet.\n if (session.active) {\n adopt(url.toString(), \"replace\");\n return;\n }\n history.replaceState({ grove: true, scrollY: window.scrollY }, \"\");\n adopt(url.toString(), \"push\");\n window.scrollTo({ top: 0, behavior: \"instant\" as ScrollBehavior });\n });\n\n window.addEventListener(\"popstate\", (event) => {\n params = new URLSearchParams(location.search);\n filters = filtersFromSearchParams(params);\n sort = effectiveSort(filters);\n if (searchInput instanceof HTMLInputElement) searchInput.value = filters.q || \"\";\n document.querySelectorAll('select[name=\"sort\"]').forEach((select) => {\n if (select instanceof HTMLSelectElement) select.value = sort;\n });\n // Back/Forward with a popover or the drawer still open: this\n // entry becomes where that session started.\n session.rebase({ url: here(), scrollY: window.scrollY });\n announceNext = true;\n keepingFocus(renderAll);\n const state = event.state as { scrollY?: number } | null;\n if (typeof state?.scrollY === \"number\") {\n window.scrollTo({ top: state.scrollY, behavior: \"instant\" as ScrollBehavior });\n }\n });\n\n renderAll();\n })();\n</script>\n",
|
|
316
316
|
"type": "registry:component",
|
|
317
317
|
"target": "~/src/components/grove/directory-index-client.astro"
|
|
318
318
|
},
|
|
319
319
|
{
|
|
320
320
|
"path": "default/components/grove/refine-panel.astro",
|
|
321
|
-
"content": "---\nimport type { IndexFilters } from '@grove-dev/core';\n/**\n * RefinePanel — multi-select facet dropdowns.\n *\n * Renders the ordered `groups` view-model produced by\n * `getDirectoryIndexModel().facetGroups` — visibility, ORDER, display\n * label, and selection mode all come from `browse.facets` + the core\n * facet registry, never from this component. Option labels arrive\n * pre-resolved from the taxonomy YAML, so the server render and the\n * client script share one label source.\n *\n * The
|
|
321
|
+
"content": "---\nimport type { IndexFilters } from '@grove-dev/core';\n/**\n * RefinePanel — multi-select facet dropdowns.\n *\n * Renders the ordered `groups` view-model produced by\n * `getDirectoryIndexModel().facetGroups` — visibility, ORDER, display\n * label, and selection mode all come from `browse.facets` + the core\n * facet registry, never from this component. Option labels arrive\n * pre-resolved from the taxonomy YAML, so the server render and the\n * client script share one label source.\n *\n * The URL is the list page base with each facet as a repeated key.\n * Empty values are dropped, so the URL stays clean.\n *\n * Filters apply live. Each checkbox or radio change builds the new\n * URL and asks the page to adopt it, and the popover stays open.\n * There is no Apply step.\n */\nimport { SORT_OPTIONS } from '@grove-dev/core';\nimport FilterGroupMenu from './filter-group-menu.astro';\n\ninterface FacetValue {\n value: string;\n label?: string;\n count?: number;\n}\n\ninterface FacetGroupModel {\n id: string;\n filterKey: 'stacks' | 'platforms' | 'categories' | 'tags' | 'licenses';\n label: string;\n single?: boolean;\n options: FacetValue[];\n initial: string[];\n}\n\ninterface Props {\n /** Ordered filter groups (see `getDirectoryIndexModel`). */\n groups: FacetGroupModel[];\n /** Current URL filter state — used to preselect the sort. */\n initial: IndexFilters;\n pathPrefix?: string;\n class?: string;\n /**\n * Emit the default flex layout on the root. Pass `false` when the\n * caller owns the layout — e.g. `layout={false} class=\"contents\"` to\n * promote the filter triggers into the parent's flex row. Without\n * this the root's own `flex` would win over any display utility in\n * `class`, since Tailwind emits `.contents` before `.flex`.\n */\n layout?: boolean;\n /** Hide the sort select (e.g. when the page renders its own). */\n hide?: Array<'sort'>;\n}\n\nconst {\n groups: groupModels,\n initial,\n pathPrefix = '/',\n class: className = '',\n layout = true,\n hide = [],\n} = Astro.props;\n\nfunction triggerLabel(group: FacetGroupModel): string {\n if (group.initial.length === 0) return `${group.label}: Any`;\n if (group.initial.length === 1) {\n const selected = group.initial[0];\n const option = group.options.find((candidate) => candidate.value === selected);\n return `${group.label}: ${option?.label ?? selected}`;\n }\n return `${group.label}: ${group.initial.length} selected`;\n}\n\nconst groups = groupModels.map((group) => ({\n ...group,\n active: group.initial.length > 0,\n popoverId: `filter-popover-${group.filterKey}`,\n trigger: triggerLabel(group),\n}));\n---\n\n<div\n class:list={[layout && \"flex flex-wrap items-center gap-2\", className]}\n role=\"toolbar\"\n aria-label=\"Filter items\"\n data-refine-panel\n data-path-prefix={pathPrefix}\n>\n {groups.map((group) => <FilterGroupMenu {...group} />)}\n\n {!hide.includes(\"sort\") && (\n <label class=\"relative\">\n <span class=\"sr-only\">Sort items</span>\n <select name=\"sort\" class=\"h-9 cursor-pointer appearance-none border py-1.5 pl-3 pr-8 text-[0.8125rem] font-medium\">\n {SORT_OPTIONS.map((option) => <option value={option.value} selected={(initial.sort ?? \"recently-updated\") === option.value}>{option.label}</option>)}\n </select>\n <svg viewBox=\"0 0 16 16\" width=\"11\" height=\"11\" aria-hidden=\"true\" class=\"pointer-events-none absolute right-2.5 top-1/2 -translate-y-1/2 text-ink-400\" fill=\"currentColor\">\n <path d=\"M4.22 6.22a.75.75 0 0 1 1.06 0L8 8.94l2.72-2.72a.75.75 0 1 1 1.06 1.06l-3.25 3.25a.75.75 0 0 1-1.06 0L4.22 7.28a.75.75 0 0 1 0-1.06Z\"/>\n </svg>\n </label>\n )}\n</div>\n\n<script>\n import { DIRECTORY_FILTER_KEYS, isDirectoryFilterGroupKey } from \"@grove-dev/core/directory\";\n import { hrefForGroupSelection } from \"../../lib/live-filters.ts\";\n\n document.querySelectorAll<HTMLElement>(\"[data-refine-panel]\").forEach((panel) => {\n const pathPrefix = panel.dataset.pathPrefix || \"/\";\n const groups = [...panel.querySelectorAll<HTMLElement>(\".grove-filter\")];\n const parts = (group: HTMLElement) => ({\n trigger: group.querySelector<HTMLButtonElement>(\".grove-filter-trigger\"),\n popover: group.querySelector<HTMLElement>(\".grove-filter-popover\"),\n });\n const isOpen = (group: HTMLElement) =>\n parts(group).trigger?.getAttribute(\"aria-expanded\") === \"true\";\n\n // Tell the page when a popover opens or closes. DirectoryIndexClient\n // uses this to replace history entries while a popover is open and\n // push one entry when it closes.\n function setOpen(group: HTMLElement, open: boolean) {\n const { trigger, popover } = parts(group);\n if (!trigger || !popover || isOpen(group) === open) return;\n popover.hidden = !open;\n popover.classList.toggle(\"hidden\", !open);\n trigger.setAttribute(\"aria-expanded\", String(open));\n document.dispatchEvent(\n new CustomEvent(\"grove:filter-surface\", {\n detail: { surface: `popover:${group.dataset.filterGroupKey}`, open },\n }),\n );\n }\n function closeAll(except?: HTMLElement) {\n for (const group of groups) if (group !== except) setOpen(group, false);\n }\n\n // A directory controller (DirectoryIndexClient) can adopt the URL\n // in place and re-render without a reload. It signals that by\n // cancelling the event. Anywhere else (a taxonomy page, or no\n // controller on the page) this falls back to navigating, so the\n // panel still works on its own.\n function go(url: string) {\n const event = new CustomEvent(\"grove:navigate\", { detail: { url }, cancelable: true });\n if (document.dispatchEvent(event)) location.assign(url);\n }\n function navigate(group: HTMLElement, values: string[]) {\n const groupKey = group.dataset.filterGroupKey ?? \"\";\n if (!isDirectoryFilterGroupKey(groupKey)) return;\n go(hrefForGroupSelection(location.search, pathPrefix, DIRECTORY_FILTER_KEYS[groupKey], values));\n }\n const checkedValues = (group: HTMLElement) =>\n [...group.querySelectorAll<HTMLInputElement>(\".grove-filter-input:checked\")].map(\n (input) => input.dataset.filterValue ?? \"\",\n );\n\n for (const group of groups) {\n const { trigger, popover } = parts(group);\n trigger?.addEventListener(\"click\", (event) => {\n event.stopPropagation();\n const opening = !isOpen(group);\n closeAll(opening ? group : undefined);\n setOpen(group, opening);\n });\n // Live: every change applies at once and the popover stays open,\n // so the next choice is one click away and the results behind it\n // show what the last one did.\n group.querySelectorAll<HTMLInputElement>(\".grove-filter-input\").forEach((input) => {\n input.addEventListener(\"change\", () => navigate(group, checkedValues(group)));\n });\n group.querySelector(\".grove-filter-clear\")?.addEventListener(\"click\", () => {\n navigate(group, []);\n // The Clear button hides once its group is empty. Keep keyboard\n // focus in the popover rather than letting it drop to <body>.\n group.querySelector<HTMLInputElement>(\".grove-filter-input:not(:disabled)\")?.focus();\n });\n popover?.addEventListener(\"click\", (event) => event.stopPropagation());\n }\n document.addEventListener(\"click\", () => closeAll());\n document.addEventListener(\"keydown\", (event) => {\n if (event.key !== \"Escape\") return;\n const openGroup = groups.find(isOpen);\n if (!openGroup) return;\n // Escape closes the popover only. Inside the mobile drawer it\n // must not also close the drawer, so the default is cancelled.\n event.preventDefault();\n closeAll();\n // Put focus back on the trigger so keyboard users keep their place.\n parts(openGroup).trigger?.focus();\n });\n document.querySelector<HTMLSelectElement>('select[name=\"sort\"]')?.addEventListener(\"change\", (event) => {\n const params = new URLSearchParams(location.search);\n params.set(\"sort\", (event.target as HTMLSelectElement).value);\n params.delete(\"page\");\n go(params.toString() ? `${pathPrefix}?${params}` : pathPrefix);\n });\n });\n</script>\n",
|
|
322
322
|
"type": "registry:component",
|
|
323
323
|
"target": "~/src/components/grove/refine-panel.astro"
|
|
324
324
|
},
|
|
325
325
|
{
|
|
326
326
|
"path": "default/components/grove/filter-group-menu.astro",
|
|
327
|
-
"content": "---\nimport {
|
|
327
|
+
"content": "---\nimport { filterTriggerClass } from '../../lib/classnames.ts';\nimport FilterOptions from './filter-options.astro';\n\ninterface FacetValue {\n value: string;\n label?: string;\n count?: number;\n}\n\ninterface Props {\n label: string;\n filterKey: string;\n options: FacetValue[];\n initial: string[];\n single?: boolean;\n active: boolean;\n popoverId: string;\n trigger: string;\n}\n\nconst group = Astro.props;\n---\n\n<div class=\"grove-filter relative\" data-filter-group-key={group.filterKey} data-filter-single={group.single ? \"true\" : \"false\"}>\n <button\n type=\"button\"\n class={filterTriggerClass(group.active)}\n aria-expanded=\"false\"\n aria-controls={group.popoverId}\n >\n <span>{group.trigger}</span>\n <svg viewBox=\"0 0 16 16\" width=\"11\" height=\"11\" aria-hidden=\"true\" fill=\"currentColor\" class=\"opacity-70\">\n <path d=\"M4.22 6.22a.75.75 0 0 1 1.06 0L8 8.94l2.72-2.72a.75.75 0 1 1 1.06 1.06l-3.25 3.25a.75.75 0 0 1-1.06 0L4.22 7.28a.75.75 0 0 1 0-1.06Z\"/>\n </svg>\n </button>\n {/* A group of native checkboxes/radios — the old listbox role over\n label/input children had no valid accessibility tree. */}\n <div\n id={group.popoverId}\n class=\"rounded-[calc(var(--radius)+0.25rem)] border border-border bg-popover text-popover-foreground shadow-xl grove-filter-popover absolute left-0 top-full z-40 mt-1 hidden w-72 max-w-[calc(100vw-2rem)] p-1.5\"\n role=\"group\"\n aria-label={`${group.label} filters`}\n hidden\n >\n <FilterOptions filterKey={group.filterKey} options={group.options} initial={group.initial} single={group.single} />\n {/* Every change applies the moment it happens (see RefinePanel), so\n there is no Apply button. The footer only holds \"Clear\", and it\n hides itself while Clear is hidden. The client script toggles\n Clear's `hidden` class from the live URL state. */}\n <div\n class=\"mt-1 flex items-center justify-between border-t border-ink-100 px-2 pt-1.5 has-[.grove-filter-clear.hidden]:hidden dark:border-ink-900\"\n >\n <button\n type=\"button\"\n class:list={[\n \"grove-filter-clear text-2xs font-medium text-ink-500 hover:text-ink-900 dark:text-ink-400 dark:hover:text-ink-100\",\n !group.active && \"hidden\",\n ]}\n >Clear {group.label.toLowerCase()}</button>\n </div>\n </div>\n</div>\n",
|
|
328
328
|
"type": "registry:component",
|
|
329
329
|
"target": "~/src/components/grove/filter-group-menu.astro"
|
|
330
330
|
},
|
|
@@ -352,6 +352,12 @@
|
|
|
352
352
|
"type": "registry:component",
|
|
353
353
|
"target": "~/src/components/grove/index-row.astro"
|
|
354
354
|
},
|
|
355
|
+
{
|
|
356
|
+
"path": "default/lib/live-filters.ts",
|
|
357
|
+
"content": "/**\n * Live-filter logic for the browse page. These are the pieces of\n * behaviour that do not need a DOM: URL building, the history-session\n * decision, the labels the page speaks, a debounce and the focus\n * fallback index.\n *\n * They live here, not inline in the `.astro` scripts, so they can be\n * unit-tested. RefinePanel, FilterDrawer and DirectoryIndexClient\n * import them.\n */\n\n/**\n * URL for one facet group's new selection. Every other parameter in\n * `search` is kept, so the query, other groups, sort and lens survive.\n * The group's key is rewritten and `page` is dropped, because a\n * different result set starts on page 1.\n *\n * This is the same URL shape the page has always used: a repeated key\n * per value. Existing links keep working.\n */\nexport function hrefForGroupSelection(\n search: string,\n pathPrefix: string,\n paramKey: string,\n values: readonly string[],\n): string {\n const params = new URLSearchParams(search);\n params.delete(paramKey);\n params.delete('page');\n for (const value of values) if (value) params.append(paramKey, value);\n const query = params.toString();\n return query ? `${pathPrefix}?${query}` : pathPrefix;\n}\n\n/**\n * Whether the browse page can show `target` in place, or must really\n * navigate to it.\n *\n * A URL with a query is always a client view of the list, so it can\n * be shown in place. A URL with no query is a prerendered document.\n * On page 1 of the same list that is the document already on screen,\n * so clearing the last filter can still happen in place, keeping focus\n * and an open drawer. From `/{slug}/page/2/`, or for a different path,\n * it is a different document and has to load for real. Otherwise page\n * 2's records would sit under the page-1 URL.\n */\nexport function canAdoptInPlace(\n target: { pathname: string; search: string },\n currentPathname: string,\n routePage: number,\n): boolean {\n if (target.search) return true;\n const strip = (path: string) => path.replace(/\\/$/, '');\n return strip(target.pathname) === strip(currentPathname) && routePage <= 1;\n}\n\n/** What a filter change does to the history stack. */\nexport type HistoryMode = 'push' | 'replace';\n\n/** Where the history stood when a filter session opened. */\nexport interface HistorySnapshot {\n url: string;\n scrollY: number;\n}\n\n/**\n * The history entries a closing session has to write: put `start` back\n * on the current entry, then push `end`.\n */\nexport interface HistoryCommit {\n start: HistorySnapshot;\n end: string;\n}\n\n/**\n * One \"filter session\": the time a filter surface (a facet popover or\n * the mobile drawer) is open.\n *\n * While a session is open, each change replaces the current history\n * entry, so ticking five checkboxes does not leave five Back steps.\n * When the last surface closes and the URL has changed, the caller\n * restores the starting URL on the current entry and pushes the final\n * one. That is one pushState per session, and Back goes to the result\n * set from before the session.\n *\n * Surfaces nest: a popover can open inside the drawer. The session\n * only ends when every surface has closed.\n */\nexport class FilterHistorySession {\n #open = new Set<string>();\n #start: HistorySnapshot | null = null;\n\n /** True while at least one filter surface is open. */\n get active(): boolean {\n return this.#open.size > 0;\n }\n\n /** A surface opened. The first one records where history stood. */\n open(surface: string, snapshot: HistorySnapshot): void {\n if (this.#open.size === 0) this.#start = snapshot;\n this.#open.add(surface);\n }\n\n /** How a filter change made now should write to history. */\n modeForChange(): HistoryMode {\n return this.active ? 'replace' : 'push';\n }\n\n /**\n * A surface closed. Returns the commit to write when this ended the\n * session and the URL changed during it. Otherwise returns `null`:\n * another surface is still open, the surface was not open, or\n * nothing changed.\n */\n close(surface: string, currentUrl: string): HistoryCommit | null {\n if (!this.#open.delete(surface) || this.#open.size > 0) return null;\n const start = this.#start;\n this.#start = null;\n if (!start || sameUrl(start.url, currentUrl)) return null;\n return { start, end: currentUrl };\n }\n\n /**\n * Back/Forward moved to another entry while a surface was open. The\n * new entry becomes the session's starting point: later changes\n * replace it, and closing pushes one entry after it. When no session\n * is open this does nothing.\n */\n rebase(snapshot: HistorySnapshot): void {\n if (this.active) this.#start = snapshot;\n }\n}\n\n/** Compare two same-origin URLs, ignoring a trailing slash on the path. */\nfunction sameUrl(a: string, b: string): boolean {\n const left = new URL(a, 'https://grove.invalid');\n const right = new URL(b, 'https://grove.invalid');\n const path = (url: URL) => url.pathname.replace(/\\/$/, '');\n return path(left) === path(right) && left.search === right.search;\n}\n\n/** `1 app`, `12 apps`. */\nexport function countLabel(count: number, singular: string, plural: string): string {\n return `${count} ${count === 1 ? singular : plural}`;\n}\n\n/**\n * What the polite live region says after the results change. It is a\n * whole sentence because a screen reader hears it without the visible\n * heading around it.\n */\nexport function resultsAnnouncement(count: number, singular: string, plural: string): string {\n if (count === 0) return `No ${plural} match these filters.`;\n return `${countLabel(count, singular, plural)} found.`;\n}\n\n/**\n * Label for the mobile drawer's results button. The button shows the\n * results. It does not apply anything, because every change has\n * already applied.\n */\nexport function showResultsLabel(\n count: number,\n singular: string,\n plural: string,\n pending = false,\n): string {\n if (pending) return 'Updating results…';\n if (count === 0) return `No ${plural} match`;\n return `Show ${countLabel(count, singular, plural)}`;\n}\n\n/** A trailing-edge debounce that can also be cancelled. */\nexport interface Debounced<Args extends unknown[]> {\n (...args: Args): void;\n cancel(): void;\n}\n\nexport function debounce<Args extends unknown[]>(\n fn: (...args: Args) => void,\n wait: number,\n): Debounced<Args> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const debounced = (...args: Args) => {\n if (timer !== undefined) clearTimeout(timer);\n timer = setTimeout(() => {\n timer = undefined;\n fn(...args);\n }, wait);\n };\n debounced.cancel = () => {\n if (timer !== undefined) clearTimeout(timer);\n timer = undefined;\n };\n return debounced;\n}\n\n/**\n * When a list re-renders under a focused item (for example, removing\n * the focused chip), this picks which item gets focus next. The answer\n * is the item that took the old one's place, or the new last item.\n * Returns `-1` when the list is empty and the caller has to fall back\n * to something else.\n */\nexport function focusIndexAfterRender(previousIndex: number, length: number): number {\n if (length <= 0) return -1;\n return Math.min(Math.max(previousIndex, 0), length - 1);\n}\n",
|
|
358
|
+
"type": "registry:file",
|
|
359
|
+
"target": "~/src/lib/live-filters.ts"
|
|
360
|
+
},
|
|
355
361
|
{
|
|
356
362
|
"path": "default/pages/[slug]/[recordSlug].astro",
|
|
357
363
|
"content": "---\n/**\n * Detail page — thin consumer wiring up the package's\n * RecordHeader, EditorialSummary, TableOfContents, MarkdownBody,\n * and RecordSidebar components. All rendering logic, prose\n * styling, sidebar visibility, and activity-badge rules live in\n * `@grove-dev/astro`; this file only composes them.\n */\nimport records from '@grove/generated/records.json';\nimport siteConfig from '@grove/generated/site-config.json';\nimport {\n getRecordContextModel,\n getRecordDetailModel,\n loadCollections,\n recordDetailPaths,\n recordsToCollectionEntries,\n} from '@grove-dev/astro/server';\nimport EditorialSummary from '../../components/grove/editorial-summary.astro';\nimport MarkdownBody from '../../components/grove/markdown-body.astro';\nimport RecordHeader from '../../components/grove/record-header.astro';\nimport RecordRelations from '../../components/grove/record-relations.astro';\nimport RecordSidebar from '../../components/grove/record-sidebar.astro';\nimport RelatedRecords from '../../components/grove/related-records.astro';\nimport TableOfContents from '../../components/grove/table-of-contents.astro';\nimport BaseLayout from '../../layouts/base-layout.astro';\n\nexport function getStaticPaths() {\n return recordDetailPaths(siteConfig);\n}\n\nconst dirSlug = siteConfig.blueprintConfig?.routeSlug ?? 'projects';\nconst detail = getRecordDetailModel(\n Astro.params.recordSlug ?? '',\n siteConfig,\n Astro.params.slug ?? dirSlug,\n);\nif (!detail) return Astro.redirect(`/${dirSlug}`);\nconst { record, itemSingular, seo } = detail;\n\n// Where this page links out to: subject hubs, sibling records, and the\n// collections the record appears in.\nconst context = getRecordContextModel(record, {\n collections: await loadCollections(process.cwd()),\n entries: recordsToCollectionEntries(\n (records as { records: unknown[] }).records as never,\n siteConfig,\n ),\n subjects: siteConfig.taxonomy?.subjects ?? [],\n});\n---\n\n<BaseLayout\n title={seo.title}\n description={seo.description}\n image={seo.image}\n imageAlt={seo.imageAlt}\n site={siteConfig}\n type=\"article\"\n jsonLd={seo.jsonLd}\n submitHref=\"/submit\"\n submitLabel={`Submit ${itemSingular}`}\n>\n <article class=\"py-8 sm:py-10\">\n <div class=\"mx-auto w-full max-w-container px-5 sm:px-7\">\n <RecordHeader detail={detail} />\n <RecordRelations relations={context.relations} />\n\n <div\n class=\"grid grid-cols-1 gap-10 lg:grid-cols-[minmax(0,1fr)_300px] lg:gap-12\"\n >\n {/* Reading column: editorial context, then the article —\n no TOC panel pushing the body down. */}\n <div class=\"min-w-0\">\n <EditorialSummary\n bestFor={detail.bestFor}\n caveats={detail.caveats}\n whyListed={detail.whyListed}\n />\n <MarkdownBody\n recordSlug={record.slug}\n fallback={record.content ? \"This record doesn't have notes yet.\" : undefined}\n />\n </div>\n {/* Right rail: the TOC and nothing else. */}\n <div class=\"min-w-0 lg:sticky lg:top-20 lg:max-h-[calc(100vh-5rem)] lg:self-start lg:overflow-y-auto\">\n <TableOfContents items={detail.toc} />\n </div>\n </div>\n\n <RelatedRecords context={context} />\n\n {/* Metadata panels — full width below the article. */}\n <section class=\"mt-12 border-t border-border pt-8\" aria-label=\"Project details\">\n <RecordSidebar detail={detail} sticky={false} layout=\"grid\" />\n </section>\n </div>\n </article>\n</BaseLayout>\n",
|
|
@@ -445,7 +451,7 @@
|
|
|
445
451
|
],
|
|
446
452
|
"meta": {
|
|
447
453
|
"version": "1.3.0",
|
|
448
|
-
"requiresGrove": "0.
|
|
454
|
+
"requiresGrove": "0.13.0"
|
|
449
455
|
},
|
|
450
456
|
"type": "registry:block"
|
|
451
457
|
}
|
package/dist/r/home.json
CHANGED
package/dist/r/not-found.json
CHANGED
package/dist/r/project-card.json
CHANGED
package/dist/r/record.json
CHANGED
package/dist/r/registry.json
CHANGED
|
@@ -47,7 +47,7 @@
|
|
|
47
47
|
],
|
|
48
48
|
"meta": {
|
|
49
49
|
"version": "1.3.0",
|
|
50
|
-
"requiresGrove": "0.
|
|
50
|
+
"requiresGrove": "0.13.0"
|
|
51
51
|
}
|
|
52
52
|
},
|
|
53
53
|
{
|
|
@@ -113,7 +113,7 @@
|
|
|
113
113
|
],
|
|
114
114
|
"meta": {
|
|
115
115
|
"version": "1.3.0",
|
|
116
|
-
"requiresGrove": "0.
|
|
116
|
+
"requiresGrove": "0.13.0"
|
|
117
117
|
}
|
|
118
118
|
},
|
|
119
119
|
{
|
|
@@ -155,7 +155,7 @@
|
|
|
155
155
|
],
|
|
156
156
|
"meta": {
|
|
157
157
|
"version": "1.3.0",
|
|
158
|
-
"requiresGrove": "0.
|
|
158
|
+
"requiresGrove": "0.13.0"
|
|
159
159
|
}
|
|
160
160
|
},
|
|
161
161
|
{
|
|
@@ -212,7 +212,7 @@
|
|
|
212
212
|
],
|
|
213
213
|
"meta": {
|
|
214
214
|
"version": "1.3.0",
|
|
215
|
-
"requiresGrove": "0.
|
|
215
|
+
"requiresGrove": "0.13.0"
|
|
216
216
|
}
|
|
217
217
|
},
|
|
218
218
|
{
|
|
@@ -264,7 +264,7 @@
|
|
|
264
264
|
],
|
|
265
265
|
"meta": {
|
|
266
266
|
"version": "1.3.0",
|
|
267
|
-
"requiresGrove": "0.
|
|
267
|
+
"requiresGrove": "0.13.0"
|
|
268
268
|
}
|
|
269
269
|
},
|
|
270
270
|
{
|
|
@@ -323,7 +323,7 @@
|
|
|
323
323
|
],
|
|
324
324
|
"meta": {
|
|
325
325
|
"version": "1.3.0",
|
|
326
|
-
"requiresGrove": "0.
|
|
326
|
+
"requiresGrove": "0.13.0"
|
|
327
327
|
}
|
|
328
328
|
},
|
|
329
329
|
{
|
|
@@ -396,11 +396,16 @@
|
|
|
396
396
|
"path": "default/components/grove/index-row.astro",
|
|
397
397
|
"type": "registry:component",
|
|
398
398
|
"target": "~/src/components/grove/index-row.astro"
|
|
399
|
+
},
|
|
400
|
+
{
|
|
401
|
+
"path": "default/lib/live-filters.ts",
|
|
402
|
+
"type": "registry:file",
|
|
403
|
+
"target": "~/src/lib/live-filters.ts"
|
|
399
404
|
}
|
|
400
405
|
],
|
|
401
406
|
"meta": {
|
|
402
407
|
"version": "1.3.0",
|
|
403
|
-
"requiresGrove": "0.
|
|
408
|
+
"requiresGrove": "0.13.0"
|
|
404
409
|
}
|
|
405
410
|
},
|
|
406
411
|
{
|
|
@@ -462,7 +467,7 @@
|
|
|
462
467
|
],
|
|
463
468
|
"meta": {
|
|
464
469
|
"version": "1.3.0",
|
|
465
|
-
"requiresGrove": "0.
|
|
470
|
+
"requiresGrove": "0.13.0"
|
|
466
471
|
}
|
|
467
472
|
},
|
|
468
473
|
{
|
|
@@ -488,7 +493,7 @@
|
|
|
488
493
|
],
|
|
489
494
|
"meta": {
|
|
490
495
|
"version": "1.3.0",
|
|
491
|
-
"requiresGrove": "0.
|
|
496
|
+
"requiresGrove": "0.13.0"
|
|
492
497
|
}
|
|
493
498
|
},
|
|
494
499
|
{
|
|
@@ -509,7 +514,7 @@
|
|
|
509
514
|
],
|
|
510
515
|
"meta": {
|
|
511
516
|
"version": "1.3.0",
|
|
512
|
-
"requiresGrove": "0.
|
|
517
|
+
"requiresGrove": "0.13.0"
|
|
513
518
|
}
|
|
514
519
|
},
|
|
515
520
|
{
|
|
@@ -530,7 +535,7 @@
|
|
|
530
535
|
],
|
|
531
536
|
"meta": {
|
|
532
537
|
"version": "1.3.0",
|
|
533
|
-
"requiresGrove": "0.
|
|
538
|
+
"requiresGrove": "0.13.0"
|
|
534
539
|
}
|
|
535
540
|
},
|
|
536
541
|
{
|
|
@@ -551,7 +556,7 @@
|
|
|
551
556
|
],
|
|
552
557
|
"meta": {
|
|
553
558
|
"version": "1.3.0",
|
|
554
|
-
"requiresGrove": "0.
|
|
559
|
+
"requiresGrove": "0.13.0"
|
|
555
560
|
}
|
|
556
561
|
},
|
|
557
562
|
{
|
|
@@ -851,6 +856,11 @@
|
|
|
851
856
|
"type": "registry:component",
|
|
852
857
|
"target": "~/src/components/grove/index-row.astro"
|
|
853
858
|
},
|
|
859
|
+
{
|
|
860
|
+
"path": "default/lib/live-filters.ts",
|
|
861
|
+
"type": "registry:file",
|
|
862
|
+
"target": "~/src/lib/live-filters.ts"
|
|
863
|
+
},
|
|
854
864
|
{
|
|
855
865
|
"path": "default/pages/[slug]/[recordSlug].astro",
|
|
856
866
|
"type": "registry:page",
|
|
@@ -929,7 +939,7 @@
|
|
|
929
939
|
],
|
|
930
940
|
"meta": {
|
|
931
941
|
"version": "1.3.0",
|
|
932
|
-
"requiresGrove": "0.
|
|
942
|
+
"requiresGrove": "0.13.0"
|
|
933
943
|
}
|
|
934
944
|
}
|
|
935
945
|
]
|
package/dist/r/shell.json
CHANGED
package/dist/r/submit.json
CHANGED