{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "chat-01",
  "title": "Conversation about a page",
  "description": "A writing assistant beside a docs page: the reply streams in word by word, Send becomes Stop while it does, and the list follows new text until you scroll up.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/button.json",
    "https://ui.ndekocode.dev/r/chat-container.json",
    "https://ui.ndekocode.dev/r/chat-loader.json",
    "https://ui.ndekocode.dev/r/chat-message.json",
    "https://ui.ndekocode.dev/r/chat-motion.json",
    "https://ui.ndekocode.dev/r/chat-prompt-input.json",
    "https://ui.ndekocode.dev/r/chat-response-stream.json",
    "https://ui.ndekocode.dev/r/chat-scroll-button.json",
    "https://ui.ndekocode.dev/r/icons.json",
    "https://ui.ndekocode.dev/r/kbd.json",
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/use-prefers-reduced-motion.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/blocks/chat/chat-01/index.tsx",
      "content": "'use client';\n\nimport { AnimatePresence, motion } from 'motion/react';\nimport { useEffect, useRef, useState } from 'react';\n\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport { FileTextIcon } from '@/registry/ndeko/lib/icons';\nimport {\n  ChatContainerContent,\n  ChatContainerRoot,\n  type ChatContainerContext,\n} from '@/registry/ndeko/ui/chat-container';\nimport {\n  PromptInput,\n  PromptInputActions,\n  PromptInputSubmit,\n  PromptInputTextarea,\n} from '@/registry/ndeko/ui/chat-prompt-input';\nimport { useTextStream } from '@/registry/ndeko/ui/chat-response-stream';\nimport { ScrollButton } from '@/registry/ndeko/ui/chat-scroll-button';\nimport { Kbd, KbdGroup } from '@/registry/ndeko/ui/kbd';\n\nimport {\n  page,\n  replies,\n  seedTurns,\n  thinkingMs,\n  wordDelayMs,\n  type AssistantTurn,\n  type ChatTurn,\n  type Feedback,\n  type ReplyStatus,\n} from './data';\nimport { rowPresenceOf } from './presence';\nimport { AssistantMessage, UserMessage } from './turns';\n\ntype FeedbackByTurn = Record<string, Feedback | undefined>;\n\nfunction replyAt(count: number) {\n  const index = count % replies.length;\n  return replies[index];\n}\n\nfunction withReply(\n  turns: ChatTurn[],\n  id: string,\n  status: ReplyStatus,\n  text: string\n) {\n  return turns.map((turn) => {\n    if (turn.id !== id) {\n      return turn;\n    }\n    const updated: AssistantTurn = { ...turn, role: 'assistant', status, text };\n    return updated;\n  });\n}\n\nfunction withoutTurn(turns: ChatTurn[], id: string) {\n  return turns.filter((turn) => turn.id !== id);\n}\n\nfunction Conversation01() {\n  const [turns, setTurns] = useState<ChatTurn[]>(seedTurns);\n  const [draft, setDraft] = useState('');\n  const [activeId, setActiveId] = useState<string | null>(null);\n  const [activeText, setActiveText] = useState('');\n  const [isThinking, setIsThinking] = useState(false);\n  const [sentCount, setSentCount] = useState(0);\n  const [feedback, setFeedback] = useState<FeedbackByTurn>({});\n  const thinkingTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n  const chatRef = useRef<ChatContainerContext | null>(null);\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const rowPresence = rowPresenceOf(shouldReduceMotion);\n  const isBusy = activeId !== null;\n\n  const stream = useTextStream({\n    textStream: activeText,\n    mode: 'fade',\n    segmentDelay: wordDelayMs,\n    onComplete: finishReply,\n  });\n\n  useEffect(() => {\n    return () => {\n      if (thinkingTimer.current) {\n        clearTimeout(thinkingTimer.current);\n      }\n    };\n  }, []);\n\n  function settle(id: string, status: ReplyStatus, text: string) {\n    setTurns((current) => withReply(current, id, status, text));\n    setActiveId(null);\n    setActiveText('');\n  }\n\n  function finishReply() {\n    if (!activeId) {\n      return;\n    }\n    settle(activeId, 'done', activeText);\n  }\n\n  function startReply(id: string, text: string) {\n    setIsThinking(false);\n    setTurns((current) => withReply(current, id, 'streaming', ''));\n    setActiveText(text);\n    stream.startStreaming();\n  }\n\n  function send() {\n    const text = draft.trim();\n    const isEmpty = text.length === 0;\n    if (isEmpty) {\n      return;\n    }\n    if (isBusy) {\n      return;\n    }\n    const userId = `sent-${sentCount}-user`;\n    const replyId = `sent-${sentCount}-reply`;\n    const reply = replyAt(sentCount);\n    const userTurn: ChatTurn = { id: userId, role: 'user', text };\n    const replyTurn: ChatTurn = {\n      id: replyId,\n      role: 'assistant',\n      status: 'thinking',\n      text: '',\n    };\n    setTurns((current) => [...current, userTurn, replyTurn]);\n    setDraft('');\n    setSentCount((count) => count + 1);\n    setActiveId(replyId);\n    setIsThinking(true);\n    chatRef.current?.scrollToBottom();\n    thinkingTimer.current = setTimeout(\n      () => startReply(replyId, reply),\n      thinkingMs\n    );\n  }\n\n  function stop() {\n    if (!activeId) {\n      return;\n    }\n    if (isThinking) {\n      if (thinkingTimer.current) {\n        clearTimeout(thinkingTimer.current);\n      }\n      setIsThinking(false);\n      setTurns((current) => withoutTurn(current, activeId));\n      setActiveId(null);\n      return;\n    }\n    stream.pause();\n    settle(activeId, 'stopped', stream.displayedText);\n  }\n\n  function changeFeedback(id: string, choice: Feedback | undefined) {\n    setFeedback((current) => ({ ...current, [id]: choice }));\n  }\n\n  return (\n    <div className='bg-background text-foreground flex h-dvh min-h-[30rem] w-full flex-col'>\n      <header className='flex h-14 shrink-0 items-center gap-2.5 px-4 sm:px-6'>\n        <span className='gem-plate inline-flex size-7 shrink-0 items-center justify-center rounded-lg [--gem:var(--primary)] [&_svg]:size-4'>\n          <FileTextIcon />\n        </span>\n        <div className='min-w-0'>\n          <h1 className='truncate text-sm font-medium'>{page.title}</h1>\n          <p className='text-muted-foreground truncate text-xs'>\n            {page.space} · Ask Quillstone about this page\n          </p>\n        </div>\n      </header>\n\n      <ChatContainerRoot contextRef={chatRef} className='flex-1'>\n        <ChatContainerContent className='mx-auto max-w-2xl px-4 pt-4 pb-2 sm:px-6'>\n          <AnimatePresence initial={false}>\n            {turns.map((turn) => (\n              <motion.div\n                key={turn.id}\n                className='-mx-1 overflow-hidden px-1'\n                {...rowPresence}\n              >\n                <div className='pb-6'>\n                  {turn.role === 'user' && <UserMessage turn={turn} />}\n                  {turn.role === 'assistant' && (\n                    <AssistantMessage\n                      turn={turn}\n                      segments={stream.segments}\n                      feedback={feedback[turn.id]}\n                      onFeedback={(choice) => changeFeedback(turn.id, choice)}\n                    />\n                  )}\n                </div>\n              </motion.div>\n            ))}\n          </AnimatePresence>\n        </ChatContainerContent>\n        <div className='pointer-events-none absolute inset-x-0 bottom-3 flex justify-center'>\n          <ScrollButton wrapperClassName='pointer-events-auto' />\n        </div>\n      </ChatContainerRoot>\n\n      <div className='shrink-0 px-4 pb-4 sm:px-6'>\n        <div className='mx-auto w-full max-w-2xl'>\n          <PromptInput\n            value={draft}\n            onValueChange={setDraft}\n            isLoading={isBusy}\n            onSubmit={send}\n          >\n            <PromptInputTextarea\n              aria-label='Message Quillstone'\n              placeholder='Ask about this page'\n            />\n            <PromptInputActions className='justify-between ps-2'>\n              <p className='text-muted-foreground hidden items-center gap-1.5 text-xs sm:flex'>\n                <KbdGroup>\n                  <Kbd>Shift</Kbd>\n                  <Kbd>Enter</Kbd>\n                </KbdGroup>\n                for a new line\n              </p>\n              <PromptInputSubmit onStop={stop} className='ms-auto' />\n            </PromptInputActions>\n          </PromptInput>\n        </div>\n      </div>\n    </div>\n  );\n}\n\nexport default Conversation01;\n",
      "type": "registry:component",
      "target": "components/blocks/chat-01/index.tsx"
    },
    {
      "path": "registry/ndeko/blocks/chat/chat-01/turns.tsx",
      "content": "'use client';\n\nimport { AnimatePresence, motion } from 'motion/react';\n\nimport { FeatherIcon } from '@/registry/ndeko/lib/icons';\nimport { TextLoader } from '@/registry/ndeko/ui/chat-loader';\nimport {\n  Message,\n  MessageAvatar,\n  MessageContent,\n  MessageGlyph,\n} from '@/registry/ndeko/ui/chat-message';\nimport {\n  ResponseStreamSegments,\n  type StreamSegment,\n} from '@/registry/ndeko/ui/chat-response-stream';\n\nimport type { AssistantTurn, Feedback, UserTurn } from './data';\nimport { reader } from './data';\nimport { fadePresence } from './presence';\nimport { ReplyActions } from './reply-actions';\n\nexport function UserMessage({ turn }: { turn: UserTurn }) {\n  return (\n    <Message className='justify-end'>\n      <MessageContent className='max-w-[85%] sm:max-w-[75%]'>\n        {turn.text}\n      </MessageContent>\n      <MessageAvatar alt={reader.name} className='hidden sm:inline-flex' />\n    </Message>\n  );\n}\n\ntype AssistantMessageProps = {\n  turn: AssistantTurn;\n  segments: StreamSegment[];\n  feedback: Feedback | undefined;\n  onFeedback: (feedback: Feedback | undefined) => void;\n};\n\nexport function AssistantMessage({\n  turn,\n  segments,\n  feedback,\n  onFeedback,\n}: AssistantMessageProps) {\n  const isThinking = turn.status === 'thinking';\n  const isStreaming = turn.status === 'streaming';\n  const isStopped = turn.status === 'stopped';\n  const isDone = turn.status === 'done';\n  const isSettled = isDone || isStopped;\n  const presence = fadePresence();\n\n  return (\n    <Message>\n      <MessageGlyph>\n        <FeatherIcon />\n      </MessageGlyph>\n      <div className='min-w-0 flex-1 space-y-2 pt-1'>\n        {isThinking && <TextLoader text='Thinking' />}\n        {isStreaming && (\n          <MessageContent variant='plain'>\n            <ResponseStreamSegments segments={segments} />\n          </MessageContent>\n        )}\n        {isSettled && (\n          <MessageContent variant='plain'>{turn.text}</MessageContent>\n        )}\n        <AnimatePresence initial={false}>\n          {isStopped && (\n            <motion.p\n              key='stopped'\n              className='text-muted-foreground text-xs'\n              {...presence}\n            >\n              Stopped\n            </motion.p>\n          )}\n          {isSettled && (\n            <motion.div key='actions' {...presence}>\n              <ReplyActions\n                text={turn.text}\n                feedback={feedback}\n                onFeedback={onFeedback}\n              />\n            </motion.div>\n          )}\n        </AnimatePresence>\n      </div>\n    </Message>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/chat-01/turns.tsx"
    },
    {
      "path": "registry/ndeko/blocks/chat/chat-01/reply-actions.tsx",
      "content": "'use client';\n\nimport { CheckIcon, CopyIcon, ThumbsUpIcon } from '@/registry/ndeko/lib/icons';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport {\n  MessageAction,\n  MessageActions,\n} from '@/registry/ndeko/ui/chat-message';\nimport { Swap } from '@/registry/ndeko/ui/chat-motion';\n\nimport type { CopyStatus } from './use-copied';\nimport { useCopied } from './use-copied';\nimport type { Feedback } from './data';\n\nconst COPY_TOOLTIP: Record<CopyStatus, string> = {\n  idle: 'Copy',\n  copied: 'Copied',\n  failed: 'Couldn’t copy, select the text instead',\n};\n\nconst ACTION_BUTTON =\n  'text-muted-foreground aria-pressed:bg-foreground/[0.06] aria-pressed:text-foreground';\n\ntype ReplyActionsProps = {\n  text: string;\n  feedback: Feedback | undefined;\n  onFeedback: (feedback: Feedback | undefined) => void;\n};\n\nfunction toggled(current: Feedback | undefined, choice: Feedback) {\n  if (current === choice) {\n    return undefined;\n  }\n  return choice;\n}\n\nexport function ReplyActions({\n  text,\n  feedback,\n  onFeedback,\n}: ReplyActionsProps) {\n  const { status, copy } = useCopied();\n  const isCopied = status === 'copied';\n  const isHelpful = feedback === 'helpful';\n  const isNotHelpful = feedback === 'not-helpful';\n  const tooltip = COPY_TOOLTIP[status];\n\n  function copyReply() {\n    copy(text);\n  }\n\n  function markHelpful() {\n    onFeedback(toggled(feedback, 'helpful'));\n  }\n\n  function markNotHelpful() {\n    onFeedback(toggled(feedback, 'not-helpful'));\n  }\n\n  return (\n    <MessageActions className='-ms-1.5'>\n      <MessageAction tooltip={tooltip}>\n        <Button\n          type='button'\n          variant='ghost'\n          size='icon-sm'\n          aria-label={tooltip}\n          onClick={copyReply}\n          className={ACTION_BUTTON}\n        >\n          <Swap swapKey={String(isCopied)}>\n            {isCopied && <CheckIcon className='size-3.5' />}\n            {!isCopied && <CopyIcon className='size-3.5' />}\n          </Swap>\n        </Button>\n      </MessageAction>\n      <MessageAction tooltip='Helpful'>\n        <Button\n          type='button'\n          variant='ghost'\n          size='icon-sm'\n          aria-label='Helpful'\n          aria-pressed={isHelpful}\n          onClick={markHelpful}\n          className={ACTION_BUTTON}\n        >\n          <ThumbsUpIcon className='size-3.5' />\n        </Button>\n      </MessageAction>\n      <MessageAction tooltip='Not helpful'>\n        <Button\n          type='button'\n          variant='ghost'\n          size='icon-sm'\n          aria-label='Not helpful'\n          aria-pressed={isNotHelpful}\n          onClick={markNotHelpful}\n          className={ACTION_BUTTON}\n        >\n          <ThumbsUpIcon className='size-3.5 rotate-180' />\n        </Button>\n      </MessageAction>\n    </MessageActions>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/chat-01/reply-actions.tsx"
    },
    {
      "path": "registry/ndeko/blocks/chat/chat-01/presence.ts",
      "content": "import type { MotionProps, Transition } from 'motion/react';\n\ntype PresenceProps = Pick<\n  MotionProps,\n  'initial' | 'animate' | 'exit' | 'transition'\n>;\n\nconst EASE_OUT_STRONG: [number, number, number, number] = [0.23, 1, 0.32, 1];\n\nconst ENTER: Transition = { duration: 0.2, ease: EASE_OUT_STRONG };\n\nconst EXIT: Transition = { duration: 0.14, ease: EASE_OUT_STRONG };\n\nconst ROW_PRESENCE: PresenceProps = {\n  initial: { height: 0, opacity: 0 },\n  animate: { height: 'auto', opacity: 1 },\n  exit: { height: 0, opacity: 0, transition: EXIT },\n  transition: ENTER,\n};\n\nconst FADE_PRESENCE: PresenceProps = {\n  initial: { opacity: 0 },\n  animate: { opacity: 1 },\n  exit: { opacity: 0, transition: EXIT },\n  transition: ENTER,\n};\n\nexport function rowPresenceOf(shouldReduceMotion: boolean | null) {\n  if (shouldReduceMotion) {\n    return FADE_PRESENCE;\n  }\n  return ROW_PRESENCE;\n}\n\nexport function fadePresence() {\n  return FADE_PRESENCE;\n}\n",
      "type": "registry:component",
      "target": "components/blocks/chat-01/presence.ts"
    },
    {
      "path": "registry/ndeko/blocks/chat/chat-01/use-copied.ts",
      "content": "'use client';\n\nimport { useEffect, useRef, useState } from 'react';\n\nexport type CopyStatus = 'idle' | 'copied' | 'failed';\n\nconst RESET_AFTER_MS = 1600;\n\nexport function useCopied() {\n  const [status, setStatus] = useState<CopyStatus>('idle');\n  const timer = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n  useEffect(() => {\n    return () => {\n      if (timer.current) {\n        clearTimeout(timer.current);\n      }\n    };\n  }, []);\n\n  function showFor(nextStatus: CopyStatus) {\n    if (timer.current) {\n      clearTimeout(timer.current);\n    }\n    setStatus(nextStatus);\n    timer.current = setTimeout(() => setStatus('idle'), RESET_AFTER_MS);\n  }\n\n  async function copy(text: string) {\n    try {\n      await navigator.clipboard.writeText(text);\n    } catch {\n      showFor('failed');\n      return;\n    }\n    showFor('copied');\n  }\n\n  return { status, copy };\n}\n",
      "type": "registry:component",
      "target": "components/blocks/chat-01/use-copied.ts"
    },
    {
      "path": "registry/ndeko/blocks/chat/chat-01/data.ts",
      "content": "export type Person = {\n  name: string;\n};\n\nexport type ReplyStatus = 'thinking' | 'streaming' | 'done' | 'stopped';\n\nexport type UserTurn = {\n  id: string;\n  role: 'user';\n  text: string;\n};\n\nexport type AssistantTurn = {\n  id: string;\n  role: 'assistant';\n  text: string;\n  status: ReplyStatus;\n};\n\nexport type ChatTurn = UserTurn | AssistantTurn;\n\nexport type Feedback = 'helpful' | 'not-helpful';\n\nexport const reader: Person = {\n  name: 'Amara Diallo',\n};\n\nexport const page = {\n  title: 'Onboarding guide',\n  space: 'People team',\n};\n\nexport const seedTurns: ChatTurn[] = [\n  {\n    id: 'turn-1',\n    role: 'user',\n    text: 'The intro of the onboarding guide runs long. Can you tighten it without losing the part about buddies?',\n  },\n  {\n    id: 'turn-2',\n    role: 'assistant',\n    status: 'done',\n    text: 'Here is a tighter intro, down from 182 words to 74:\\n\\nWelcome to Fernhill. Your first two weeks are about meeting people, not shipping. Each new teammate gets a buddy who has been here at least a year. They book your first coffee and answer the questions you would rather not ask in a channel.\\n\\nI moved the paragraph on laptops and accounts to the Setup section, where people already look for it.',\n  },\n];\n\nexport const replies = [\n  'A title that says what the page is for: \"Your first two weeks at Fernhill\". It matches how the other guides in People team are named, and it reads well in search.\\n\\nI can also write a one-line summary under it, so the link preview in chat says something useful.',\n  'Done. The buddy paragraph is now second, since it is what most new people ask about, and the history of the office is a single sentence that links to the About page.\\n\\nThe intro fits on one phone screen now. The rest of the guide is unchanged.',\n  'Three sections repeat the same advice about the calendar: Day one, Meetings and Tools. I would keep it in Meetings and link to it from the other two.\\n\\nWant me to make that change and leave a comment for Jonas, who owns the Tools section?',\n];\n\nexport const thinkingMs = 700;\n\nexport const wordDelayMs = 45;\n",
      "type": "registry:component",
      "target": "components/blocks/chat-01/data.ts"
    }
  ],
  "categories": [
    "blocks",
    "chat"
  ],
  "type": "registry:block"
}