{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "app-search-results",
  "type": "registry:block",
  "title": "App, search results",
  "description": "A results page: a search box, checkbox facets whose counts follow the other filters, active filters as removable chips, a result count that is announced when it changes, and a no-results state with suggestions. Filled, empty, loading and error states.",
  "categories": [
    "app"
  ],
  "dependencies": [
    "lucide-react@^1.49.0",
    "zod@^4.6.5"
  ],
  "registryDependencies": [
    "https://ui.klarhimmel.com/r/badge.json",
    "https://ui.klarhimmel.com/r/block-kit.json",
    "https://ui.klarhimmel.com/r/button.json",
    "https://ui.klarhimmel.com/r/checkbox.json",
    "https://ui.klarhimmel.com/r/editing.json",
    "https://ui.klarhimmel.com/r/input.json",
    "https://ui.klarhimmel.com/r/kit-app.json",
    "https://ui.klarhimmel.com/r/skeleton.json"
  ],
  "files": [
    {
      "path": "src/blocks/app-search-results/spec.ts",
      "type": "registry:file",
      "target": "components/klarhimmel/blocks/app-search-results/spec.ts",
      "content": "import { z } from 'zod';\nimport { defineSpec, req, t } from '../_shared/schema';\n\nconst schema = z.object({\n  eyebrow: t(60).optional(),\n  title: t(120),\n  description: t(300).optional(),\n  searchLabel: req(40),\n  searchButton: req(30),\n  /** The query the page opens with. Typing and pressing the search button filters the results given, by their words. */\n  query: t(80),\n  /** Facets are checkbox groups. A result belongs to the options named in its `matches` (the same words as the option labels), and shows them as tags. Within a facet the options add up (any of); across facets they narrow (all of). */\n  facets: z.array(z.object({ name: t(30), options: z.array(z.object({ label: t(30), checked: z.boolean() })).min(2).max(6) })).min(1).max(3),\n  results: z.array(z.object({ title: t(80), summary: t(160), href: t(300), meta: t(60).optional(), matches: z.array(t(30)).max(3) })).max(12),\n  /** \"5 results for spa\": the count, then these words. `singular` is used for exactly one. */\n  resultsLabel: t(20),\n  singular: t(20),\n  forLabel: t(10),\n  /** The button on each active filter chip says this, then the facet and option. */\n  removeLabel: t(30),\n  clearAll: t(30),\n  filtersLabel: req(30),\n  noResults: z.object({ title: t(80), hint: t(160), suggestionsLabel: t(60) }),\n  suggestions: z.array(t(40)).max(4),\n  /** filled; empty (the search found nothing, whatever the filters); loading (placeholders, said once); error (a banner with a retry). */\n  state: z.enum(['filled', 'empty', 'loading', 'error']),\n  messages: z.object({ loading: t(60), error: t(120), retry: t(30) }),\n});\n\nexport const spec = defineSpec({\n  type: 'app-search-results',\n  aliases: ['app/search-results'],\n  name: 'App, search results',\n  category: 'app',\n  role: 'body',\n  description: 'A results page: a search box, checkbox facets whose counts follow the other filters, active filters as removable chips, a result count that is announced when it changes, and a no-results state with suggestions. Filled, empty, loading and error states.',\n  schema,\n  defaults: {\n    \"eyebrow\": \"Name the section\",\n    \"title\": \"Name what is searched\",\n    \"description\": \"Say which kinds of things this search covers.\",\n    \"searchLabel\": \"Search\",\n    \"searchButton\": \"Search\",\n    \"query\": \"Name\",\n    \"facets\": [\n      {\n        \"name\": \"Type\",\n        \"options\": [\n          {\n            \"label\": \"First type\",\n            \"checked\": false\n          },\n          {\n            \"label\": \"Second type\",\n            \"checked\": false\n          },\n          {\n            \"label\": \"Third type\",\n            \"checked\": false\n          }\n        ]\n      },\n      {\n        \"name\": \"Price\",\n        \"options\": [\n          {\n            \"label\": \"First price band\",\n            \"checked\": false\n          },\n          {\n            \"label\": \"Second price band\",\n            \"checked\": false\n          }\n        ]\n      }\n    ],\n    \"results\": [\n      {\n        \"title\": \"Name the first result\",\n        \"summary\": \"Say in one sentence what this result is and what it includes.\",\n        \"href\": \"#spa-day\",\n        \"meta\": \"Type of result · $00\",\n        \"matches\": [\n          \"First type\",\n          \"Second price band\"\n        ]\n      },\n      {\n        \"title\": \"Name the second result\",\n        \"summary\": \"Say in one sentence what this result is and where it happens.\",\n        \"href\": \"#massage\",\n        \"meta\": \"Type of result · $00\",\n        \"matches\": [\n          \"First type\",\n          \"First price band\"\n        ]\n      },\n      {\n        \"title\": \"Name the third result\",\n        \"summary\": \"Say in one sentence what this result is and what comes with it.\",\n        \"href\": \"#room-311\",\n        \"meta\": \"Type of result · $00\",\n        \"matches\": [\n          \"Second type\",\n          \"Second price band\"\n        ]\n      },\n      {\n        \"title\": \"Name the fourth result\",\n        \"summary\": \"Say in one sentence who this result is for and what it covers.\",\n        \"href\": \"#group-weekend\",\n        \"meta\": \"Type of result · $00\",\n        \"matches\": [\n          \"Third type\",\n          \"Second price band\"\n        ]\n      },\n      {\n        \"title\": \"Name the fifth result\",\n        \"summary\": \"Say in one sentence what this result is and how it arrives.\",\n        \"href\": \"#gift-card\",\n        \"meta\": \"Type of result · $00\",\n        \"matches\": [\n          \"First type\",\n          \"First price band\"\n        ]\n      }\n    ],\n    \"resultsLabel\": \"results\",\n    \"singular\": \"result\",\n    \"forLabel\": \"for\",\n    \"removeLabel\": \"Remove filter\",\n    \"clearAll\": \"Clear every filter\",\n    \"filtersLabel\": \"Filters\",\n    \"noResults\": {\n      \"title\": \"Say that nothing matches\",\n      \"hint\": \"Say what to try: spelling, fewer words, fewer filters.\",\n      \"suggestionsLabel\": \"Try one of these\"\n    },\n    \"suggestions\": [\n      \"First result\",\n      \"Second result\",\n      \"Third result\"\n    ],\n    \"state\": \"filled\",\n    \"messages\": {\n      \"loading\": \"Searching…\",\n      \"error\": \"Say the search failed and to retry.\",\n      \"retry\": \"Try again\"\n    }\n  },\n});\n"
    },
    {
      "path": "src/blocks/app-search-results/index.tsx",
      "type": "registry:file",
      "target": "components/klarhimmel/blocks/app-search-results/index.tsx",
      "content": "import { useEffect, useId, useMemo, useRef, useState, type FormEvent } from 'react';\nimport { AlertCircle, Search, X } from 'lucide-react';\nimport { Text, withHeadingLevel } from '../../editing';\nimport { Badge } from '../../ui/badge';\nimport { Button, safeHref } from '../../ui/button';\nimport { Checkbox } from '../../ui/checkbox';\nimport { Input } from '../../ui/input';\nimport { Skeleton } from '../../ui/skeleton';\nimport { Container, Named, Opt, Section, SectionHeader, useEditing, useNamed } from '../_shared/kit';\nimport { AppPanel, StateSlot, useSynced } from '../_shared/app-kit';\nimport { spec } from './spec';\nimport type { BlockProps } from '../types';\nimport type { z } from 'zod';\n\nexport { spec };\ntype Props = z.infer<typeof spec.schema>;\n\nconst initial = (facets: Props['facets']) => new Set(facets.flatMap((f, fi) => f.options.flatMap((o, oi) => (o.checked ? [`${fi}:${oi}`] : []))));\n\nfunction AppSearchResults({ props }: BlockProps<Props>) {\n  const searchNamed = useNamed(props.searchLabel);\n  const id = useId();\n  const editing = useEditing();\n  // Ticks, the typed text and the query follow the data they came from, compared by content: a parent that rebuilds its arrays\n  // on every render does not wipe what the person did, and new data starts them over.\n  const [keys, setKeys] = useSynced<string[]>([...initial(props.facets)]);\n  const checked = useMemo(() => new Set(keys), [keys]);\n  const setChecked = (f: Set<string> | ((s: Set<string>) => Set<string>)) => setKeys((prev) => [...(typeof f === 'function' ? f(new Set(prev)) : f)]);\n  const [typed, setTyped] = useSynced(props.query);\n  const [query, setQuery] = useSynced(props.query);\n  const [retried, setRetried] = useSynced(false, props.state);\n  const state = retried && props.state === 'error' ? 'loading' : props.state;\n  const loadingMsg = useRef<HTMLParagraphElement>(null);\n  const justRetried = useRef(false);\n  useEffect(() => {\n    if (justRetried.current) loadingMsg.current?.focus();\n    justRetried.current = false;\n  }, [retried]);\n  const input = useRef<HTMLInputElement>(null);\n  const status = useRef<HTMLParagraphElement>(null);\n  const [toStatus, setToStatus] = useState(false);\n  /** Focus moved to the count after a removal: that count is read once, from focus, not again from the live region. */\n  const [byFocus, setByFocus] = useState(false);\n  useEffect(() => {\n    if (toStatus) status.current?.focus();\n    setToStatus(false);\n  }, [toStatus]);\n\n  const terms = query.toLowerCase().split(/\\s+/).filter(Boolean);\n  const selected = props.facets.map((f, fi) => f.options.filter((_, oi) => checked.has(`${fi}:${oi}`)).map((o) => o.label));\n  const textOk = (r: Props['results'][number]) => terms.every((w) => `${r.title} ${r.summary}`.toLowerCase().includes(w));\n  /** A result passes a facet when no option of it is ticked or one it belongs to is; `skip` leaves a facet out (for its own counts). */\n  const passes = (r: Props['results'][number], skip = -1) => selected.every((sel, fi) => fi === skip || sel.length === 0 || r.matches.some((m) => sel.includes(m)));\n  const visible = useMemo(() => (state === 'filled' ? props.results.filter((r) => textOk(r) && passes(r)) : []), [props.results, state, query, checked]); // eslint-disable-line react-hooks/exhaustive-deps\n  const count = (fi: number, label: string) => props.results.filter((r) => textOk(r) && passes(r, fi) && r.matches.includes(label)).length;\n  const active = props.facets.flatMap((f, fi) => f.options.flatMap((o, oi) => (checked.has(`${fi}:${oi}`) ? [{ fi, oi, facet: f.name, label: o.label }] : [])));\n  const none = state === 'empty' || (state === 'filled' && visible.length === 0);\n  const n = visible.length;\n  const summary = `${n} ${n === 1 ? props.singular : props.resultsLabel}${query ? ` ${props.forLabel} “${query}”` : ''}`;\n  const toggle = (key: string, on: boolean) => {\n    setByFocus(false);\n    setChecked((s) => { const next = new Set(s); if (on) next.add(key); else next.delete(key); return next; });\n  };\n  const search = (e: FormEvent) => {\n    e.preventDefault();\n    setByFocus(false);\n    setQuery(typed.trim());\n  };\n  const loading = state === 'loading';\n  return (\n    <Section labelledBy={id}>\n      <Container>\n        <SectionHeader id={id} eyebrow={props.eyebrow} title={props.title} description={props.description} />\n        {searchNamed && (\n        <form role=\"search\" aria-label={props.searchLabel} onSubmit={search} className=\"mt-8 flex flex-col gap-3 @md:flex-row\">\n          <label htmlFor={`${id}-q`} className=\"sr-only\">\n            <Text path={['searchLabel']} value={props.searchLabel} as=\"span\" />\n          </label>\n          <Input ref={input} id={`${id}-q`} type=\"search\" name=\"q\" value={typed} onChange={(e) => setTyped(e.target.value)} autoComplete=\"off\" className=\"@md:flex-1\" />\n          <Button type=\"submit\" icon={<Search aria-hidden className=\"size-4\" />}>\n            <Text path={['searchButton']} value={props.searchButton} as=\"span\" />\n          </Button>\n        </form>\n        )}\n        {editing && (\n          <p className=\"mt-3 text-kh-caption text-kh-muted\">\n            <Text path={['resultsLabel']} value={props.resultsLabel} as=\"span\" /> · <Text path={['singular']} value={props.singular} as=\"span\" /> · <Text path={['forLabel']} value={props.forLabel} as=\"span\" /> · <Text path={['removeLabel']} value={props.removeLabel} as=\"span\" /> · <Text path={['filtersLabel']} value={props.filtersLabel} as=\"span\" />\n          </p>\n        )}\n        <div className=\"mt-8 grid gap-8 @3xl:grid-cols-[16rem_1fr] @3xl:items-start\">\n          <div className=\"flex min-w-0 flex-col gap-6\">\n            <Named as=\"h3\" className=\"text-kh-small font-semibold\">\n              <Text path={['filtersLabel']} value={props.filtersLabel} as=\"span\" />\n            </Named>\n            {props.facets.map((f, fi) => (\n              <fieldset key={fi} className=\"min-w-0\">\n                <legend className=\"mb-1 text-kh-small font-medium\">\n                  <Text path={['facets', fi, 'name']} value={f.name} as=\"span\" />\n                </legend>\n                <div className=\"flex flex-col\">\n                  {f.options.map((o, oi) => (\n                    <Checkbox\n                      key={oi}\n                      checked={checked.has(`${fi}:${oi}`)}\n                      onCheckedChange={(on) => toggle(`${fi}:${oi}`, on)}\n                      disabled={loading}\n                      label={\n                        <span className=\"flex items-baseline gap-2\">\n                          <Text path={['facets', fi, 'options', oi, 'label']} value={o.label} as=\"span\" />\n                          <span className=\"text-kh-caption text-kh-muted tabular-nums\">{state === 'filled' ? `(${count(fi, o.label)})` : ''}</span>\n                        </span>\n                      }\n                    />\n                  ))}\n                </div>\n              </fieldset>\n            ))}\n          </div>\n\n          <div className=\"min-w-0\" aria-busy={loading || undefined}>\n            <StateSlot show={state === 'error'}>\n              <div role=\"alert\" className=\"mb-4 flex flex-wrap items-center gap-3 rounded-kh-lg border border-kh-danger px-4 py-3 text-kh-small\">\n                <AlertCircle aria-hidden className=\"size-4 text-kh-danger\" />\n                <Text path={['messages', 'error']} value={props.messages.error} as=\"span\" />\n                <Button\n                  type=\"button\"\n                  variant=\"secondary\"\n                  onClick={() => {\n                    justRetried.current = true;\n                    setRetried(true);\n                  }}\n                >\n                  <Text path={['messages', 'retry']} value={props.messages.retry} as=\"span\" />\n                </Button>\n              </div>\n            </StateSlot>\n            <StateSlot show={loading}>\n              <div ref={loadingMsg} tabIndex={-1} role=\"status\" className=\"mb-4 text-kh-small text-kh-muted outline-none\">\n                <Text path={['messages', 'loading']} value={props.messages.loading} as=\"span\" />\n              </div>\n              <div aria-hidden className=\"flex flex-col gap-4\">\n                <Skeleton className=\"h-24 w-full\" />\n                <Skeleton className=\"h-24 w-full\" />\n                <Skeleton className=\"h-24 w-full\" />\n              </div>\n            </StateSlot>\n            {state !== 'loading' && state !== 'error' && (\n              <>\n                <p ref={status} role=\"status\" aria-live={byFocus ? 'off' : undefined} tabIndex={-1} className=\"text-kh-small font-medium outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-(--kh-focus)\">\n                  {state === 'empty' ? `0 ${props.resultsLabel}${query ? ` ${props.forLabel} “${query}”` : ''}` : summary}\n                </p>\n                {(active.length > 0 || editing) && (\n                  <ul aria-label={props.filtersLabel} className=\"mt-3 flex flex-wrap items-center gap-2\">\n                    {active.map((a) => (\n                      <li key={`${a.fi}:${a.oi}`}>\n                        <Badge tone=\"outline\" className=\"gap-1 pr-1\">\n                          {a.facet}: {a.label}\n                          <button\n                            type=\"button\"\n                            aria-label={`${props.removeLabel}: ${a.facet}: ${a.label}`}\n                            onClick={() => {\n                              toggle(`${a.fi}:${a.oi}`, false);\n                              setByFocus(true);\n                              setToStatus(true);\n                            }}\n                            className=\"relative inline-flex size-6 items-center justify-center rounded-kh-pill text-kh-muted hover:bg-kh-surface-2 hover:text-kh-ink after:absolute after:-inset-2 after:content-[''] focus-visible:outline-2 focus-visible:outline-(--kh-focus)\"\n                          >\n                            <X aria-hidden className=\"size-3.5\" />\n                          </button>\n                        </Badge>\n                      </li>\n                    ))}\n                    <li>\n                      <Button\n                        type=\"button\"\n                        variant=\"ghost\"\n                        onClick={() => {\n                          setChecked(new Set());\n                          setByFocus(true);\n                          setToStatus(true);\n                        }}\n                      >\n                        <Text path={['clearAll']} value={props.clearAll} as=\"span\" />\n                      </Button>\n                    </li>\n                  </ul>\n                )}\n                {state === 'filled' && visible.length > 0 && (\n                  <ol className=\"mt-4 flex flex-col gap-4\">\n                    {visible.map((r) => {\n                      const ri = props.results.indexOf(r);\n                      return (\n                        <li key={ri}>\n                          <AppPanel className=\"p-4 @xl:p-5\">\n                            <h4 className=\"text-kh-body font-semibold [overflow-wrap:anywhere]\">\n                              <a href={safeHref(r.href)} className=\"inline-block rounded-kh-sm py-0.5 underline-offset-4 hover:underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-(--kh-focus)\">\n                                <Text path={['results', ri, 'title']} value={r.title} as=\"span\" />\n                              </a>\n                            </h4>\n                            <Text path={['results', ri, 'summary']} value={r.summary} as=\"p\" className=\"mt-1 text-kh-small text-kh-muted\" />\n                            <Opt path={['results', ri, 'meta']} value={r.meta} as=\"p\" className=\"mt-2 text-kh-caption text-kh-muted\" placeholder=\"Meta\" />\n                            <ul className=\"mt-3 flex flex-wrap gap-1.5\">\n                              {r.matches.map((m, k) => (\n                                <li key={k}>\n                                  <Badge tone=\"outline\">\n                                    <Text path={['results', ri, 'matches', k]} value={m} as=\"span\" />\n                                  </Badge>\n                                </li>\n                              ))}\n                            </ul>\n                          </AppPanel>\n                        </li>\n                      );\n                    })}\n                  </ol>\n                )}\n              </>\n            )}\n            <StateSlot show={none}>\n              <div className=\"mt-6 rounded-kh-xl border border-dashed border-kh-line-strong p-6 text-center\">\n                <p className=\"text-kh-body font-semibold\">\n                  <Text path={['noResults', 'title']} value={props.noResults.title} as=\"span\" />\n                </p>\n                <p className=\"mt-1 text-kh-small text-kh-muted\">\n                  <Text path={['noResults', 'hint']} value={props.noResults.hint} as=\"span\" />\n                </p>\n                <p className=\"mt-4 text-kh-small font-medium\">\n                  <Text path={['noResults', 'suggestionsLabel']} value={props.noResults.suggestionsLabel} as=\"span\" />\n                </p>\n                <ul className=\"mt-2 flex flex-wrap justify-center gap-2\">\n                  {props.suggestions.map((s, i) => (\n                    <li key={i}>\n                      <Button\n                        type=\"button\"\n                        variant=\"secondary\"\n                        onClick={() => {\n                          setTyped(s);\n                          setQuery(s);\n                          setChecked(new Set());\n                          input.current?.focus();\n                        }}\n                      >\n                        <Text path={['suggestions', i]} value={s} as=\"span\" />\n                      </Button>\n                    </li>\n                  ))}\n                </ul>\n              </div>\n            </StateSlot>\n          </div>\n        </div>\n      </Container>\n    </Section>\n  );\n}\n\nexport default withHeadingLevel(AppSearchResults);\n"
    }
  ]
}
