{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "chat-02",
  "title": "Prompt composer",
  "description": "A composer that grows with the text, takes files from the picker or a drop, lets you pick a model and fills itself from suggested prompts.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/animated-size.json",
    "https://ui.ndekocode.dev/r/button.json",
    "https://ui.ndekocode.dev/r/chat-file-upload.json",
    "https://ui.ndekocode.dev/r/chat-motion.json",
    "https://ui.ndekocode.dev/r/chat-prompt-input.json",
    "https://ui.ndekocode.dev/r/chat-prompt-suggestion.json",
    "https://ui.ndekocode.dev/r/icons.json",
    "https://ui.ndekocode.dev/r/select.json",
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/use-prefers-reduced-motion.json",
    "https://ui.ndekocode.dev/r/utils.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/blocks/chat/chat-02/index.tsx",
      "content": "'use client';\n\nimport { AnimatePresence, motion } from 'motion/react';\nimport { useEffect, useId, useRef, useState } from 'react';\n\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport {\n  CircleAlertIcon,\n  CircleCheckIcon,\n  PaperclipIcon,\n  UploadCloudIcon,\n} from '@/registry/ndeko/lib/icons';\nimport { AnimatedSize } from '@/registry/ndeko/ui/animated-size';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport {\n  FileUpload,\n  FileUploadContent,\n  useFileUpload,\n} from '@/registry/ndeko/ui/chat-file-upload';\nimport {\n  PromptInput,\n  PromptInputAction,\n  PromptInputActions,\n  PromptInputTextarea,\n} from '@/registry/ndeko/ui/chat-prompt-input';\nimport { PromptSuggestion } from '@/registry/ndeko/ui/chat-prompt-suggestion';\n\nimport { AttachmentList, formatBytes } from './attachment-list';\nimport {\n  maxBytes,\n  maxFiles,\n  models,\n  seedAttachments,\n  sendingMs,\n  sentMs,\n  suggestions,\n  type Attachment,\n  type AttachmentKind,\n  type ModelValue,\n} from './data';\nimport { ModelPicker } from './model-picker';\nimport { risePresenceOf } from './presence';\nimport { SubmitButton, type SubmitPhase } from './submit-button';\n\ntype NoticeTone = 'refusal' | 'sent';\n\ntype Notice = {\n  tone: NoticeTone;\n  text: string;\n};\n\nconst NOTICE_ICON: Record<NoticeTone, React.ReactNode> = {\n  refusal: <CircleAlertIcon className='text-warning-foreground size-4' />,\n  sent: <CircleCheckIcon className='text-success-foreground size-4' />,\n};\n\nfunction kindOf(file: File): AttachmentKind {\n  const isImage = file.type.startsWith('image/');\n  if (isImage) {\n    return 'image';\n  }\n  return 'document';\n}\n\nfunction modelLabelOf(value: ModelValue) {\n  const model = models.find((candidate) => candidate.value === value);\n  return model?.label ?? value;\n}\n\nfunction fileCountOf(count: number) {\n  if (count === 1) {\n    return '1 file';\n  }\n  return `${count} files`;\n}\n\nfunction sentTextOf(modelLabel: string, fileCount: number) {\n  if (fileCount === 0) {\n    return `Sent to ${modelLabel}`;\n  }\n  const files = fileCountOf(fileCount);\n  return `Sent to ${modelLabel} with ${files}`;\n}\n\nfunction refusalOf(tooLargeName: string | null, hasOverflow: boolean) {\n  if (tooLargeName) {\n    const limit = formatBytes(maxBytes);\n    const text = `“${tooLargeName}” is over ${limit}. Attach a smaller copy`;\n    return { tone: 'refusal' as const, text };\n  }\n  if (hasOverflow) {\n    const text = `${fileCountOf(maxFiles)} fit in one prompt. Remove one to add another`;\n    return { tone: 'refusal' as const, text };\n  }\n  return null;\n}\n\nfunction focusAtEnd(id: string) {\n  const element = document.getElementById(id);\n  if (!(element instanceof HTMLTextAreaElement)) {\n    return;\n  }\n  const end = element.value.length;\n  element.focus();\n  element.setSelectionRange(end, end);\n}\n\ntype AttachButtonProps = {\n  isFull: boolean;\n  disabled: boolean;\n  onRefuse: () => void;\n};\n\nfunction AttachButton({ isFull, disabled, onRefuse }: AttachButtonProps) {\n  const { openPicker } = useFileUpload();\n\n  function attach() {\n    if (isFull) {\n      onRefuse();\n      return;\n    }\n    openPicker();\n  }\n\n  return (\n    <PromptInputAction tooltip='Attach files'>\n      <Button\n        type='button'\n        variant='ghost'\n        size='icon'\n        aria-label='Attach files'\n        disabled={disabled}\n        onClick={attach}\n        className='text-muted-foreground'\n      >\n        <PaperclipIcon />\n      </Button>\n    </PromptInputAction>\n  );\n}\n\nfunction Composer02() {\n  const [draft, setDraft] = useState('');\n  const [attachments, setAttachments] = useState<Attachment[]>(seedAttachments);\n  const [model, setModel] = useState<ModelValue>('deep');\n  const [phase, setPhase] = useState<SubmitPhase>('idle');\n  const [notice, setNotice] = useState<Notice | null>(null);\n  const idCounter = useRef(0);\n  const timers = useRef(new Set<ReturnType<typeof setTimeout>>());\n  const textareaId = useId();\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const presence = risePresenceOf(shouldReduceMotion);\n  const isIdle = phase === 'idle';\n  const isWorking = !isIdle;\n  const hasText = draft.trim().length > 0;\n  const hasAttachments = attachments.length > 0;\n  const canSend = hasText || hasAttachments;\n  const isFull = attachments.length >= maxFiles;\n  const isDraftEmpty = draft.length === 0;\n  const showsSuggestions = isDraftEmpty && isIdle;\n\n  useEffect(() => {\n    const pending = timers.current;\n    return () => {\n      pending.forEach((timer) => clearTimeout(timer));\n    };\n  }, []);\n\n  function schedule(task: () => void, delay: number) {\n    const timer = setTimeout(() => {\n      timers.current.delete(timer);\n      task();\n    }, delay);\n    timers.current.add(timer);\n  }\n\n  function nextId() {\n    idCounter.current += 1;\n    return `file-${idCounter.current}`;\n  }\n\n  function addFiles(files: File[]) {\n    const room = maxFiles - attachments.length;\n    const accepted: Attachment[] = [];\n    let tooLargeName: string | null = null;\n    let hasOverflow = false;\n    for (const file of files) {\n      const isTooLarge = file.size > maxBytes;\n      if (isTooLarge) {\n        tooLargeName = file.name;\n        continue;\n      }\n      const isOutOfRoom = accepted.length >= room;\n      if (isOutOfRoom) {\n        hasOverflow = true;\n        continue;\n      }\n      const attachment: Attachment = {\n        id: nextId(),\n        name: file.name,\n        size: file.size,\n        kind: kindOf(file),\n      };\n      accepted.push(attachment);\n    }\n    setAttachments((current) => [...current, ...accepted]);\n    setNotice(refusalOf(tooLargeName, hasOverflow));\n  }\n\n  function removeAttachment(id: string) {\n    setAttachments((current) => current.filter((item) => item.id !== id));\n    setNotice(null);\n  }\n\n  function refuseMoreFiles() {\n    setNotice(refusalOf(null, true));\n  }\n\n  function changeDraft(value: string) {\n    setDraft(value);\n    if (notice?.tone === 'sent') {\n      setNotice(null);\n    }\n  }\n\n  function applySuggestion(text: string) {\n    setDraft(text);\n    requestAnimationFrame(() => focusAtEnd(textareaId));\n  }\n\n  function send() {\n    if (!isIdle) {\n      return;\n    }\n    if (!canSend) {\n      return;\n    }\n    const modelLabel = modelLabelOf(model);\n    const sentText = sentTextOf(modelLabel, attachments.length);\n    setPhase('sending');\n    setNotice(null);\n    schedule(() => {\n      setPhase('sent');\n      setDraft('');\n      setAttachments([]);\n      setNotice({ tone: 'sent', text: sentText });\n    }, sendingMs);\n    schedule(() => setPhase('idle'), sendingMs + sentMs);\n  }\n\n  return (\n    <div className='bg-background text-foreground flex min-h-dvh w-full flex-col items-center px-4 pt-16 pb-10 sm:pt-24'>\n      <div className='w-full max-w-xl'>\n        <div className='mb-5 space-y-1.5 text-center'>\n          <h1 className='text-xl font-semibold text-balance sm:text-2xl'>\n            Draft with Quillstone\n          </h1>\n          <p className='text-muted-foreground text-sm text-balance'>\n            Attach notes or a page, pick a model and say what you need\n          </p>\n        </div>\n\n        <FileUpload onFilesAdded={addFiles} disabled={isWorking}>\n          <PromptInput\n            value={draft}\n            onValueChange={changeDraft}\n            onSubmit={send}\n            isLoading={isWorking}\n          >\n            <AnimatedSize>\n              <AttachmentList\n                attachments={attachments}\n                onRemove={removeAttachment}\n                disabled={isWorking}\n              />\n              <PromptInputTextarea\n                id={textareaId}\n                aria-label='Prompt'\n                placeholder='Ask Quillstone to draft, rewrite or summarise'\n                readOnly={isWorking}\n              />\n              <PromptInputActions className='justify-between gap-2 pt-1'>\n                <div className='flex min-w-0 items-center gap-1'>\n                  <AttachButton\n                    isFull={isFull}\n                    disabled={isWorking}\n                    onRefuse={refuseMoreFiles}\n                  />\n                  <ModelPicker\n                    value={model}\n                    onChange={setModel}\n                    disabled={isWorking}\n                  />\n                </div>\n                <SubmitButton phase={phase} canSend={canSend} onSend={send} />\n              </PromptInputActions>\n            </AnimatedSize>\n          </PromptInput>\n          <FileUploadContent>\n            <div className='bg-card hairline-border border-foreground/25 flex flex-col items-center gap-2 rounded-2xl border-dashed px-10 py-8 text-center shadow-[0_1px_2px_rgb(0_0_0/0.04)]'>\n              <UploadCloudIcon className='text-muted-foreground size-6' />\n              <p className='text-sm font-medium'>Drop files to attach them</p>\n              <p className='text-muted-foreground text-xs'>\n                Up to {fileCountOf(maxFiles)}, {formatBytes(maxBytes)} each\n              </p>\n            </div>\n          </FileUploadContent>\n        </FileUpload>\n\n        <AnimatedSize>\n          <div aria-live='polite'>\n            <AnimatePresence initial={false} mode='popLayout'>\n              {notice && (\n                <motion.p\n                  key={notice.text}\n                  className='text-muted-foreground flex items-start gap-2 px-1 pt-3 text-[13px]'\n                  {...presence}\n                >\n                  <span className='mt-px shrink-0'>\n                    {NOTICE_ICON[notice.tone]}\n                  </span>\n                  {notice.text}\n                </motion.p>\n              )}\n            </AnimatePresence>\n          </div>\n        </AnimatedSize>\n\n        <AnimatePresence initial={false}>\n          {showsSuggestions && (\n            <motion.ul\n              key='suggestions'\n              aria-label='Suggested prompts'\n              className='mt-4 flex flex-wrap justify-center gap-2'\n              {...presence}\n            >\n              {suggestions.map((suggestion) => (\n                <li key={suggestion}>\n                  <PromptSuggestion onClick={() => applySuggestion(suggestion)}>\n                    {suggestion}\n                  </PromptSuggestion>\n                </li>\n              ))}\n            </motion.ul>\n          )}\n        </AnimatePresence>\n      </div>\n    </div>\n  );\n}\n\nexport default Composer02;\n",
      "type": "registry:component",
      "target": "components/blocks/chat-02/index.tsx"
    },
    {
      "path": "registry/ndeko/blocks/chat/chat-02/attachment-list.tsx",
      "content": "'use client';\n\nimport { AnimatePresence, motion } from 'motion/react';\n\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport { FileTextIcon, ImageIcon, XIcon } from '@/registry/ndeko/lib/icons';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Button } from '@/registry/ndeko/ui/button';\n\nimport type { Attachment, AttachmentKind } from './data';\nimport { layoutTransitionOf, settlePresenceOf } from './presence';\n\nconst KILOBYTE = 1024;\n\nconst MEGABYTE = KILOBYTE * 1024;\n\nconst KIND_LOOK: Record<\n  AttachmentKind,\n  { icon: React.ReactNode; gem: string }\n> = {\n  document: { icon: <FileTextIcon />, gem: 'var(--primary)' },\n  image: { icon: <ImageIcon />, gem: 'var(--info)' },\n};\n\nexport function formatBytes(size: number) {\n  if (size < KILOBYTE) {\n    return `${size} B`;\n  }\n  if (size < MEGABYTE) {\n    const kilobytes = Math.round(size / KILOBYTE);\n    return `${kilobytes} KB`;\n  }\n  const tenths = Math.round((size / MEGABYTE) * 10);\n  const megabytes = tenths / 10;\n  return `${megabytes} MB`;\n}\n\ntype AttachmentListProps = {\n  attachments: Attachment[];\n  onRemove: (id: string) => void;\n  disabled?: boolean;\n};\n\nexport function AttachmentList({\n  attachments,\n  onRemove,\n  disabled = false,\n}: AttachmentListProps) {\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const presence = settlePresenceOf(shouldReduceMotion);\n  const layoutTransition = layoutTransitionOf(shouldReduceMotion);\n  const transition = { ...presence.transition, layout: layoutTransition };\n  const hasAttachments = attachments.length > 0;\n\n  return (\n    <ul\n      aria-label='Attachments'\n      className={cn(\n        'flex flex-wrap gap-1.5',\n        hasAttachments && 'px-1 pt-1 pb-2'\n      )}\n    >\n      <AnimatePresence mode='popLayout' initial={false}>\n        {attachments.map((attachment) => {\n          const look = KIND_LOOK[attachment.kind];\n          const plateStyle = { '--gem': look.gem } as React.CSSProperties;\n          const size = formatBytes(attachment.size);\n\n          return (\n            <motion.li\n              key={attachment.id}\n              layout\n              initial={presence.initial}\n              animate={presence.animate}\n              exit={presence.exit}\n              transition={transition}\n              className='bg-card hairline-ring ring-border flex h-11 max-w-60 items-center gap-2 rounded-lg ps-1.5 pe-1 shadow-[0_1px_2px_rgb(0_0_0/0.04)]'\n            >\n              <span\n                aria-hidden='true'\n                style={plateStyle}\n                className='gem-plate inline-flex size-7 shrink-0 items-center justify-center rounded-md [&_svg]:size-3.5'\n              >\n                {look.icon}\n              </span>\n              <span className='min-w-0 flex-1'>\n                <span className='block truncate text-xs font-medium'>\n                  {attachment.name}\n                </span>\n                <span className='text-muted-foreground block text-xs tabular-nums'>\n                  {size}\n                </span>\n              </span>\n              <Button\n                type='button'\n                variant='ghost'\n                size='icon-sm'\n                aria-label={`Remove ${attachment.name}`}\n                disabled={disabled}\n                onClick={() => onRemove(attachment.id)}\n                className='text-muted-foreground'\n              >\n                <XIcon className='size-3.5' />\n              </Button>\n            </motion.li>\n          );\n        })}\n      </AnimatePresence>\n    </ul>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/chat-02/attachment-list.tsx"
    },
    {
      "path": "registry/ndeko/blocks/chat/chat-02/model-picker.tsx",
      "content": "'use client';\n\nimport {\n  Select,\n  SelectContent,\n  SelectItem,\n  SelectTrigger,\n  SelectValue,\n} from '@/registry/ndeko/ui/select';\n\nimport { models, type ModelValue } from './data';\n\nfunction isModelValue(value: unknown): value is ModelValue {\n  return models.some((model) => model.value === value);\n}\n\ntype ModelPickerProps = {\n  value: ModelValue;\n  onChange: (value: ModelValue) => void;\n  disabled?: boolean;\n};\n\nexport function ModelPicker({ value, onChange, disabled }: ModelPickerProps) {\n  function change(next: unknown) {\n    if (isModelValue(next)) {\n      onChange(next);\n    }\n  }\n\n  return (\n    <Select\n      items={models}\n      value={value}\n      onValueChange={change}\n      disabled={disabled}\n    >\n      <SelectTrigger size='sm' aria-label='Model' className='w-auto min-w-32'>\n        <SelectValue />\n      </SelectTrigger>\n      <SelectContent className='min-w-64'>\n        {models.map((model) => (\n          <SelectItem key={model.value} value={model.value}>\n            <span className='shrink-0'>{model.label}</span>\n            <span className='text-muted-foreground truncate text-xs'>\n              {model.hint}\n            </span>\n          </SelectItem>\n        ))}\n      </SelectContent>\n    </Select>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/chat-02/model-picker.tsx"
    },
    {
      "path": "registry/ndeko/blocks/chat/chat-02/submit-button.tsx",
      "content": "'use client';\n\nimport { CheckIcon, LoaderIcon, SendIcon } from '@/registry/ndeko/lib/icons';\nimport { AnimatedSize } from '@/registry/ndeko/ui/animated-size';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { Swap } from '@/registry/ndeko/ui/chat-motion';\n\nexport type SubmitPhase = 'idle' | 'sending' | 'sent';\n\nconst PHASE_LABEL: Record<SubmitPhase, string> = {\n  idle: 'Send',\n  sending: 'Sending',\n  sent: 'Sent',\n};\n\nfunction PhaseIcon({ phase }: { phase: SubmitPhase }) {\n  if (phase === 'sending') {\n    return <LoaderIcon className='animate-spin' />;\n  }\n  if (phase === 'sent') {\n    return <CheckIcon />;\n  }\n  return <SendIcon />;\n}\n\ntype SubmitButtonProps = {\n  phase: SubmitPhase;\n  canSend: boolean;\n  onSend: () => void;\n};\n\nexport function SubmitButton({ phase, canSend, onSend }: SubmitButtonProps) {\n  const isIdle = phase === 'idle';\n  const isDisabled = isIdle && !canSend;\n  const label = PHASE_LABEL[phase];\n\n  function send() {\n    if (isIdle) {\n      onSend();\n    }\n  }\n\n  return (\n    <Button\n      type='button'\n      onClick={send}\n      disabled={isDisabled}\n      aria-live='polite'\n      className='px-3'\n    >\n      <AnimatedSize as='span' axis='width' contentClassName='flex items-center'>\n        <Swap swapKey={phase}>\n          <span className='flex items-center gap-1.5'>\n            <PhaseIcon phase={phase} />\n            {label}\n          </span>\n        </Swap>\n      </AnimatedSize>\n    </Button>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/chat-02/submit-button.tsx"
    },
    {
      "path": "registry/ndeko/blocks/chat/chat-02/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 SETTLE_PRESENCE: PresenceProps = {\n  initial: { opacity: 0, scale: 0.95 },\n  animate: { opacity: 1, scale: 1 },\n  exit: { opacity: 0, scale: 0.95, transition: EXIT },\n  transition: ENTER,\n};\n\nconst RISE_PRESENCE: PresenceProps = {\n  initial: { opacity: 0, y: 4 },\n  animate: { opacity: 1, y: 0 },\n  exit: { opacity: 0, y: 4, 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 const LAYOUT_SPRING: Transition = {\n  type: 'spring',\n  bounce: 0,\n  duration: 0.3,\n};\n\nexport const INSTANT: Transition = { duration: 0 };\n\nexport function settlePresenceOf(shouldReduceMotion: boolean | null) {\n  if (shouldReduceMotion) {\n    return FADE_PRESENCE;\n  }\n  return SETTLE_PRESENCE;\n}\n\nexport function risePresenceOf(shouldReduceMotion: boolean | null) {\n  if (shouldReduceMotion) {\n    return FADE_PRESENCE;\n  }\n  return RISE_PRESENCE;\n}\n\nexport function layoutTransitionOf(shouldReduceMotion: boolean | null) {\n  if (shouldReduceMotion) {\n    return INSTANT;\n  }\n  return LAYOUT_SPRING;\n}\n",
      "type": "registry:component",
      "target": "components/blocks/chat-02/presence.ts"
    },
    {
      "path": "registry/ndeko/blocks/chat/chat-02/data.ts",
      "content": "export type ModelValue = 'swift' | 'deep';\n\nexport type Model = {\n  value: ModelValue;\n  label: string;\n  hint: string;\n};\n\nexport type AttachmentKind = 'document' | 'image';\n\nexport type Attachment = {\n  id: string;\n  name: string;\n  size: number;\n  kind: AttachmentKind;\n};\n\nexport const models: Model[] = [\n  { value: 'swift', label: 'Quill Swift', hint: 'Quick drafts and rewrites' },\n  { value: 'deep', label: 'Quill Deep', hint: 'Careful edits on long pages' },\n];\n\nexport const suggestions = [\n  'Summarise this page in five lines',\n  'Rewrite the intro for new hires',\n  'Turn my meeting notes into a checklist',\n];\n\nexport const seedAttachments: Attachment[] = [\n  {\n    id: 'seed-notes',\n    name: 'Interview notes, March.pdf',\n    size: 186_000,\n    kind: 'document',\n  },\n];\n\nexport const maxFiles = 4;\n\nexport const maxBytes = 10 * 1024 * 1024;\n\nexport const sendingMs = 1100;\n\nexport const sentMs = 1400;\n",
      "type": "registry:component",
      "target": "components/blocks/chat-02/data.ts"
    }
  ],
  "categories": [
    "blocks",
    "chat"
  ],
  "type": "registry:block"
}