{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "pages-find-record",
  "title": "Find a record page",
  "description": "The page of a records place whose entity the session may read but not list: find one record by its identifier or a lookup selector.",
  "dependencies": [
    "@registrystack/app-runtime@~0.43.0-next.0"
  ],
  "registryDependencies": [
    "@registrystack/lib-content",
    "@registrystack/lib-format",
    "@registrystack/field-renderers",
    "@registrystack/pages-content",
    "@registrystack/record-summary",
    "@registrystack/shell-error-panel",
    "@registrystack/shell-page-heading",
    "@registrystack/shell-routing",
    "@registrystack/ui-button",
    "@registrystack/ui-input"
  ],
  "files": [
    {
      "path": "pages/find-record-page.tsx",
      "content": "import { useEffect, useId, useRef, useState } from \"react\";\nimport {\n  problemView,\n  type EntityModel,\n  type LookupModel,\n  type RecordView,\n} from \"@registrystack/app-runtime\";\nimport { useRecord, useRecordLookup } from \"@registrystack/app-runtime/react\";\nimport { Button } from \"@/components/ui/button\";\nimport { Input } from \"@/components/ui/input\";\nimport { YesNoSelect } from \"@/blocks/fields/input-field\";\nimport { RecordFacts } from \"@/blocks/record/record-summary\";\nimport { useLocale } from \"@/blocks/lib/content\";\nimport { fill, inSentence, selectorNamedFor } from \"@/blocks/lib/format\";\nimport { ErrorPanel } from \"@/blocks/shell/error-panel\";\nimport { PageHeading } from \"@/blocks/shell/page-heading\";\nimport { navigate } from \"@/blocks/shell/routing\";\nimport { usePagesContent } from \"@/blocks/pages/pages-content\";\n\n/**\n * The page of a records place whose entity the session may read but not\n * list: it finds one record from what the person already holds. Nothing here\n * enumerates records. A record the session cannot read, one outside its\n * boundary and one that does not exist read the same way, so the page never\n * says which of them an identifier was. A BReg lookup selector the session may\n * use gets a form of its own; its values go to the host in a request body.\n */\nexport function FindRecordPage({\n  entity,\n  recordRoute,\n}: {\n  entity: EntityModel;\n  recordRoute: (id: string) => string;\n}) {\n  const pages = usePagesContent();\n  const locale = useLocale();\n  const selectors = entity.operations.lookup?.selectors ?? [];\n  const lookupHeading =\n    selectors[0] && selectorNamedFor(selectors[0], entity.label, locale);\n  return (\n    <>\n      <PageHeading\n        title={fill(\n          pages.findRecordTitle,\n          { records: inSentence(entity.pluralLabel, locale) },\n          locale,\n        )}\n        description={pages.findRecordDescription}\n      />\n      {selectors.map((selector) => (\n        <LookupForm\n          key={selector.id}\n          entity={entity}\n          selector={selector}\n          disclosed={entity.operations.lookup!.disclosed}\n          recordRoute={recordRoute}\n        />\n      ))}\n      {entity.operations.get && (\n        <OpenById\n          entity={entity}\n          recordRoute={recordRoute}\n          lookupHeading={lookupHeading}\n        />\n      )}\n    </>\n  );\n}\n\n/**\n * One lookup selector as a form. A match opens the record page where the\n * session may read the record, and otherwise shows the fields the lookup\n * discloses. A refusal, an out-of-boundary record and a non-match all read as\n * the one no-match answer. An answer shows only beside the values it answers:\n * the fields hold still while a lookup is pending, and a change clears it. A\n * lookup that answers after the person left the page changes nothing.\n */\nfunction LookupForm({\n  entity,\n  selector,\n  disclosed,\n  recordRoute,\n}: {\n  entity: EntityModel;\n  selector: LookupModel[\"selectors\"][number];\n  disclosed: string[];\n  recordRoute: (id: string) => string;\n}) {\n  const pages = usePagesContent();\n  const locale = useLocale();\n  const formId = useId();\n  const { lookup, pending, error } = useRecordLookup(entity.id);\n  const [values, setValues] = useState<Record<string, string>>({});\n  const [outcome, setOutcome] = useState<\"none\" | RecordView>(\"none\");\n  const [edited, setEdited] = useState(false);\n  const shown = useRef(true);\n  useEffect(() => {\n    shown.current = true;\n    return () => {\n      shown.current = false;\n    };\n  }, []);\n  async function submit() {\n    setEdited(false);\n    const found = await lookup(selector.id, values);\n    if (!shown.current) return;\n    if (found && entity.operations.get) navigate(recordRoute(found.id));\n    else setOutcome(found ?? \"none\");\n  }\n  return (\n    <section aria-labelledby={`${formId}-heading`}>\n      <h2 id={`${formId}-heading`}>\n        {selectorNamedFor(selector, entity.label, locale)}\n      </h2>\n      <form\n        className=\"search-form\"\n        onSubmit={(event) => {\n          event.preventDefault();\n          void submit();\n        }}\n      >\n        {selector.fields.map((field) => {\n          const id = `${formId}-${field.id}`;\n          const value = values[field.id] ?? \"\";\n          const change = (typed: string) => {\n            setValues({ ...values, [field.id]: typed });\n            setOutcome(\"none\");\n            setEdited(true);\n          };\n          return (\n            <div key={field.id}>\n              <label htmlFor={id}>{field.label}</label>\n              {field.type === \"boolean\" ? (\n                // The host sends the choice's \"true\" or \"false\" as JSON.\n                <YesNoSelect\n                  id={id}\n                  value={value === \"\" ? undefined : value === \"true\"}\n                  required={field.required}\n                  disabled={pending}\n                  onChange={(chosen) =>\n                    change(chosen === undefined ? \"\" : String(chosen))\n                  }\n                />\n              ) : (\n                <Input\n                  id={id}\n                  value={value}\n                  required={field.required}\n                  readOnly={pending}\n                  autoComplete=\"off\"\n                  {...(field.type === \"integer\"\n                    ? { inputMode: \"numeric\" as const }\n                    : {})}\n                  onChange={(event) => change(event.target.value)}\n                />\n              )}\n            </div>\n          );\n        })}\n        <Button type=\"submit\" variant=\"outline\" disabled={pending}>\n          {pages.lookupSubmit}\n        </Button>\n      </form>\n      {!edited && error != null && (\n        <FindFailure error={error} retry={() => void submit()} />\n      )}\n      {typeof outcome === \"object\" && (\n        <div role=\"status\">\n          <h3>{pages.lookupResultHeading}</h3>\n          <RecordFacts entity={entity} record={outcome} fields={disclosed} />\n        </div>\n      )}\n    </section>\n  );\n}\n\n/** A registry record identifier: a UUID. */\nconst recordIdentifier =\n  /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/**\n * Opens the record with a typed identifier through the same exact read the\n * reference picker uses; the identifier is sent in the host's request path\n * only when the person submits it. A value that cannot be a record identifier\n * is not sent: the page says what the box takes and, where the page also\n * finds by code, points to that form. Beside a find by code, the identifier\n * is a secondary way in, folded behind its heading.\n */\nfunction OpenById({\n  entity,\n  recordRoute,\n  lookupHeading,\n}: {\n  entity: EntityModel;\n  recordRoute: (id: string) => string;\n  lookupHeading?: string | undefined;\n}) {\n  const pages = usePagesContent();\n  const locale = useLocale();\n  const [typed, setTyped] = useState(\"\");\n  const [asked, setAsked] = useState(\"\");\n  const [notIdentifier, setNotIdentifier] = useState(false);\n  const inputId = useId();\n  const record = useRecord(entity.id, asked);\n  const requested = asked !== \"\" && asked === typed.trim();\n  const found = requested && !record.isFetching && !record.error && record.data;\n  useEffect(() => {\n    if (found) navigate(recordRoute(found.id));\n  }, [found && found.id]);\n  const body = (\n    <>\n      <form\n        className=\"search-form\"\n        onSubmit={(event) => {\n          event.preventDefault();\n          const id = typed.trim();\n          if (!id) return;\n          if (!recordIdentifier.test(id)) {\n            setNotIdentifier(true);\n            return;\n          }\n          if (id === asked) void record.refetch();\n          else setAsked(id);\n        }}\n      >\n        <div>\n          <label htmlFor={inputId}>{pages.openByIdLabel}</label>\n          <Input\n            id={inputId}\n            value={typed}\n            autoComplete=\"off\"\n            onChange={(event) => {\n              setTyped(event.target.value);\n              setNotIdentifier(false);\n            }}\n          />\n        </div>\n        <Button type=\"submit\" variant=\"outline\" disabled={!typed.trim()}>\n          {pages.openByIdSubmit}\n        </Button>\n      </form>\n      {notIdentifier && (\n        <p role=\"status\">\n          {pages.openByIdNotIdentifier}\n          {lookupHeading &&\n            ` ${fill(pages.openByIdUseLookup, { selector: lookupHeading }, locale)}`}\n        </p>\n      )}\n      {requested && record.error && (\n        <FindFailure\n          error={record.error}\n          retry={() => void record.refetch()}\n        />\n      )}\n    </>\n  );\n  if (lookupHeading)\n    return (\n      <details className=\"alternative\">\n        <summary>{pages.openByIdHeading}</summary>\n        {body}\n      </details>\n    );\n  return (\n    <section aria-labelledby={`${inputId}-heading`}>\n      <h2 id={`${inputId}-heading`}>{pages.openByIdHeading}</h2>\n      {body}\n    </section>\n  );\n}\n\n/**\n * Why a find ended without a record. Only the uniform unavailable answer\n * reads as no match, since it says nothing of whether the record exists; any\n * other failure is the service not answering and offers a retry.\n */\nexport function FindFailure({\n  error,\n  retry,\n}: {\n  error: unknown;\n  retry: () => void;\n}) {\n  const pages = usePagesContent();\n  if (problemView(error).kind === \"unavailable\")\n    return <p role=\"status\">{pages.findNoMatch}</p>;\n  return <ErrorPanel error={error} retry={retry} />;\n}\n",
      "type": "registry:block",
      "target": "@components/pages/find-record-page.tsx"
    }
  ],
  "type": "registry:block"
}