{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"listing-filters","type":"registry:ui","title":"Listing filters","description":"Home search filters with location search, type chips, beds and baths, dual price slider and result count.","dependencies":["lucide-react","motion"],"registryDependencies":["utils"],"files":[{"path":"registry/items/listing-filters/listing-filters.tsx","type":"registry:ui","target":"components/facade/listing-filters.tsx","content":"\"use client\";\n\nimport * as React from \"react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport { Check, Search, X } from \"lucide-react\";\nimport { cn } from \"@/lib/utils\";\n\nexport interface ListingFiltersValue {\n  query: string;\n  types: string[];\n  /** Minimum bedrooms, 0 means any. */\n  beds: number;\n  /** Minimum bathrooms, 0 means any. */\n  baths: number;\n  price: [number, number];\n}\n\nexport interface ListingFiltersProps {\n  propertyTypes?: string[];\n  priceMin?: number;\n  priceMax?: number;\n  priceStep?: number;\n  defaultValue?: Partial<ListingFiltersValue>;\n  /** Number of results for the current filters. Pass a function to compute it from the value. */\n  resultCount?: number | ((value: ListingFiltersValue) => number);\n  searchPlaceholder?: string;\n  onChange?: (value: ListingFiltersValue) => void;\n  className?: string;\n}\n\nconst compactUsd = (n: number) => {\n  // Number() drops trailing zeros without eating the digits of whole millions ($10M stays $10M).\n  if (n >= 1_000_000) return `$${Number((n / 1_000_000).toFixed(2))}M`;\n  if (n >= 1000) return `$${Math.round(n / 1000)}K`;\n  return `$${n}`;\n};\n\nconst bedOptions = [0, 1, 2, 3, 4];\nconst bathOptions = [0, 1, 2, 3];\n\nfunction SegmentGroup({\n  label,\n  options,\n  value,\n  onChange,\n  layoutId,\n}: {\n  label: string;\n  options: number[];\n  value: number;\n  onChange: (v: number) => void;\n  layoutId: string;\n}) {\n  const reduce = useReducedMotion();\n  const labelId = `${layoutId}-label`;\n  const groupRef = React.useRef<HTMLDivElement>(null);\n\n  // Roving tabindex: one tab stop per group, arrow keys move the selection.\n  const onKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {\n    const idx = options.indexOf(value);\n    let next: number | undefined;\n    if (e.key === \"ArrowRight\" || e.key === \"ArrowDown\") next = options[(idx + 1) % options.length];\n    else if (e.key === \"ArrowLeft\" || e.key === \"ArrowUp\") next = options[(idx - 1 + options.length) % options.length];\n    else if (e.key === \"Home\") next = options[0];\n    else if (e.key === \"End\") next = options[options.length - 1];\n    if (next === undefined) return;\n    e.preventDefault();\n    onChange(next);\n    groupRef.current?.querySelectorAll<HTMLButtonElement>(\"[role=radio]\")[options.indexOf(next)]?.focus();\n  };\n\n  return (\n    <div className=\"space-y-2\">\n      <p id={labelId} className=\"text-[12px] font-medium uppercase tracking-[0.08em] text-muted-foreground\">\n        {label}\n      </p>\n      <div\n        ref={groupRef}\n        role=\"radiogroup\"\n        aria-labelledby={labelId}\n        onKeyDown={onKeyDown}\n        className=\"flex rounded-xl bg-background p-1 dark:bg-foreground/[0.08]\"\n      >\n        {options.map((o) => {\n          const active = value === o;\n          return (\n            <button\n              key={o}\n              type=\"button\"\n              role=\"radio\"\n              aria-checked={active}\n              tabIndex={active ? 0 : -1}\n              onClick={() => onChange(o)}\n              className={cn(\n                \"relative flex-1 rounded-[10px] px-2 py-1.5 text-sm font-medium tabular-nums transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring\",\n                active ? \"text-background\" : \"text-muted-foreground hover:text-foreground\",\n              )}\n            >\n              {active && (\n                <motion.span\n                  layoutId={layoutId}\n                  className=\"absolute inset-0 rounded-[10px] bg-foreground\"\n                  transition={reduce ? { duration: 0 } : { type: \"spring\", stiffness: 380, damping: 34 }}\n                />\n              )}\n              <span className=\"relative\">{o === 0 ? \"Any\" : `${o}+`}</span>\n            </button>\n          );\n        })}\n      </div>\n    </div>\n  );\n}\n\nfunction RangeSlider({\n  min,\n  max,\n  step,\n  value,\n  onChange,\n  id,\n}: {\n  min: number;\n  max: number;\n  step: number;\n  value: [number, number];\n  onChange: (v: [number, number]) => void;\n  id: string;\n}) {\n  const trackRef = React.useRef<HTMLDivElement>(null);\n  const [dragging, setDragging] = React.useState<0 | 1 | null>(null);\n  const pct = (v: number) => ((v - min) / (max - min)) * 100;\n  const snap = (v: number) => Math.min(max, Math.max(min, Math.round((v - min) / step) * step + min));\n\n  const setThumb = (thumb: 0 | 1, raw: number) => {\n    const v = snap(raw);\n    if (thumb === 0) onChange([Math.min(v, value[1] - step), value[1]]);\n    else onChange([value[0], Math.max(v, value[0] + step)]);\n  };\n\n  const valueFromClient = (clientX: number) => {\n    const rect = trackRef.current?.getBoundingClientRect();\n    if (!rect) return min;\n    return min + ((clientX - rect.left) / rect.width) * (max - min);\n  };\n\n  const onTrackDown = (e: React.PointerEvent<HTMLDivElement>) => {\n    const v = valueFromClient(e.clientX);\n    const thumb: 0 | 1 = Math.abs(v - value[0]) <= Math.abs(v - value[1]) ? 0 : 1;\n    e.currentTarget.setPointerCapture(e.pointerId);\n    setDragging(thumb);\n    setThumb(thumb, v);\n    const btn = trackRef.current?.querySelectorAll<HTMLElement>(\"[role=slider]\")[thumb];\n    btn?.focus({ preventScroll: true });\n  };\n\n  const onKey = (thumb: 0 | 1) => (e: React.KeyboardEvent<HTMLDivElement>) => {\n    const big = step * 10;\n    const current = value[thumb];\n    let next: number | null = null;\n    if (e.key === \"ArrowLeft\" || e.key === \"ArrowDown\") next = current - step;\n    else if (e.key === \"ArrowRight\" || e.key === \"ArrowUp\") next = current + step;\n    else if (e.key === \"PageDown\") next = current - big;\n    else if (e.key === \"PageUp\") next = current + big;\n    else if (e.key === \"Home\") next = thumb === 0 ? min : value[0] + step;\n    else if (e.key === \"End\") next = thumb === 0 ? value[1] - step : max;\n    if (next !== null) {\n      e.preventDefault();\n      setThumb(thumb, next);\n    }\n  };\n\n  const fmt = (v: number) => (v >= max ? `${compactUsd(v)}+` : compactUsd(v));\n\n  return (\n    <div\n      ref={trackRef}\n      className=\"relative h-6 touch-none select-none\"\n      onPointerDown={onTrackDown}\n      onPointerMove={(e) => {\n        if (dragging !== null) setThumb(dragging, valueFromClient(e.clientX));\n      }}\n      onPointerUp={() => setDragging(null)}\n      onPointerCancel={() => setDragging(null)}\n    >\n      <div className=\"absolute inset-x-0 top-1/2 h-1.5 -translate-y-1/2 rounded-full bg-background dark:bg-foreground/[0.08]\" />\n      <div\n        className=\"absolute top-1/2 h-1.5 -translate-y-1/2 rounded-full bg-brand\"\n        style={{ left: `${pct(value[0])}%`, right: `${100 - pct(value[1])}%` }}\n      />\n      {([0, 1] as const).map((thumb) => (\n        <div\n          key={thumb}\n          role=\"slider\"\n          tabIndex={0}\n          id={thumb === 0 ? `${id}-min` : `${id}-max`}\n          aria-label={thumb === 0 ? \"Minimum price\" : \"Maximum price\"}\n          aria-valuemin={thumb === 0 ? min : value[0] + step}\n          aria-valuemax={thumb === 0 ? value[1] - step : max}\n          aria-valuenow={value[thumb]}\n          aria-valuetext={fmt(value[thumb])}\n          onKeyDown={onKey(thumb)}\n          className={cn(\n            \"absolute top-1/2 size-6 -translate-x-1/2 -translate-y-1/2 cursor-grab rounded-full bg-background shadow-float ring-1 ring-foreground/[0.08] transition-transform duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring dark:bg-foreground dark:ring-0\",\n            dragging === thumb ? \"scale-110 cursor-grabbing\" : \"hover:scale-110\",\n          )}\n          style={{ left: `${pct(value[thumb])}%`, zIndex: dragging === thumb ? 2 : 1 }}\n        />\n      ))}\n    </div>\n  );\n}\n\nexport function ListingFilters({\n  propertyTypes = [\"House\", \"Condo\", \"Townhome\", \"Multi-family\", \"Land\"],\n  priceMin = 0,\n  priceMax = 2_000_000,\n  priceStep = 25_000,\n  defaultValue,\n  resultCount,\n  searchPlaceholder = \"City, neighborhood, ZIP or address\",\n  onChange,\n  className,\n}: ListingFiltersProps) {\n  const uid = React.useId();\n  const reduce = useReducedMotion();\n  const empty: ListingFiltersValue = { query: \"\", types: [], beds: 0, baths: 0, price: [priceMin, priceMax] };\n  const [value, setValue] = React.useState<ListingFiltersValue>(() => ({\n    query: \"\",\n    types: [],\n    beds: 0,\n    baths: 0,\n    price: [priceMin, priceMax],\n    ...defaultValue,\n  }));\n\n  const onChangeRef = React.useRef(onChange);\n  React.useEffect(() => {\n    onChangeRef.current = onChange;\n  });\n\n  const update = (patch: Partial<ListingFiltersValue>) => {\n    // Compute outside the updater so onChange is not called twice under StrictMode.\n    const next = { ...value, ...patch };\n    setValue(next);\n    onChangeRef.current?.(next);\n  };\n\n  const activeCount =\n    (value.query ? 1 : 0) +\n    value.types.length +\n    (value.beds ? 1 : 0) +\n    (value.baths ? 1 : 0) +\n    (value.price[0] !== priceMin || value.price[1] !== priceMax ? 1 : 0);\n\n  const count = typeof resultCount === \"function\" ? resultCount(value) : resultCount;\n  const priceLabel = `${compactUsd(value.price[0])} to ${value.price[1] >= priceMax ? `${compactUsd(priceMax)}+` : compactUsd(value.price[1])}`;\n\n  return (\n    <div className={cn(\"w-full rounded-[28px] bg-muted p-4 text-foreground sm:p-6\", className)}>\n      <div className=\"relative\">\n        <Search className=\"pointer-events-none absolute left-3.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground\" aria-hidden=\"true\" />\n        <input\n          type=\"search\"\n          aria-label=\"Search location\"\n          placeholder={searchPlaceholder}\n          value={value.query}\n          onChange={(e) => update({ query: e.target.value })}\n          className=\"h-12 w-full rounded-xl bg-background pl-10 pr-10 text-[15px] text-foreground transition-shadow placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring dark:bg-foreground/[0.08] [&::-webkit-search-cancel-button]:hidden\"\n        />\n        <AnimatePresence>\n          {value.query && (\n            <motion.button\n              type=\"button\"\n              aria-label=\"Clear search\"\n              onClick={() => update({ query: \"\" })}\n              initial={{ opacity: 0, scale: 0.8 }}\n              animate={{ opacity: 1, scale: 1 }}\n              exit={{ opacity: 0, scale: 0.8 }}\n              transition={{ duration: 0.15 }}\n              className=\"absolute right-3 top-1/2 grid size-6 -translate-y-1/2 place-items-center rounded-full text-muted-foreground hover:bg-foreground/[0.06] hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n            >\n              <X className=\"size-3.5\" />\n            </motion.button>\n          )}\n        </AnimatePresence>\n      </div>\n\n      <fieldset className=\"mt-6\">\n        <legend className=\"mb-2.5 text-[12px] font-medium uppercase tracking-[0.08em] text-muted-foreground\">Home type</legend>\n        <div className=\"flex flex-wrap gap-2\">\n          {propertyTypes.map((t) => {\n            const on = value.types.includes(t);\n            return (\n              <motion.button\n                key={t}\n                type=\"button\"\n                aria-pressed={on}\n                onClick={() => update({ types: on ? value.types.filter((x) => x !== t) : [...value.types, t] })}\n                layout={!reduce}\n                transition={{ type: \"spring\", stiffness: 380, damping: 34 }}\n                className={cn(\n                  \"inline-flex h-9 items-center gap-1.5 rounded-full px-3.5 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-muted\",\n                  on\n                    ? \"bg-foreground text-background\"\n                    : \"bg-background text-muted-foreground hover:text-foreground dark:bg-foreground/[0.08]\",\n                )}\n              >\n                <AnimatePresence initial={false}>\n                  {on && (\n                    <motion.span\n                      initial={{ width: 0, opacity: 0 }}\n                      animate={{ width: \"auto\", opacity: 1 }}\n                      exit={{ width: 0, opacity: 0 }}\n                      transition={{ duration: reduce ? 0 : 0.25, ease: [0.16, 1, 0.3, 1] }}\n                      className=\"inline-flex overflow-hidden\"\n                    >\n                      <Check className=\"size-3.5\" strokeWidth={2.5} aria-hidden=\"true\" />\n                    </motion.span>\n                  )}\n                </AnimatePresence>\n                {t}\n              </motion.button>\n            );\n          })}\n        </div>\n      </fieldset>\n\n      <div className=\"mt-6 grid gap-4 sm:grid-cols-2\">\n        <SegmentGroup label=\"Beds\" options={bedOptions} value={value.beds} onChange={(beds) => update({ beds })} layoutId={`${uid}-beds`} />\n        <SegmentGroup label=\"Baths\" options={bathOptions} value={value.baths} onChange={(baths) => update({ baths })} layoutId={`${uid}-baths`} />\n      </div>\n\n      <div className=\"mt-6 space-y-3\">\n        <div className=\"flex items-baseline justify-between\">\n          <p id={`${uid}-price`} className=\"text-[12px] font-medium uppercase tracking-[0.08em] text-muted-foreground\">\n            Price\n          </p>\n          <p className=\"text-sm font-medium tabular-nums text-foreground\">{priceLabel}</p>\n        </div>\n        <div role=\"group\" aria-labelledby={`${uid}-price`} className=\"px-2.5\">\n          <RangeSlider\n            id={uid}\n            min={priceMin}\n            max={priceMax}\n            step={priceStep}\n            value={value.price}\n            onChange={(price) => update({ price })}\n          />\n        </div>\n      </div>\n\n      <div className=\"mt-7 flex items-center justify-between gap-3\">\n        <button\n          type=\"button\"\n          onClick={() => {\n            setValue(empty);\n            onChangeRef.current?.(empty);\n          }}\n          disabled={activeCount === 0}\n          className=\"rounded-md text-sm font-medium text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40\"\n        >\n          Clear all{activeCount > 0 && <span className=\"tabular-nums\"> ({activeCount})</span>}\n        </button>\n        {count !== undefined && (\n          <p className=\"inline-flex h-11 items-center rounded-full bg-brand px-5 text-[15px] font-medium text-brand-foreground\" aria-live=\"polite\">\n            <span className=\"relative inline-flex overflow-hidden tabular-nums\">\n              <AnimatePresence mode=\"popLayout\" initial={false}>\n                <motion.span\n                  key={count}\n                  initial={reduce ? false : { y: \"100%\", opacity: 0 }}\n                  animate={{ y: 0, opacity: 1 }}\n                  exit={reduce ? undefined : { y: \"-100%\", opacity: 0 }}\n                  transition={{ duration: 0.3, ease: [0.16, 1, 0.3, 1] }}\n                >\n                  {count.toLocaleString(\"en-US\")}\n                </motion.span>\n              </AnimatePresence>\n            </span>\n            &nbsp;{count === 1 ? \"home\" : \"homes\"}\n          </p>\n        )}\n      </div>\n    </div>\n  );\n}\n\nexport default ListingFilters;\n"}],"categories":["forms"],"meta":{"tier":"free","demo":"\"use client\";\n\nimport { ListingFilters, type ListingFiltersValue } from \"./listing-filters\";\n\n// Deterministic mock count so the demo feels live without a backend.\nfunction estimateResults(v: ListingFiltersValue) {\n  let n = 1284;\n  if (v.query.trim()) n *= 0.18;\n  if (v.types.length) n *= Math.min(1, 0.22 * v.types.length + 0.15);\n  n *= [1, 0.92, 0.74, 0.46, 0.21][v.beds] ?? 1;\n  n *= [1, 0.95, 0.62, 0.28][v.baths] ?? 1;\n  const span = (v.price[1] - v.price[0]) / 2_000_000;\n  n *= Math.max(0.04, span);\n  return Math.max(0, Math.round(n));\n}\n\nexport default function Demo() {\n  return (\n    <div className=\"w-full max-w-[560px]\">\n      <ListingFilters\n        defaultValue={{ query: \"Austin, TX\", types: [\"House\", \"Townhome\"], beds: 3, price: [450_000, 1_250_000] }}\n        resultCount={estimateResults}\n      />\n    </div>\n  );\n}\n"}}