{"slug":"refine-search","category":"tables","job":"steer","added":"2026-11-12T15:51Z","title":"Refine Search","description":"A \"Refine your search\" panel above search results where the AI proposes a few filters, each with the count it would leave, and one click applies it as a removable chip.","url":"https://ai-patterns.app/patterns/tables/refine-search","markdown":"https://ai-patterns.app/patterns/tables/refine-search.md","json":"https://ai-patterns.app/api/patterns/tables/refine-search","seenIn":[{"team":"datamaran","source":"https://www.datamaran.com/"}],"spec":"# Refine Search\n\n## Summary\nA \"Refine your search\" panel between a search field and its results, where the AI proposes a few filters that would usefully narrow the current result set — each shown as a pill with the number of results it would leave (\"Beta (6)\"). One click applies a proposal as an ordinary, removable filter; the results and the proposals update together. The user keeps searching the way they already do; the AI only points out the facets worth cutting on.\n\n## When to use\n- Search over large, faceted datasets (regulations, documents, records, a pattern catalogue) where a typical query returns too many results and the right facet to narrow on isn't obvious.\n- When the filter UI is rich but buried (\"Add filters\" menus with many fields), so people rarely discover which facet would help.\n- When the best next facet depends on the query and the results — something a static facet sidebar can't know.\n\n## When not to use\n- Result sets that are already short enough to scan.\n- When there is a fixed, well-known facet sidebar people already use; don't duplicate it with an AI panel.\n- To rewrite the query itself or answer the question — use a describe-style or natural-language interface instead.\n\n## Anatomy\n- **Search field** — the existing keyword search, with its submit button.\n- **Applied filters** — removable chips for proposals the user accepted, each marked as AI-suggested, plus a Reset action.\n- **Refine panel** — a soft, inset container with a sparkle and the title \"Refine your search\", and a dismiss (×) button.\n- **Proposal pills** — a value label, the resulting count in parentheses, and a trailing search icon that says \"this runs a search\". Two to three at most.\n- **Loading state** — skeleton pills in the panel while proposals are generated; the panel keeps its height.\n- **Result summary** — \"There are 22 search results sorted by latest update\", above the table.\n\n## Behavior\n- Proposals are requested after each search and after every filter is added or removed, for the result set as it now stands. Stale responses are dropped.\n- Counts are computed by the product from the real results, never taken from the model. Proposals that would leave zero rows, or every row, are not shown.\n- Clicking a pill moves it into the applied filters (a short shared-layout move from panel to chip row), filters the results, and the panel reloads with proposals for the narrower set.\n- Applied chips are ordinary filters: removing one restores the wider set and its proposals. Reset clears filters and query.\n- If no proposal is worth showing, or the request fails, the panel collapses quietly — the search itself never depends on it.\n- Dismissing the panel hides it until the next new search.\n\n## Content guidelines\n- Title: \"Refine your search\" — an invitation, not \"AI suggestions\".\n- Pill labels use the dataset's own vocabulary and values (\"Active\", \"Proposed\", \"Beta\"), not sentences. Keep them to one or two words; the field name goes on the applied chip and the tooltip.\n- Always show the count. It's what lets someone pick a refinement without trying each one.\n- The result summary states the count and the sort order in plain words.\n\n## Accessibility\n- The search is a `role=\"search\"` form; the panel is a labelled `<section>` with `aria-busy` while loading and a `role=\"status\"` message (\"Finding ways to narrow these results\").\n- Each pill is a `<button>` labelled with field, value and count (\"Refine by Status Beta, 6 results\"); the trailing icon is decorative.\n- Applied chips are a labelled list; each remove button names its filter. The AI marker has a text label (\"Suggested by AI\").\n- The result summary is `aria-live=\"polite\"`, so applying or removing a filter announces the new count.\n- Respect `prefers-reduced-motion`: drop the shared-layout move, stagger and skeleton pulse.\n\n## Related patterns\n- **Describe Filters** — Use it instead when people can say what they want in their own words and the AI should build the filters.\n- **Natural Language Query** — Use it instead when people want to see and edit the query behind the results.\n- **Follow-up List** — Use it instead for suggested next questions after an answer, rather than narrowing a result set.\n- **Confidence Indicator** — Use it as well when a proposal matches by meaning and the model can say how sure it is.\n","code":"\"use client\";\n\nimport * as React from \"react\";\nimport { AnimatePresence, LayoutGroup, motion, useReducedMotion } from \"motion/react\";\nimport { RotateCcw, Search, Sparkles, X } from \"lucide-react\";\n\nimport { cn } from \"@/lib/utils\";\n\nexport interface RefineSearchColumn<Row> {\n  key: string;\n  label: string;\n  /** Renders the cell; defaults to `String(row[key])`. */\n  render?: (row: Row) => React.ReactNode;\n  className?: string;\n}\n\n/** A filter the AI proposes for the current results. */\nexport interface RefineProposal<Row> {\n  id: string;\n  /** What the filter narrows on, e.g. \"Status\". Shown on the applied chip. */\n  field: string;\n  /** The value, e.g. \"Beta\". Shown on the proposal pill. */\n  label: string;\n  test: (row: Row) => boolean;\n}\n\nexport interface RefineSearchProps<Row extends { id: string }> {\n  columns: RefineSearchColumn<Row>[];\n  rows: Row[];\n  /** Text the keyword search matches against. */\n  searchText: (row: Row) => string;\n  /**\n   * Proposes filters for the current results. Counts are computed here from\n   * `results`, not trusted from the model, and proposals that wouldn't narrow\n   * the set (0 rows, or every row) are dropped.\n   */\n  onPropose: (query: string, results: Row[], applied: RefineProposal<Row>[]) => Promise<RefineProposal<Row>[]>;\n  initialQuery?: string;\n  placeholder?: string;\n  /** Completes \"There are N search results sorted by …\". */\n  sortLabel?: string;\n  /** Most proposals shown at once. */\n  maxProposals?: number;\n  className?: string;\n}\n\nexport function RefineSearch<Row extends { id: string }>({\n  columns,\n  rows,\n  searchText,\n  onPropose,\n  initialQuery = \"\",\n  placeholder = \"Search\",\n  sortLabel = \"latest update\",\n  maxProposals = 3,\n  className,\n}: RefineSearchProps<Row>) {\n  const reduceMotion = useReducedMotion();\n  const [draft, setDraft] = React.useState(initialQuery);\n  const [query, setQuery] = React.useState(initialQuery);\n  const [applied, setApplied] = React.useState<RefineProposal<Row>[]>([]);\n  /** The last proposal response, tagged with the result set it was for. */\n  const [response, setResponse] = React.useState<{ key: string; proposals: RefineProposal<Row>[] } | null>(null);\n  const [dismissed, setDismissed] = React.useState(false);\n  const requestId = React.useRef(0);\n\n  const results = React.useMemo(() => {\n    const q = query.trim().toLowerCase();\n    return rows.filter(\n      (row) => (!q || searchText(row).toLowerCase().includes(q)) && applied.every((f) => f.test(row))\n    );\n  }, [rows, query, applied, searchText]);\n\n  // Re-propose whenever the result set changes: a new search or a filter\n  // added/removed. Responses for an older result set are ignored, and the\n  // panel shows its loading state until the current one arrives.\n  const key = JSON.stringify([query, applied.map((f) => f.id)]);\n  React.useEffect(() => {\n    const id = ++requestId.current;\n    const appliedKeys = new Set(applied.map((f) => `${f.field}:${f.label}`));\n    onPropose(query, results, applied)\n      .then((next) => {\n        if (id !== requestId.current) return;\n        setResponse({\n          key,\n          proposals: next\n            .filter((p) => !appliedKeys.has(`${p.field}:${p.label}`))\n            .filter((p) => {\n              const n = results.filter(p.test).length;\n              return n > 0 && n < results.length;\n            })\n            .slice(0, maxProposals),\n        });\n      })\n      // A failed request collapses the panel; search keeps working.\n      .catch(() => {\n        if (id === requestId.current) setResponse({ key, proposals: [] });\n      });\n    // `key` captures query + applied; `results` derives from them.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [key]);\n\n  const status = response?.key === key ? \"ready\" : \"loading\";\n  const proposals = status === \"ready\" ? response!.proposals : [];\n\n  function submit(e: React.FormEvent) {\n    e.preventDefault();\n    if (draft.trim() === query.trim()) return;\n    setQuery(draft.trim());\n    setDismissed(false);\n  }\n\n  function apply(p: RefineProposal<Row>) {\n    setApplied((prev) => [...prev, p]);\n  }\n\n  function remove(id: string) {\n    setApplied((prev) => prev.filter((f) => f.id !== id));\n  }\n\n  function reset() {\n    setApplied([]);\n    setDraft(\"\");\n    setQuery(\"\");\n    setDismissed(false);\n  }\n\n  const showPanel = !dismissed && (status === \"loading\" || proposals.length > 0);\n  const transition = reduceMotion ? { duration: 0 } : { type: \"spring\" as const, bounce: 0.15, duration: 0.4 };\n\n  return (\n    <div className={cn(\"w-full overflow-hidden rounded-2xl border bg-card text-sm\", className)}>\n      <LayoutGroup>\n        <div className=\"flex flex-col gap-3 p-3\">\n          {/* Search */}\n          <form onSubmit={submit} role=\"search\" className=\"flex h-10 items-stretch overflow-hidden rounded-lg border bg-background focus-within:ring-2 focus-within:ring-ring/40\">\n            <input\n              value={draft}\n              onChange={(e) => setDraft(e.target.value)}\n              placeholder={placeholder}\n              aria-label=\"Search\"\n              className=\"min-w-0 flex-1 bg-transparent px-3 outline-none placeholder:text-muted-foreground\"\n            />\n            <button\n              type=\"submit\"\n              aria-label=\"Run search\"\n              className=\"flex w-10 shrink-0 items-center justify-center border-l text-muted-foreground transition-colors hover:bg-accent hover:text-foreground\"\n            >\n              <Search className=\"size-4\" />\n            </button>\n          </form>\n\n          {/* Applied filters */}\n          <AnimatePresence initial={false}>\n            {applied.length > 0 && (\n              <motion.div\n                initial={{ height: 0, opacity: 0 }}\n                animate={{ height: \"auto\", opacity: 1 }}\n                exit={{ height: 0, opacity: 0 }}\n                transition={{ duration: reduceMotion ? 0 : 0.18 }}\n                className=\"-mb-1 overflow-hidden\"\n              >\n                <ul aria-label=\"Applied filters\" className=\"flex flex-wrap items-center gap-1.5 pb-1\">\n                  <AnimatePresence initial={false} mode=\"popLayout\">\n                    {applied.map((f) => (\n                      <motion.li\n                        key={f.id}\n                        layoutId={`refine-${f.id}`}\n                        transition={transition}\n                        exit={{ opacity: 0, scale: 0.9 }}\n                        className=\"flex h-7 items-center gap-1.5 rounded-md border bg-background pl-2.5 pr-1 text-xs\"\n                      >\n                        <Sparkles className=\"size-3 shrink-0 text-muted-foreground\" aria-label=\"Suggested by AI\" />\n                        <span className=\"text-muted-foreground\">{f.field}</span>\n                        <span>{f.label}</span>\n                        <button\n                          type=\"button\"\n                          onClick={() => remove(f.id)}\n                          aria-label={`Remove filter: ${f.field} ${f.label}`}\n                          className=\"flex size-5 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent hover:text-foreground\"\n                        >\n                          <X className=\"size-3\" />\n                        </button>\n                      </motion.li>\n                    ))}\n                  </AnimatePresence>\n                  <li>\n                    <button\n                      type=\"button\"\n                      onClick={reset}\n                      className=\"flex h-7 items-center gap-1 rounded-md px-2 text-xs text-muted-foreground transition-colors hover:bg-accent hover:text-foreground\"\n                    >\n                      <RotateCcw className=\"size-3\" aria-hidden />\n                      Reset\n                    </button>\n                  </li>\n                </ul>\n              </motion.div>\n            )}\n          </AnimatePresence>\n\n          {/* AI proposals */}\n          <AnimatePresence initial={false}>\n            {showPanel && (\n              <motion.section\n                key=\"refine\"\n                aria-labelledby=\"refine-search-title\"\n                aria-busy={status === \"loading\"}\n                initial={{ height: 0, opacity: 0 }}\n                animate={{ height: \"auto\", opacity: 1 }}\n                exit={{ height: 0, opacity: 0 }}\n                transition={{ duration: reduceMotion ? 0 : 0.2 }}\n                className=\"overflow-hidden rounded-lg bg-muted/60\"\n              >\n                <div className=\"flex flex-col gap-2.5 px-3 py-3\">\n                  <div className=\"flex items-center gap-1.5\">\n                    <Sparkles\n                      className={cn(\n                        \"size-3.5 shrink-0 text-muted-foreground\",\n                        status === \"loading\" && !reduceMotion && \"animate-pulse\"\n                      )}\n                      aria-hidden\n                    />\n                    <h3 id=\"refine-search-title\" className=\"text-xs font-medium\">\n                      Refine your search\n                    </h3>\n                    <button\n                      type=\"button\"\n                      onClick={() => setDismissed(true)}\n                      aria-label=\"Hide suggestions\"\n                      className=\"ml-auto flex size-6 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent hover:text-foreground\"\n                    >\n                      <X className=\"size-3.5\" />\n                    </button>\n                  </div>\n\n                  <div className=\"flex min-h-7 flex-wrap gap-1.5\">\n                    {status === \"loading\" ? (\n                      <span role=\"status\" className=\"flex flex-wrap gap-1.5\">\n                        <span className=\"sr-only\">Finding ways to narrow these results</span>\n                        {[64, 84, 72].map((w) => (\n                          <span\n                            key={w}\n                            aria-hidden\n                            style={{ width: w }}\n                            className={cn(\"h-7 rounded-md border bg-background/60\", !reduceMotion && \"animate-pulse\")}\n                          />\n                        ))}\n                      </span>\n                    ) : (\n                      proposals.map((p, i) => {\n                        const count = results.filter(p.test).length;\n                        return (\n                          <motion.button\n                            key={p.id}\n                            layoutId={`refine-${p.id}`}\n                            type=\"button\"\n                            onClick={() => apply(p)}\n                            initial={{ opacity: 0, y: 4 }}\n                            animate={{ opacity: 1, y: 0 }}\n                            transition={{ ...transition, delay: reduceMotion ? 0 : i * 0.05 }}\n                            title={`${p.field}: ${p.label}`}\n                            aria-label={`Refine by ${p.field} ${p.label}, ${count} results`}\n                            className=\"flex h-7 items-center gap-1.5 rounded-md border bg-background px-2.5 text-xs transition-colors hover:bg-accent\"\n                          >\n                            <span>{p.label}</span>\n                            <span className=\"text-muted-foreground tabular-nums\">({count})</span>\n                            <Search className=\"size-3 text-muted-foreground\" aria-hidden />\n                          </motion.button>\n                        );\n                      })\n                    )}\n                  </div>\n                </div>\n              </motion.section>\n            )}\n          </AnimatePresence>\n        </div>\n      </LayoutGroup>\n\n      {/* Result count */}\n      <p className=\"border-t px-4 py-2.5 text-xs text-muted-foreground\" aria-live=\"polite\">\n        There {results.length === 1 ? \"is\" : \"are\"}{\" \"}\n        <span className=\"font-medium text-foreground tabular-nums\">{results.length}</span> search{\" \"}\n        {results.length === 1 ? \"result\" : \"results\"} sorted by {sortLabel}\n      </p>\n\n      {/* Results */}\n      <div className=\"max-h-72 overflow-auto border-t\">\n        <table className=\"w-full border-collapse whitespace-nowrap\" aria-busy={status === \"loading\"}>\n          <thead className=\"sticky top-0 z-[1] bg-card\">\n            <tr className=\"border-b text-left text-xs text-muted-foreground\">\n              {columns.map((c) => (\n                <th key={c.key} scope=\"col\" className={cn(\"px-4 py-2 font-medium\", c.className)}>\n                  {c.label}\n                </th>\n              ))}\n            </tr>\n          </thead>\n          <tbody>\n            <AnimatePresence initial={false}>\n              {results.map((row) => (\n                <motion.tr\n                  key={row.id}\n                  layout={reduceMotion ? false : \"position\"}\n                  initial={{ opacity: 0 }}\n                  animate={{ opacity: 1 }}\n                  exit={{ opacity: 0 }}\n                  transition={{ duration: reduceMotion ? 0 : 0.18 }}\n                  className=\"border-b last:border-b-0\"\n                >\n                  {columns.map((c) => (\n                    <td key={c.key} className={cn(\"px-4 py-2.5\", c.className)}>\n                      {c.render ? c.render(row) : String((row as Record<string, unknown>)[c.key] ?? \"\")}\n                    </td>\n                  ))}\n                </motion.tr>\n              ))}\n            </AnimatePresence>\n          </tbody>\n        </table>\n        {results.length === 0 && (\n          <div className=\"flex flex-col items-center gap-2 px-4 py-10 text-center\">\n            <p className=\"text-muted-foreground\">No results match this search.</p>\n            <button\n              type=\"button\"\n              onClick={reset}\n              className=\"text-xs font-medium underline-offset-2 hover:underline\"\n            >\n              Reset search\n            </button>\n          </div>\n        )}\n      </div>\n    </div>\n  );\n}\n","dependencies":["lucide-react","motion"],"localImports":["@/lib/utils"]}