{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "app-comments-thread",
  "type": "registry:block",
  "title": "App, comment thread",
  "description": "A discussion between people: comments with author and time, replies one level deep, a Reply button that opens a form under its comment (focus moves in and back), and a composer. Posting adds to the thread in place, clears the field and announces it. Filled, empty, posting and error states.",
  "categories": [
    "app"
  ],
  "dependencies": [
    "lucide-react@^1.49.0",
    "zod@^4.6.5"
  ],
  "registryDependencies": [
    "https://ui.klarhimmel.com/r/avatar.json",
    "https://ui.klarhimmel.com/r/banner.json",
    "https://ui.klarhimmel.com/r/block-kit.json",
    "https://ui.klarhimmel.com/r/button.json",
    "https://ui.klarhimmel.com/r/editing.json",
    "https://ui.klarhimmel.com/r/empty-state.json",
    "https://ui.klarhimmel.com/r/input.json",
    "https://ui.klarhimmel.com/r/kit-app.json"
  ],
  "files": [
    {
      "path": "src/blocks/app-comments-thread/spec.ts",
      "type": "registry:file",
      "target": "components/klarhimmel/blocks/app-comments-thread/spec.ts",
      "content": "import { z } from 'zod';\nimport { defineSpec, t, req } from '../_shared/schema';\n\nconst reply = z.object({ author: t(40), time: t(20), body: t(300) });\n\nconst schema = z.object({\n  eyebrow: t(60).optional(),\n  title: t(120),\n  description: t(300).optional(),\n  /** Follows the number of comments and replies: \"3 comments\". */\n  summaryWord: t(20),\n  comments: z.array(reply.extend({ replies: z.array(reply).max(3) })).min(1).max(4),\n  /** The Reply button's text; the author's name follows it for screen readers. */\n  replyLabel: t(20),\n  /** The small form that opens under a comment. */\n  replyForm: z.object({ label: req(40), submit: req(30), cancel: t(20) }),\n  composer: z.object({ label: req(40), submit: req(30), posting: t(30), empty: t(80) }),\n  /** Who a comment written here is from, and when. */\n  you: t(24),\n  justNow: t(24),\n  /** Said after a post, shown and announced. */\n  notices: z.object({ posted: t(40), replied: t(40) }),\n  /** filled: the thread. empty: no comments yet. posting: the composer waits. error: the composer's post failed. */\n  state: z.enum(['filled', 'empty', 'posting', 'error']),\n  messages: z.object({ emptyTitle: req(80), emptyBody: t(160), error: t(120) }),\n});\n\nexport const spec = defineSpec({\n  type: 'app-comments-thread',\n  aliases: ['app/comments-thread'],\n  name: 'App, comment thread',\n  category: 'app',\n  role: 'body',\n  description: 'A discussion between people: comments with author and time, replies one level deep, a Reply button that opens a form under its comment (focus moves in and back), and a composer. Posting adds to the thread in place, clears the field and announces it. Filled, empty, posting and error states.',\n  schema,\n  defaults: {\n    \"eyebrow\": \"Discussion\",\n    \"title\": \"Name the discussion\",\n    \"description\": \"Say who can see this.\",\n    \"summaryWord\": \"comments\",\n    \"comments\": [\n      {\n        \"author\": \"Person one\",\n        \"time\": \"0 hours ago\",\n        \"body\": \"Write a comment of one or two sentences, with a question for the team.\",\n        \"replies\": [\n          {\n            \"author\": \"Person two\",\n            \"time\": \"0 hour ago\",\n            \"body\": \"Write a short reply to the comment.\"\n          },\n          {\n            \"author\": \"Person one\",\n            \"time\": \"00 minutes ago\",\n            \"body\": \"Write a short answer back.\"\n          }\n        ]\n      }\n    ],\n    \"replyLabel\": \"Reply\",\n    \"replyForm\": {\n      \"label\": \"Your reply\",\n      \"submit\": \"Send reply\",\n      \"cancel\": \"Cancel\"\n    },\n    \"composer\": {\n      \"label\": \"Add a comment\",\n      \"submit\": \"Post comment\",\n      \"posting\": \"Posting…\",\n      \"empty\": \"Say to write something first.\"\n    },\n    \"you\": \"You\",\n    \"justNow\": \"just now\",\n    \"notices\": {\n      \"posted\": \"Comment posted.\",\n      \"replied\": \"Reply posted.\"\n    },\n    \"state\": \"filled\",\n    \"messages\": {\n      \"emptyTitle\": \"No comments yet\",\n      \"emptyBody\": \"Say what starting the discussion does.\",\n      \"error\": \"Say the post failed and to retry.\"\n    }\n  },\n});\n"
    },
    {
      "path": "src/blocks/app-comments-thread/index.tsx",
      "type": "registry:file",
      "target": "components/klarhimmel/blocks/app-comments-thread/index.tsx",
      "content": "import { useEffect, useId, useRef, type FormEvent } from 'react';\nimport { MessageSquare } from 'lucide-react';\nimport { Text, withHeadingLevel } from '../../editing';\nimport { Avatar } from '../../ui/avatar';\nimport { Banner } from '../../ui/banner';\nimport { Button } from '../../ui/button';\nimport { EmptyState } from '../../ui/empty-state';\nimport { Textarea } from '../../ui/input';\nimport { Container, 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>;\ntype Entry = { author: string; time: string; body: string };\n\nfunction Byline({ path, c }: { path: (string | number)[]; c: Entry }) {\n  return (\n    <p className=\"flex flex-wrap items-baseline gap-x-2\">\n      <Text path={[...path, 'author']} value={c.author} as=\"span\" className=\"text-kh-small font-semibold\" />\n      <Text path={[...path, 'time']} value={c.time} as=\"span\" className=\"text-kh-caption text-kh-muted\" />\n    </p>\n  );\n}\n\nfunction AppCommentsThread({ props }: BlockProps<Props>) {\n  const composerNamed = useNamed(props.composer.label);\n  const id = useId();\n  const editing = useEditing();\n  const { state } = props;\n  const posting = state === 'posting';\n  // What people add here lives in this block; it starts over when the thread's own props change.\n  const [open, setOpen] = useSynced<number | null>(null, props.comments);\n  const [added, setAdded] = useSynced<{ at: number | null; entry: Entry }[]>([], props.comments);\n  const [notice, setNotice] = useSynced('', props.comments);\n  const [bad, setBad] = useSynced<'reply' | 'new' | null>(null, props.comments);\n  const replyBtn = useRef<Record<number, HTMLButtonElement | null>>({});\n  const replyBox = useRef<HTMLTextAreaElement>(null);\n  const newBox = useRef<HTMLTextAreaElement>(null);\n  const root = useRef<HTMLOListElement>(null);\n  const focusNext = useRef<{ k: 'field' | 'button' | 'new-entry' | 'composer'; i?: number } | null>(null);\n  useEffect(() => {\n    const f = focusNext.current;\n    focusNext.current = null;\n    if (!f) return;\n    if (f.k === 'field') replyBox.current?.focus();\n    else if (f.k === 'composer') newBox.current?.focus();\n    else if (f.k === 'button') replyBtn.current[f.i!]?.focus();\n    else if (f.k === 'new-entry') root.current?.querySelector<HTMLElement>('[data-new=\"true\"]:last-of-type, [data-new=\"true\"]')?.focus();\n  });\n  const closeReply = (to: number | null) => {\n    focusNext.current = { k: 'button', i: to ?? 0 };\n    replyBox.current?.form?.reset(); // a draft is dropped with the form\n    setOpen(null);\n  };\n  const tops = [...props.comments.map((c, i) => ({ c, i, isNew: false })), ...added.filter((a) => a.at === null).map((a, k) => ({ c: { ...a.entry, replies: [] as Entry[] }, i: props.comments.length + k, isNew: true }))];\n  const total = props.comments.reduce((n, c) => n + 1 + c.replies.length, 0) + added.length;\n  const sendReply = (e: FormEvent<HTMLFormElement>, at: number) => {\n    e.preventDefault();\n    const body = replyBox.current?.value.trim() ?? '';\n    if (!body) {\n      setBad('reply');\n      replyBox.current?.focus();\n      return;\n    }\n    setAdded((a) => [...a, { at, entry: { author: props.you, time: props.justNow, body } }]);\n    e.currentTarget.reset(); // a reopened form starts empty\n    setNotice(props.notices.replied);\n    setBad(null);\n    focusNext.current = { k: 'new-entry' };\n    setOpen(null);\n  };\n  const post = (e: FormEvent<HTMLFormElement>) => {\n    e.preventDefault();\n    if (posting) return;\n    const body = newBox.current?.value.trim() ?? '';\n    if (!body) {\n      setBad('new');\n      newBox.current?.focus();\n      return;\n    }\n    setAdded((a) => [...a, { at: null, entry: { author: props.you, time: props.justNow, body } }]);\n    setNotice(props.notices.posted);\n    setBad(null);\n    e.currentTarget.reset();\n    focusNext.current = { k: 'composer' };\n  };\n  return (\n    <Section labelledBy={id}>\n      <Container width=\"narrow\">\n        <SectionHeader id={id} eyebrow={props.eyebrow} title={props.title} description={props.description} />\n        <AppPanel className=\"mt-10\">\n          <StateSlot show={state !== 'empty' || added.length > 0}>\n            <div className=\"border-b border-kh-line px-6 py-3 text-kh-small text-kh-muted @xl:px-8\">\n              <p className=\"tabular-nums\">\n                {total} <Text path={['summaryWord']} value={props.summaryWord} as=\"span\" />\n              </p>\n              <p role=\"status\" className=\"min-h-5 text-kh-ink\">\n                {notice}\n              </p>\n            </div>\n            <ol ref={root} className=\"divide-y divide-kh-line\">\n              {tops.map(({ c, i, isNew }) => {\n                const cid = `${id}-c${i}`;\n                const isOpen = open === i;\n                const replies = [...c.replies.map((r) => ({ r, isNew: false })), ...added.filter((a) => a.at === i).map((a) => ({ r: a.entry, isNew: true }))];\n                return (\n                  <li key={i} className=\"px-6 py-5 @xl:px-8\">\n                    <article aria-labelledby={`${cid}-a`} data-new={isNew || undefined} tabIndex={isNew ? -1 : undefined} className=\"flex gap-3 outline-none\">\n                      <Avatar name={c.author} decorative />\n                      <div className=\"min-w-0 flex-1\">\n                        <span id={`${cid}-a`} className=\"sr-only\">\n                          {c.author}, {c.time}\n                        </span>\n                        {isNew ? (\n                          <p className=\"flex flex-wrap items-baseline gap-x-2\">\n                            <span className=\"text-kh-small font-semibold\">{c.author}</span>\n                            <span className=\"text-kh-caption text-kh-muted\">{c.time}</span>\n                          </p>\n                        ) : (\n                          <Byline path={['comments', i]} c={c} />\n                        )}\n                        {isNew ? <p className=\"mt-1 whitespace-pre-wrap text-kh-body\">{c.body}</p> : <Text path={['comments', i, 'body']} value={c.body} as=\"p\" className=\"mt-1 text-kh-body\" />}\n                        <button\n                          type=\"button\"\n                          aria-expanded={isOpen}\n                          aria-controls={`${cid}-f`}\n                          ref={(el) => {\n                            replyBtn.current[i] = el;\n                          }}\n                          onClick={() => {\n                            if (isOpen) return closeReply(i);\n                            focusNext.current = { k: 'field' };\n                            setBad(null);\n                            setOpen(i);\n                          }}\n                          className=\"mt-1 inline-flex min-h-11 items-center rounded-kh-sm px-1 text-kh-small font-medium text-kh-ink underline [text-decoration-color:var(--kh-edge)] underline-offset-4 hover:decoration-current focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-(--kh-focus)\"\n                        >\n                          <Text path={['replyLabel']} value={props.replyLabel} as=\"span\" /> <span className=\"sr-only\">{c.author}</span>\n                        </button>\n                        {replies.length > 0 && (\n                          <ol className=\"mt-2 flex flex-col gap-4 border-l border-kh-line pl-4\">\n                            {replies.map(({ r, isNew: rNew }, k) => (\n                              <li key={k} className=\"flex gap-3\">\n                                <Avatar name={r.author} size=\"sm\" decorative />\n                                <article className=\"min-w-0 flex-1 outline-none\" aria-label={`${r.author}, ${r.time}`} data-new={rNew || undefined} tabIndex={rNew ? -1 : undefined}>\n                                  {rNew ? (\n                                    <p className=\"flex flex-wrap items-baseline gap-x-2\">\n                                      <span className=\"text-kh-small font-semibold\">{r.author}</span>\n                                      <span className=\"text-kh-caption text-kh-muted\">{r.time}</span>\n                                    </p>\n                                  ) : (\n                                    <Byline path={['comments', i, 'replies', k]} c={r} />\n                                  )}\n                                  {rNew ? <p className=\"mt-0.5 whitespace-pre-wrap text-kh-small text-kh-ink-2\">{r.body}</p> : <Text path={['comments', i, 'replies', k, 'body']} value={r.body} as=\"p\" className=\"mt-0.5 text-kh-small text-kh-ink-2\" />}\n                                </article>\n                              </li>\n                            ))}\n                          </ol>\n                        )}\n                        <form\n                          id={`${cid}-f`}\n                          hidden={!isOpen && !editing}\n                          onSubmit={(e) => sendReply(e, i)}\n                          onKeyDown={(e) => e.key === 'Escape' && isOpen && closeReply(i)}\n                          className=\"mt-3 flex flex-col gap-3\"\n                        >\n                          <label htmlFor={`${cid}-t`} className=\"text-kh-small font-medium\">\n                            <Text path={['replyForm', 'label']} value={props.replyForm.label} as=\"span\" />\n                          </label>\n                          <Textarea\n                            ref={isOpen ? replyBox : undefined}\n                            id={`${cid}-t`}\n                            rows={3}\n                            aria-invalid={(isOpen && bad === 'reply') || undefined}\n                            aria-describedby={isOpen && bad === 'reply' ? `${cid}-e` : undefined}\n                            onChange={() => bad === 'reply' && setBad(null)}\n                          />\n                          {isOpen && bad === 'reply' && (\n                            <p id={`${cid}-e`} className=\"text-kh-small text-kh-danger\">\n                              {props.composer.empty}\n                            </p>\n                          )}\n                          <div className=\"flex flex-wrap gap-2\">\n                            <Button type=\"submit\">\n                              <Text path={['replyForm', 'submit']} value={props.replyForm.submit} as=\"span\" />\n                            </Button>\n                            <Button type=\"button\" variant=\"ghost\" onClick={() => closeReply(i)}>\n                              <Text path={['replyForm', 'cancel']} value={props.replyForm.cancel} as=\"span\" />\n                            </Button>\n                          </div>\n                        </form>\n                      </div>\n                    </article>\n                  </li>\n                );\n              })}\n            </ol>\n          </StateSlot>\n          <StateSlot show={state === 'empty' && added.length === 0}>\n            <EmptyState icon={<MessageSquare />} title={<Text path={['messages', 'emptyTitle']} value={props.messages.emptyTitle} as=\"span\" />} level={3}>\n              <Text path={['messages', 'emptyBody']} value={props.messages.emptyBody} as=\"span\" />\n            </EmptyState>\n          </StateSlot>\n          {composerNamed && (\n          <form onSubmit={post} noValidate aria-busy={posting || undefined} className=\"flex flex-col gap-3 border-t border-kh-line p-6 @xl:p-8\">\n            <StateSlot show={state === 'error'}>\n              <Banner tone=\"error\"><Text path={['messages', 'error']} value={props.messages.error} as=\"span\" /></Banner>\n            </StateSlot>\n            <label htmlFor={`${id}-new`} className=\"text-kh-small font-medium\">\n              <Text path={['composer', 'label']} value={props.composer.label} as=\"span\" />\n            </label>\n            <Textarea ref={newBox} id={`${id}-new`} rows={3} disabled={posting} aria-invalid={bad === 'new' || undefined} aria-describedby={bad === 'new' ? `${id}-ne` : undefined} onChange={() => bad === 'new' && setBad(null)} />\n            {bad === 'new' && (\n              <p id={`${id}-ne`} className=\"text-kh-small text-kh-danger\">\n                {props.composer.empty}\n              </p>\n            )}\n            <div className=\"flex justify-end\">\n              <Button type=\"submit\" disabled={posting}>\n                <Text path={['composer', posting ? 'posting' : 'submit']} value={posting ? props.composer.posting : props.composer.submit} as=\"span\" />\n              </Button>\n            </div>\n            <StateSlot show={false}>\n              <Text path={['composer', posting ? 'submit' : 'posting']} value={posting ? props.composer.submit : props.composer.posting} as=\"p\" />\n              <Text path={['composer', 'empty']} value={props.composer.empty} as=\"p\" />\n              <Text path={['you']} value={props.you} as=\"p\" />\n              <Text path={['justNow']} value={props.justNow} as=\"p\" />\n              <Text path={['notices', 'posted']} value={props.notices.posted} as=\"p\" />\n              <Text path={['notices', 'replied']} value={props.notices.replied} as=\"p\" />\n            </StateSlot>\n          </form>\n          )}\n        </AppPanel>\n      </Container>\n    </Section>\n  );\n}\n\nexport default withHeadingLevel(AppCommentsThread);\n"
    }
  ]
}
