{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "filter",
  "title": "Filter",
  "description": "Filter menu with grouped options, a selection count and a footer, plus helpers for the selection model.",
  "dependencies": [
    "class-variance-authority@^0.7.1",
    "lucide-react@^1.27.0"
  ],
  "registryDependencies": [
    "@pestoui/badge",
    "@pestoui/button",
    "@pestoui/checkbox",
    "@pestoui/empty-state",
    "@pestoui/popover",
    "@pestoui/style",
    "@pestoui/utils"
  ],
  "files": [
    {
      "path": "pestoui/ui/filter.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { cva, type VariantProps } from \"class-variance-authority\"\nimport { ChevronDownIcon, ListFilterIcon, SearchIcon } from \"lucide-react\"\n\nimport { cn } from \"@/lib/utils\"\nimport { Badge } from \"@/components/ui/badge\"\nimport { Button } from \"@/components/ui/button\"\nimport { Checkbox } from \"@/components/ui/checkbox\"\nimport {\n  EmptyState,\n  EmptyStateDescription,\n  EmptyStateTitle,\n} from \"@/components/ui/empty-state\"\nimport { Popover, PopoverContent, PopoverTrigger } from \"@/components/ui/popover\"\n\n/* ------------------------------------------------------------------ model -- */\n\ntype FilterOption = {\n  /** Stable key. This is what lands in the selection array for the facet. */\n  value: string\n  label: string\n  /** Matching-record tally, right-aligned on the row. Omit to hide it. */\n  count?: number\n  disabled?: boolean\n}\n\ntype FilterFacet = {\n  /** Stable key. The selection is keyed by it. */\n  id: string\n  label: string\n  options: FilterOption[]\n}\n\n/**\n * facet id -> the option values checked inside it. A facet with nothing checked\n * is absent from the object rather than present with an empty array, so an\n * \"is anything applied\" test is a key count and never has to look inside.\n */\ntype FilterSelection = Record<string, string[]>\n\n/** Exported so a consumer tallies the applied set the same way the badge does. */\nfunction countFilterSelection(selection: FilterSelection): number {\n  return Object.values(selection).reduce(\n    (total, values) => total + values.length,\n    0\n  )\n}\n\nfunction setFacetValues(\n  selection: FilterSelection,\n  facetId: string,\n  values: string[]\n): FilterSelection {\n  const next = { ...selection }\n  if (values.length === 0) {\n    delete next[facetId]\n  } else {\n    next[facetId] = values\n  }\n  return next\n}\n\n/**\n * Add or drop one value inside one facet, returning a new selection. Exported\n * because `FilterMenuPanel` is fully controlled — a consumer mounting it in a\n * Sheet needs the same reducer the popover uses internally.\n */\nfunction toggleFilterValue(\n  selection: FilterSelection,\n  facetId: string,\n  value: string\n): FilterSelection {\n  const current = selection[facetId] ?? []\n  return setFacetValues(\n    selection,\n    facetId,\n    current.includes(value)\n      ? current.filter((item) => item !== value)\n      : [...current, value]\n  )\n}\n\n/* ----------------------------------------------------------------- option -- */\n\ntype FilterMenuOptionProps = Omit<\n  React.ComponentProps<\"label\">,\n  \"onChange\" | \"children\"\n> & {\n  option: FilterOption\n  checked: boolean\n  onCheckedChange: (checked: boolean) => void\n}\n\n/* A real <label> wrapping a real checkbox, so the whole band is a hit target\n   and Space toggles it — no re-implemented listbox, no roving tabindex. The\n   browser suppresses the label's own activation when the click already landed\n   on the control, so wrapping cannot double-toggle. */\nfunction FilterMenuOption({\n  option,\n  checked,\n  onCheckedChange,\n  className,\n  ...props\n}: FilterMenuOptionProps) {\n  return (\n    <label\n      data-slot=\"filter-menu-option\"\n      /* Emitted for descendants and for consumers styling a checked band —\n         the row never reads it back to style itself. */\n      data-checked={checked ? \"true\" : undefined}\n      className={cn(\n        \"flex cursor-pointer items-center gap-2.5 rounded-md px-2 py-1.5 text-sm transition-colors duration-instant ease-out-expo select-none hover:bg-accent has-[[data-slot=checkbox]:focus-visible]:bg-accent has-[[data-slot=checkbox]:disabled]:cursor-not-allowed has-[[data-slot=checkbox]:disabled]:opacity-50\",\n        className\n      )}\n      {...props}\n    >\n      <Checkbox\n        checked={checked}\n        disabled={option.disabled}\n        onCheckedChange={(next) => onCheckedChange(next === true)}\n      />\n      <span className=\"min-w-0 flex-1 truncate\">{option.label}</span>\n      {option.count === undefined ? null : (\n        <span\n          data-slot=\"filter-menu-option-count\"\n          className=\"shrink-0 text-xs tabular-nums text-muted-foreground\"\n        >\n          {option.count}\n        </span>\n      )}\n    </label>\n  )\n}\n\n/* ------------------------------------------------------------------ group -- */\n\ntype FilterMenuGroupProps = Omit<\n  React.ComponentProps<\"div\">,\n  \"onChange\" | \"children\"\n> & {\n  facet: FilterFacet\n  /** Checked values inside this facet only. */\n  value: string[]\n  onValueChange: (next: string[]) => void\n}\n\n/* One facet: a heading plus its checklist. role=\"group\" + aria-labelledby is\n   what lets a screen-reader user tell \"Active\" under Status apart from\n   \"Active\" under Plan — there are no visible labels on the rows themselves. */\nfunction FilterMenuGroup({\n  facet,\n  value,\n  onValueChange,\n  className,\n  ...props\n}: FilterMenuGroupProps) {\n  const headingId = React.useId()\n\n  return (\n    <div\n      data-slot=\"filter-menu-group\"\n      role=\"group\"\n      aria-labelledby={headingId}\n      className={cn(\"flex flex-col\", className)}\n      {...props}\n    >\n      <div\n        id={headingId}\n        data-slot=\"filter-menu-group-label\"\n        className=\"px-2 pt-2 pb-1 text-xs font-medium text-muted-foreground\"\n      >\n        {facet.label}\n      </div>\n      {facet.options.map((option) => (\n        <FilterMenuOption\n          key={option.value}\n          option={option}\n          checked={value.includes(option.value)}\n          onCheckedChange={(next) =>\n            onValueChange(\n              next\n                ? [...value, option.value]\n                : value.filter((item) => item !== option.value)\n            )\n          }\n        />\n      ))}\n    </div>\n  )\n}\n\n/* ----------------------------------------------------------------- footer -- */\n\nfunction FilterMenuFooter({ className, ...props }: React.ComponentProps<\"div\">) {\n  return (\n    <div\n      data-slot=\"filter-menu-footer\"\n      /* Fade with no travel. The footer mounts the moment the first filter\n         lands, which changes the panel's height — anything that moves here\n         would fight Radix repositioning the panel on the same frame. */\n      className={cn(\n        \"flex animate-in items-center justify-between gap-2 border-t border-border px-3 py-2.5 fade-in-0 duration-spring-swap ease-spring-swap\",\n        className\n      )}\n      {...props}\n    />\n  )\n}\n\n/* ------------------------------------------------------------------ panel -- */\n\nconst filterMenuPanelVariants = cva(\"flex w-full min-w-0 flex-col\", {\n  variants: {\n    surface: {\n      /* Dropped into PopoverContent, which already paints fill, ring and\n         shadow — the panel adds nothing of its own. */\n      popover: \"\",\n      /* Standalone: inside a Sheet on a narrow viewport, or laid flat in a\n         page. It has to paint its own card. */\n      flush: \"rounded-xl bg-card ring-1 ring-border\",\n    },\n  },\n  defaultVariants: {\n    surface: \"popover\",\n  },\n})\n\ntype FilterMenuPanelProps = Omit<\n  React.ComponentProps<\"div\">,\n  \"onChange\" | \"defaultValue\"\n> &\n  VariantProps<typeof filterMenuPanelVariants> & {\n    facets: FilterFacet[]\n    /** Fully controlled — this part holds no selection state of its own. */\n    value: FilterSelection\n    onValueChange: (next: FilterSelection) => void\n    searchable?: boolean\n    searchPlaceholder?: string\n    /** Rendering the Apply button is what makes the panel a draft. */\n    onApply?: () => void\n    onClear?: () => void\n    clearLabel?: React.ReactNode\n    applyLabel?: React.ReactNode\n    emptyTitle?: React.ReactNode\n    emptyDescription?: React.ReactNode\n  }\n\n/* Body + footer with no popover chrome of its own, so the same panel can be\n   mounted in a Sheet for the narrow-viewport treatment. Deliberately not given\n   a `responsive` prop that swaps its own container — two mount points sharing\n   one draft is a state-duplication trap; compose it instead. */\nfunction FilterMenuPanel({\n  facets,\n  value,\n  onValueChange,\n  surface = \"popover\",\n  searchable = false,\n  searchPlaceholder = \"Search filters\",\n  onApply,\n  onClear,\n  clearLabel = \"Clear all\",\n  applyLabel = \"Apply\",\n  emptyTitle,\n  emptyDescription,\n  className,\n  children,\n  ...props\n}: FilterMenuPanelProps) {\n  const [query, setQuery] = React.useState(\"\")\n  const searchRef = React.useRef<HTMLInputElement>(null)\n  const bodyRef = React.useRef<HTMLDivElement>(null)\n\n  const selectedCount = countFilterSelection(value)\n  const searching = query.trim().length > 0\n\n  /* Announced only once the count actually moves. A live region that mounts\n     with text in it can be read out the moment the panel opens, which would\n     make every open start with \"0 filters selected\". */\n  const [announcement, setAnnouncement] = React.useState(\"\")\n  const mounted = React.useRef(false)\n  React.useEffect(() => {\n    if (!mounted.current) {\n      mounted.current = true\n      return\n    }\n    setAnnouncement(\n      selectedCount === 1\n        ? \"1 filter selected\"\n        : `${selectedCount} filters selected`\n    )\n  }, [selectedCount])\n\n  const visibleFacets = React.useMemo(() => {\n    const needle = query.trim().toLowerCase()\n    if (needle.length === 0) return facets\n    return facets\n      .map((facet) => ({\n        ...facet,\n        options: facet.options.filter((option) =>\n          option.label.toLowerCase().includes(needle)\n        ),\n      }))\n      .filter((facet) => facet.options.length > 0)\n  }, [facets, query])\n\n  function handleClear() {\n    onClear?.()\n    /* Clear all unmounts itself the instant it succeeds, which would drop\n       focus onto <body>. Hand it to the search box, else to the first\n       checkbox, else leave it where the browser put it. */\n    requestAnimationFrame(() => {\n      const fallback = bodyRef.current?.querySelector<HTMLElement>(\n        \"[data-slot=checkbox]:not(:disabled)\"\n      )\n      const target = searchRef.current ?? fallback\n      target?.focus()\n    })\n  }\n\n  const showFooter = onApply !== undefined || selectedCount > 0\n\n  return (\n    <div\n      data-slot=\"filter-menu-panel\"\n      data-surface={surface}\n      className={cn(filterMenuPanelVariants({ surface }), className)}\n      {...props}\n    >\n      {searchable ? (\n        <div\n          data-slot=\"filter-menu-search\"\n          className=\"relative shrink-0 border-b border-border\"\n        >\n          <SearchIcon\n            aria-hidden=\"true\"\n            className=\"pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground\"\n          />\n          <input\n            ref={searchRef}\n            type=\"search\"\n            value={query}\n            onChange={(event) => setQuery(event.target.value)}\n            placeholder={searchPlaceholder}\n            aria-label={searchPlaceholder}\n            className=\"h-10 w-full bg-transparent pr-3 pl-9 text-sm outline-none placeholder:text-muted-foreground\"\n          />\n        </div>\n      ) : null}\n\n      <div\n        ref={bodyRef}\n        data-slot=\"filter-menu-body\"\n        className=\"flex max-h-72 flex-col overflow-y-auto overscroll-contain p-1.5\"\n      >\n        {visibleFacets.length === 0 ? (\n          <EmptyState size=\"sm\">\n            <EmptyStateTitle>\n              {emptyTitle ??\n                (searching ? \"No matching filters\" : \"No filters available\")}\n            </EmptyStateTitle>\n            <EmptyStateDescription>\n              {emptyDescription ??\n                (searching\n                  ? \"Try a different search term.\"\n                  : \"There is nothing to filter on yet.\")}\n            </EmptyStateDescription>\n          </EmptyState>\n        ) : (\n          visibleFacets.map((facet) => (\n            <FilterMenuGroup\n              key={facet.id}\n              facet={facet}\n              value={value[facet.id] ?? []}\n              onValueChange={(next) =>\n                onValueChange(setFacetValues(value, facet.id, next))\n              }\n            />\n          ))\n        )}\n        {children}\n      </div>\n\n      {/* A row being checked, or the whole set being cleared, is silent — the\n          list it narrows is somewhere else on the page entirely. */}\n      <span aria-live=\"polite\" className=\"sr-only\">\n        {announcement}\n      </span>\n\n      {showFooter ? (\n        <FilterMenuFooter>\n          {selectedCount > 0 ? (\n            <Button\n              type=\"button\"\n              variant=\"ghost\"\n              size=\"xs\"\n              onClick={handleClear}\n              className=\"text-muted-foreground hover:text-foreground\"\n            >\n              {clearLabel}\n            </Button>\n          ) : null}\n          {onApply ? (\n            <Button type=\"button\" size=\"xs\" onClick={onApply} className=\"ml-auto\">\n              {applyLabel}\n            </Button>\n          ) : null}\n        </FilterMenuFooter>\n      ) : null}\n    </div>\n  )\n}\n\n/* ---------------------------------------------------------------- trigger -- */\n\ntype FilterMenuTriggerProps = React.ComponentProps<typeof Button> & {\n  /** Applied filters. Zero hides the badge entirely. */\n  count?: number\n  label?: React.ReactNode\n}\n\nfunction FilterMenuTrigger({\n  count = 0,\n  label = \"Filters\",\n  variant = \"outline\",\n  className,\n  children,\n  ...props\n}: FilterMenuTriggerProps) {\n  return (\n    <Button\n      type=\"button\"\n      data-slot=\"filter-menu-trigger\"\n      /* For descendants and for consumers — never read back to style this\n         button. Radix supplies aria-expanded / aria-haspopup on top. */\n      data-applied={count > 0 ? \"true\" : undefined}\n      variant={variant}\n      className={className}\n      {...props}\n    >\n      <ListFilterIcon aria-hidden=\"true\" />\n      {label}\n      {count > 0 ? (\n        <>\n          {/* Deliberately NOT the badge's own `count` colours: that variant is\n              bg-info, and info is reserved for informational UI. An applied\n              tally says \"this control is switched on\", which is selection\n              semantics, so it takes the selected accent. Please don't \"fix\"\n              this back to the default. Keyed by the number so it remounts and\n              replays the pop each time the count actually lands. */}\n          <Badge\n            key={count}\n            appear\n            variant=\"count\"\n            aria-hidden=\"true\"\n            className=\"bg-selected text-selected-foreground\"\n          >\n            {count}\n          </Badge>\n          {/* A button is named from its content, so the tally has to say what\n              it means rather than read out as a bare digit. */}\n          <span className=\"sr-only\">{count} applied</span>\n        </>\n      ) : null}\n      {children}\n      <ChevronDownIcon\n        aria-hidden=\"true\"\n        /* One chevron that turns: a half turn lands exactly on the up chevron,\n           so only the change between the two states is animated. */\n        className=\"size-4 shrink-0 text-muted-foreground transition-transform duration-spring-press ease-spring-press group-aria-expanded/button:rotate-180\"\n      />\n    </Button>\n  )\n}\n\n/* ------------------------------------------------------------------- root -- */\n\ntype FilterMenuProps = Omit<\n  React.ComponentProps<\"button\">,\n  \"value\" | \"defaultValue\" | \"onChange\"\n> & {\n  facets: FilterFacet[]\n\n  /** The draft — what is checked in the panel right now. */\n  value?: FilterSelection\n  defaultValue?: FilterSelection\n  onValueChange?: (next: FilterSelection) => void\n\n  /**\n   * Commit handler. When present the panel holds a DRAFT and only lifts it on\n   * Apply — the badge then counts the last committed set, not what is checked.\n   * When omitted no Apply button is rendered and every toggle is live.\n   */\n  onApply?: (selection: FilterSelection) => void\n\n  /* Trigger. */\n  label?: React.ReactNode\n  size?: \"sm\" | \"default\"\n  variant?: \"outline\" | \"secondary\" | \"ghost\"\n  disabled?: boolean\n\n  /* Panel. */\n  align?: React.ComponentProps<typeof PopoverContent>[\"align\"]\n  sideOffset?: number\n  open?: boolean\n  onOpenChange?: (open: boolean) => void\n  searchable?: boolean\n  searchPlaceholder?: string\n  panelClassName?: string\n\n  /* Copy. */\n  clearLabel?: React.ReactNode\n  applyLabel?: React.ReactNode\n  emptyTitle?: React.ReactNode\n  emptyDescription?: React.ReactNode\n}\n\nfunction FilterMenu({\n  facets,\n  value: valueProp,\n  defaultValue,\n  onValueChange,\n  onApply,\n  label,\n  size = \"default\",\n  variant = \"outline\",\n  disabled = false,\n  align = \"start\",\n  sideOffset = 6,\n  open: openProp,\n  onOpenChange,\n  searchable = false,\n  searchPlaceholder,\n  panelClassName,\n  clearLabel,\n  applyLabel,\n  emptyTitle,\n  emptyDescription,\n  ...props\n}: FilterMenuProps) {\n  const isControlled = valueProp !== undefined\n  const [internalValue, setInternalValue] = React.useState<FilterSelection>(\n    () => defaultValue ?? {}\n  )\n  const draft = isControlled ? valueProp : internalValue\n\n  /* Deferred the moment a commit handler exists. Three cases, pinned here: the\n     badge counts the APPLIED set while deferred and the draft otherwise;\n     closing without applying keeps the draft so reopening resumes, but the\n     badge does not move because nothing was committed; and Clear all edits the\n     draft like any other control, so in deferred mode it still needs an Apply\n     to take effect. */\n  const deferred = onApply !== undefined\n  const [applied, setApplied] = React.useState<FilterSelection>(\n    () => defaultValue ?? valueProp ?? {}\n  )\n\n  const [internalOpen, setInternalOpen] = React.useState(false)\n  const open = openProp ?? internalOpen\n\n  function setOpen(next: boolean) {\n    if (openProp === undefined) setInternalOpen(next)\n    onOpenChange?.(next)\n  }\n\n  function commit(next: FilterSelection) {\n    if (!isControlled) setInternalValue(next)\n    onValueChange?.(next)\n  }\n\n  function handleApply() {\n    setApplied(draft)\n    onApply?.(draft)\n    setOpen(false)\n  }\n\n  const appliedCount = countFilterSelection(deferred ? applied : draft)\n\n  return (\n    <Popover\n      open={open}\n      onOpenChange={(next) => setOpen(disabled ? false : next)}\n    >\n      <PopoverTrigger asChild>\n        <FilterMenuTrigger\n          count={appliedCount}\n          label={label}\n          size={size}\n          variant={variant}\n          disabled={disabled}\n          {...props}\n        />\n      </PopoverTrigger>\n\n      <PopoverContent\n        align={align}\n        sideOffset={sideOffset}\n        /* Keep the panel off the viewport edge. It grows as facets open, and a\n           panel that hits the edge makes Radix flip sides mid-interaction. */\n        collisionPadding={12}\n        /* Width is content-driven with a floor, never three hardcoded steps.\n           overflow-hidden lets the flush body clip to the popover's corners. */\n        className={cn(\n          \"w-auto min-w-72 max-w-[calc(var(--radix-popover-content-available-width,100vw)-1.5rem)] gap-0 overflow-hidden p-0\",\n          panelClassName\n        )}\n      >\n        <FilterMenuPanel\n          facets={facets}\n          value={draft}\n          onValueChange={commit}\n          searchable={searchable}\n          searchPlaceholder={searchPlaceholder}\n          onApply={deferred ? handleApply : undefined}\n          onClear={() => commit({})}\n          clearLabel={clearLabel}\n          applyLabel={applyLabel}\n          emptyTitle={emptyTitle}\n          emptyDescription={emptyDescription}\n        />\n      </PopoverContent>\n    </Popover>\n  )\n}\n\nexport {\n  FilterMenu,\n  FilterMenuFooter,\n  FilterMenuGroup,\n  FilterMenuOption,\n  FilterMenuPanel,\n  FilterMenuTrigger,\n  countFilterSelection,\n  filterMenuPanelVariants,\n  toggleFilterValue,\n}\nexport type {\n  FilterFacet,\n  FilterMenuGroupProps,\n  FilterMenuOptionProps,\n  FilterMenuPanelProps,\n  FilterMenuProps,\n  FilterMenuTriggerProps,\n  FilterOption,\n  FilterSelection,\n}\n",
      "type": "registry:ui"
    }
  ],
  "type": "registry:ui"
}