Filter panel
A vertical GET form of collapsible facets with checkbox counts, a number range, a switch, in-list search and Clear all.
pnpm dlx shadcn@latest add @haze/filter-panel---
import { ChevronDown } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
import Button from "./button.astro";
import Checkbox from "./checkbox.astro";
import Input from "./input.astro";
import Switch from "./switch.astro";
interface Option {
value: string;
label: string;
/** Number of results with this value. Shown muted and read as a description. */
count?: number;
checked?: boolean;
}
interface Facet {
/** Query parameter for options and toggles (key=value, repeated for several values). */
key: string;
label: string;
/** options: checkboxes. range: two number inputs. toggle: one switch. */
type?: "options" | "range" | "toggle";
/** Section starts open. Sections are not exclusive, so several can be open. */
open?: boolean;
options?: Option[];
/** Options shown before the "Show more" disclosure. Default 6; a single hidden option is never folded away. */
visibleCount?: number;
/** Adds a search field above the options. It appears only once the script has run. */
searchable?: boolean;
/** Range: bounds, step and current values. Parameters are `${key}_min` and `${key}_max` unless named. */
min?: number;
max?: number;
step?: number;
minValue?: number;
maxValue?: number;
minName?: string;
maxName?: string;
/** Toggle: starts on. */
checked?: boolean;
/** Toggle: helper text under the label. */
description?: string;
}
interface Props {
/** Required: ids of the title, fields and options derive from it. */
id: string;
/** Where the GET form submits. Empty means the current page. */
action?: string;
title?: string;
headingLevel?: 2 | 3 | 4;
facets?: Facet[];
/** BCP 47 locale for the result counts. */
locale?: string;
/** Link target of "Clear all", normally the unfiltered URL. Without it the button is a reset: with script it clears every field, without script it restores the page's initial state (pre-checked options come back). */
clearHref?: string;
clearLabel?: string;
applyLabel?: string;
/** Word after the active count ("2 active"). */
activeLabel?: string;
/** Spoken after a count ("48 results"). */
resultsLabel?: string;
/** Use {count} for the number of folded options. */
showMoreLabel?: string;
showFewerLabel?: string;
searchPlaceholder?: string;
/** Prefix of the search field's accessible name, followed by the facet label. */
searchLabel?: string;
emptyLabel?: string;
minLabel?: string;
maxLabel?: string;
class?: string;
}
const {
id,
action = "",
title = "Filters",
headingLevel = 2,
locale = "en-US",
clearHref,
clearLabel = "Clear all",
applyLabel = "Apply",
activeLabel = "active",
resultsLabel = "results",
showMoreLabel = "Show {count} more",
showFewerLabel = "Show fewer",
searchPlaceholder = "Search",
searchLabel = "Search within",
emptyLabel = "No matches",
minLabel = "Min",
maxLabel = "Max",
class: className,
facets = [
{
key: "category",
label: "Category",
open: true,
options: [
{ value: "notebooks", label: "Notebooks", count: 48 },
{ value: "pens", label: "Pens and markers", count: 112 },
{ value: "desk", label: "Desk organisers", count: 37 },
{ value: "filing", label: "Filing and folders", count: 64 },
{ value: "boards", label: "Whiteboards", count: 15 },
],
},
{
key: "brand",
label: "Brand",
open: true,
searchable: true,
visibleCount: 5,
options: [
{ value: "alder", label: "Alder & Co", count: 41 },
{ value: "basalt", label: "Basalt", count: 23 },
{ value: "harbor", label: "Harbor Desk", count: 58 },
{ value: "lumen", label: "Lumen Office", count: 19 },
{ value: "pennant", label: "Pennant", count: 76 },
{ value: "quillmark", label: "Quillmark", count: 33 },
{ value: "tern", label: "Tern Supply", count: 12 },
{ value: "wicker", label: "Wicker & Reed", count: 9 },
],
},
{ key: "price", label: "Price (USD)", type: "range", open: true, min: 0, max: 500, step: 1 },
{ key: "in_stock", label: "In stock only", type: "toggle", description: "Hide items that ship in 2 weeks or more" },
],
} = Astro.props;
const Heading = ({ 2: "h2", 3: "h3", 4: "h4" } as const)[headingLevel];
const number = new Intl.NumberFormat(locale);
const slide =
"supports-[interpolate-size:allow-keywords]:[interpolate-size:allow-keywords] supports-[interpolate-size:allow-keywords]:details-content:h-0 supports-[interpolate-size:allow-keywords]:details-content:overflow-clip supports-[interpolate-size:allow-keywords]:details-content:transition-[height,content-visibility] supports-[interpolate-size:allow-keywords]:details-content:transition-discrete supports-[interpolate-size:allow-keywords]:details-content:duration-300 supports-[interpolate-size:allow-keywords]:details-content:ease-snappy supports-[interpolate-size:allow-keywords]:open:details-content:h-auto";
const enhancedOnly = "hidden [[data-haze-filter-panel][data-enhanced]_&]:block";
---
<form
id={id}
data-haze-filter-panel
data-active-label={activeLabel}
method="get"
action={action}
aria-labelledby={`${id}-title`}
class={cn("min-w-0 overflow-hidden rounded-xl border border-border bg-card text-card-foreground", className)}
>
<div class="flex min-h-14 flex-wrap items-center justify-between gap-x-3 gap-y-1 border-b border-border px-4 py-2">
<div class="flex min-w-0 items-center gap-2">
<Heading id={`${id}-title`} class="text-[1.0625rem] leading-[1.4] font-medium tracking-[-0.01em]">{title}</Heading>
<span data-filter-count aria-hidden="true" hidden class="rounded-full bg-muted px-2 text-xs/5 font-medium text-foreground tabular-nums inset-ring inset-ring-frame"></span>
<span data-filter-status role="status" class="sr-only"></span>
</div>
{
clearHref ? (
<Button href={clearHref} variant="ghost" size="sm">{clearLabel}</Button>
) : (
<Button type="reset" variant="ghost" size="sm" data-filter-clear>{clearLabel}</Button>
)
}
</div>
<div class="divide-y divide-border">
{
facets.map((facet) => {
const kind = facet.type ?? "options";
const options = facet.options ?? [];
const fold = facet.visibleCount ?? 6;
const split = options.length - fold > 1 ? fold : options.length;
const head = options.slice(0, split);
const tail = options.slice(split);
const facetId = `${id}-${facet.key}`;
const minName = facet.minName ?? `${facet.key}_min`;
const maxName = facet.maxName ?? `${facet.key}_max`;
return kind === "toggle" ? (
<div data-facet class="px-4 py-3">
<Switch id={facetId} name={facet.key} value="1" label={facet.label} description={facet.description} checked={facet.checked} />
</div>
) : (
<details data-facet open={facet.open} class={slide}>
<summary class="flex min-h-11 cursor-pointer list-none items-center justify-between gap-3 px-4 py-3 text-[0.8125rem]/5 font-medium text-foreground transition-colors duration-150 ease-snappy hover:bg-accent focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring [&::-webkit-details-marker]:hidden">
<span class="flex min-w-0 items-center gap-2">
<span>{facet.label}</span>
<span data-facet-count aria-hidden="true" hidden class="rounded-full bg-muted px-1.5 text-xs/5 font-medium text-foreground tabular-nums inset-ring inset-ring-frame"></span>
</span>
<ChevronDown aria-hidden="true" class="size-4 shrink-0 text-muted-foreground transition-[rotate,color] duration-200 ease-spring motion-reduce:transition-none [[open]>summary_&]:rotate-180 [[open]>summary_&]:text-foreground" />
</summary>
<div class="grid gap-3 px-4 pt-2 pb-4 text-[0.8125rem]/5 not-supports-[interpolate-size:allow-keywords]:animate-rise">
{kind === "range" ? (
<fieldset class="grid min-w-0 grid-cols-2 gap-2">
<legend class="sr-only">{facet.label}</legend>
<div class="grid min-w-0 gap-2">
<label for={`${facetId}-min`} class="text-[0.8125rem]/5 font-medium">{minLabel}</label>
<Input id={`${facetId}-min`} name={minName} type="number" inputmode="decimal" min={facet.min} max={facet.max} step={facet.step} value={facet.minValue} placeholder={facet.min !== undefined ? String(facet.min) : undefined} class="h-9 tabular-nums" />
</div>
<div class="grid min-w-0 gap-2">
<label for={`${facetId}-max`} class="text-[0.8125rem]/5 font-medium">{maxLabel}</label>
<Input id={`${facetId}-max`} name={maxName} type="number" inputmode="decimal" min={facet.min} max={facet.max} step={facet.step} value={facet.maxValue} placeholder={facet.max !== undefined ? String(facet.max) : undefined} class="h-9 tabular-nums" />
</div>
</fieldset>
) : (
<fieldset class="grid min-w-0 gap-3">
<legend class="sr-only">{facet.label}</legend>
{facet.searchable && (
<div class={enhancedOnly}>
<label for={`${facetId}-search`} class="sr-only">{`${searchLabel} ${facet.label}`}</label>
<Input id={`${facetId}-search`} name="" type="search" autocomplete="off" placeholder={searchPlaceholder} data-facet-search class="h-9" />
</div>
)}
<div class="grid gap-2" data-facet-options>
{head.map((option, index) => (
<div data-option data-option-label={option.label} class="flex min-w-0 items-start justify-between gap-2">
<Checkbox id={`${facetId}-${index}`} name={facet.key} value={option.value} label={option.label} checked={option.checked} class="min-w-0 flex-1 [&>div]:min-w-0" aria-describedby={option.count !== undefined ? `${facetId}-${index}-count` : undefined} />
{option.count !== undefined && (
<span id={`${facetId}-${index}-count`} class="shrink-0 text-[0.8125rem]/6 text-muted-foreground tabular-nums">
{number.format(option.count)}<span class="sr-only"> {resultsLabel}</span>
</span>
)}
</div>
))}
{tail.length > 0 && (
<details data-more open={tail.some((option) => option.checked)} class="group/more grid gap-2">
<summary class="inline-flex min-h-6 w-fit cursor-pointer list-none items-center rounded-sm text-[0.8125rem]/5 font-medium text-muted-foreground transition-colors duration-150 ease-snappy hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring [&::-webkit-details-marker]:hidden">
<span class="group-open/more:hidden">{showMoreLabel.replace("{count}", String(tail.length))}</span>
<span class="hidden group-open/more:inline">{showFewerLabel}</span>
</summary>
<div class="mt-2 grid gap-2">
{tail.map((option, index) => (
<div data-option data-option-label={option.label} class="flex min-w-0 items-start justify-between gap-2">
<Checkbox id={`${facetId}-${split + index}`} name={facet.key} value={option.value} label={option.label} checked={option.checked} class="min-w-0 flex-1 [&>div]:min-w-0" aria-describedby={option.count !== undefined ? `${facetId}-${split + index}-count` : undefined} />
{option.count !== undefined && (
<span id={`${facetId}-${split + index}-count`} class="shrink-0 text-[0.8125rem]/6 text-muted-foreground tabular-nums">
{number.format(option.count)}<span class="sr-only"> {resultsLabel}</span>
</span>
)}
</div>
))}
</div>
</details>
)}
</div>
{facet.searchable && <p data-facet-empty hidden class="text-[0.8125rem]/5 text-muted-foreground">{emptyLabel}</p>}
</fieldset>
)}
</div>
</details>
);
})
}
</div>
<div class="border-t border-border bg-background/40 p-4">
<Button type="submit" class="w-full">{applyLabel}</Button>
</div>
</form>
<script>
function enhance(root: HTMLFormElement) {
if (root.hasAttribute("data-enhanced")) return;
root.setAttribute("data-enhanced", "");
const label = root.dataset.activeLabel ?? "active";
const total = root.querySelector<HTMLElement>("[data-filter-count]");
const status = root.querySelector<HTMLElement>("[data-filter-status]");
const facets = [...root.querySelectorAll<HTMLElement>("[data-facet]")];
const show = (el: HTMLElement | null, n: number) => {
if (!el) return;
const text = n > 0 ? String(n) : "";
if (el.textContent !== text) el.textContent = text;
el.hidden = n === 0;
};
const sync = () => {
let sum = 0;
for (const facet of facets) {
const checked = facet.querySelectorAll("input[type=checkbox]:checked").length;
const ranged = [...facet.querySelectorAll<HTMLInputElement>("input[type=number]")].some((input) => input.value !== "") ? 1 : 0;
const n = checked + ranged;
sum += n;
show(facet.querySelector<HTMLElement>("[data-facet-count]"), n);
}
show(total, sum);
const spoken = sum > 0 ? `${sum} ${label}` : "";
window.clearTimeout(announceTimer);
announceTimer = window.setTimeout(() => {
if (status && status.textContent !== spoken) status.textContent = spoken;
}, 500);
};
let announceTimer: number | undefined;
const closedBefore = new WeakSet<HTMLDetailsElement>();
const search = (input: HTMLInputElement) => {
const facet = input.closest<HTMLElement>("[data-facet]");
if (!facet) return;
const query = input.value.trim().toLowerCase();
let visible = 0;
for (const row of facet.querySelectorAll<HTMLElement>("[data-option]")) {
const match = !query || (row.dataset.optionLabel ?? "").toLowerCase().includes(query);
row.hidden = !match;
if (match) visible += 1;
}
const more = facet.querySelector<HTMLDetailsElement>("[data-more]");
if (more) {
if (query && !more.open) {
closedBefore.add(more);
more.open = true;
} else if (!query && closedBefore.has(more)) {
closedBefore.delete(more);
more.open = false;
}
}
const empty = facet.querySelector<HTMLElement>("[data-facet-empty]");
if (empty) empty.hidden = visible > 0;
};
root.addEventListener("change", sync);
root.addEventListener("input", (event) => {
const target = event.target;
if (target instanceof HTMLInputElement && target.hasAttribute("data-facet-search")) search(target);
else sync();
});
// Enter in the in-facet search must not submit the form.
root.addEventListener("keydown", (event) => {
const target = event.target;
if (event.key === "Enter" && target instanceof HTMLInputElement && target.hasAttribute("data-facet-search")) event.preventDefault();
});
// With script, "Clear all" empties every field instead of restoring the page's pre-checked state.
root.querySelector<HTMLElement>("[data-filter-clear]")?.addEventListener("click", (event) => {
event.preventDefault();
root.querySelectorAll<HTMLInputElement>("input[type=checkbox]").forEach((input) => {
input.checked = false;
});
root.querySelectorAll<HTMLInputElement>("input[type=number]").forEach((input) => {
input.value = "";
});
root.querySelectorAll<HTMLInputElement>("[data-facet-search]").forEach((input) => {
input.value = "";
search(input);
});
sync();
});
root.addEventListener("reset", () =>
setTimeout(() => {
root.querySelectorAll<HTMLInputElement>("[data-facet-search]").forEach(search);
sync();
}, 0),
);
// Keep empty range fields out of the query string, then restore them (the page may come back from the bfcache).
root.addEventListener("submit", () => {
const empty = [...root.querySelectorAll<HTMLInputElement>("input[type=number]")].filter((input) => input.value === "" && !input.disabled);
empty.forEach((input) => {
input.disabled = true;
});
setTimeout(() => {
empty.forEach((input) => {
input.disabled = false;
});
}, 0);
});
window.addEventListener("pageshow", () => {
if (!root.isConnected) return;
root.querySelectorAll<HTMLInputElement>("input[type=number]").forEach((input) => {
input.disabled = false;
});
});
sync();
}
const init = () => document.querySelectorAll<HTMLFormElement>("[data-haze-filter-panel]").forEach(enhance);
init();
if (!document.documentElement.hasAttribute("data-haze-filter-panel-listener")) {
document.documentElement.setAttribute("data-haze-filter-panel-listener", "");
document.addEventListener("astro:page-load", init);
}
</script>When to use
- A product catalog, directory or table sits beside a sidebar of facets such as category, brand and price.
- Selected filters should land in the query string so results can be linked, reloaded and server-rendered.
- A facet has many options and needs a folded 'Show more' list with optional search.
When not to use
- Filters sit above the results as a row of dropdowns; use filter-toolbar.
- The filters must open from a button on small screens; put this panel inside drawer.
- One short list of options in a form; use checkbox-group.
Installation
Add the Haze registry to components.json once, then install Filter panel with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/filter-panelnpx shadcn@latest add @haze/filter-panelyarn dlx shadcn@latest add @haze/filter-panelbunx --bun shadcn@latest add @haze/filter-panelFirst time? Registry and theme setup
1. Add to components.json:
{
"registries": {
"@haze": "http://localhost:4329/r/{name}.json"
}
}2. Install the theme once: npx shadcn@latest add @haze/theme, then import it after Tailwind in your global CSS:@import "./haze.css";
API reference
| Prop | Type | Default | Description |
|---|---|---|---|
| id* | string | – | Prefix for the form, title and every field id. |
| action | string | "" | Where the GET form submits. Empty means the current page. |
| title | string | "Filters" | Panel heading. |
| headingLevel | 2 | 3 | 4 | 2 | Heading level of the title. |
| facets | Facet[] | – | Sections. type 'options' (default): key, label, options[{ value, label, count, checked }], visibleCount, searchable, open. type 'range': min, max, step, minValue, maxValue, minName, maxName. type 'toggle': checked, description. |
| locale | string | "en-US" | BCP 47 locale for the result counts. |
| clearHref | string | – | Makes Clear all a link to the unfiltered URL. Without it Clear all is type=reset and restores the form's first state. |
| clearLabel | string | "Clear all" | Text of the clear control. |
| applyLabel | string | "Apply" | Text of the submit button. |
| activeLabel | string | "active" | Word after the active count, read as '2 active'. |
| resultsLabel | string | "results" | Spoken after each option count. |
| showMoreLabel | string | "Show {count} more" | Folded-list opener; {count} is replaced by the number of hidden options. |
| showFewerLabel | string | "Show fewer" | Folded-list closer. |
| searchLabel | string | "Search within" | Accessible name prefix of a facet search, followed by the facet label. |
| searchPlaceholder | string | "Search" | Placeholder of a facet search. |
| emptyLabel | string | "No matches" | Shown when a facet search matches nothing. |
| minLabel | string | "Min" | Label of the lower range input. |
| maxLabel | string | "Max" | Label of the upper range input. |
| class | string | – | Classes for the form, for example a fixed sidebar width. |
Keyboard interactions
- TabShiftTab
- Move between section summaries, options, range inputs, Clear all and Apply
- EnterSpace
- Open or close a section or a 'Show more' list; toggle a checkbox or switch
Accessibility
- A real form named by its heading. Every option is a native checkbox in a fieldset whose legend is the facet name; counts are announced as descriptions such as '48 results'.
- Sections are native details elements, not exclusive, so any number can stay open; summaries show a focus ring and rotate a decorative chevron.
- Without script the panel still filters: the form submits query parameters, 'Show more' is a nested details, and the live count and facet search simply do not appear.
- The active count is a polite status region that is updated only when the number changes. The visible badge is hidden from assistive technology so it is not read twice.
- On a small screen the panel is one column; place it inside drawer rather than building a second layout.
Notes for AI
Copy into Claude Code, Cursor, Codex or any coding agent. Agents can also read the Markdown version of this page.
Install and use
Install the Haze UI component "Filter panel" with `npx shadcn@latest add @haze/filter-panel`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "http://localhost:4329/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import FilterPanel from "@/components/haze/ui/filter-panel.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: http://localhost:4329/ui/filter-panel.md
Customize with real content
Adapt the Haze filter-panel ui for our product. Replace the demo values of these props with our real content: id, action, title, headingLevel, facets, locale, clearHref, clearLabel, applyLabel, activeLabel, resultsLabel, showMoreLabel, showFewerLabel, searchLabel, searchPlaceholder, emptyLabel, minLabel, maxLabel, class. Keep the layout, the heading level rules and these accessibility details: A real form named by its heading. Every option is a native checkbox in a fieldset whose legend is the facet name; counts are announced as descriptions such as '48 results'. Sections are native details elements, not exclusive, so any number can stay open; summaries show a focus ring and rotate a decorative chevron. Without script the panel still filters: the form submits query parameters, 'Show more' is a nested details, and the live count and facet search simply do not appear. The active count is a polite status region that is updated only when the number changes. The visible badge is hidden from assistive technology so it is not read twice. On a small screen the panel is one column; place it inside drawer rather than building a second layout. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using filter-panel, check it fits: use it when a product catalog, directory or table sits beside a sidebar of facets such as category, brand and price.; selected filters should land in the query string so results can be linked, reloaded and server-rendered.; a facet has many options and needs a folded 'show more' list with optional search.. Avoid it when filters sit above the results as a row of dropdowns; use filter-toolbar.; the filters must open from a button on small screens; put this panel inside drawer.; one short list of options in a form; use checkbox-group.. Alternatives: @haze/filter-toolbar, @haze/drawer, @haze/checkbox-group.
Dependencies
- npm: @lucide/astro
- @haze/button
- @haze/checkbox
- @haze/input
- @haze/switch
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.