{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "ai-prompt-input",
  "type": "registry:item",
  "title": "Ai Prompt Input",
  "description": "A ai-prompt-input item.",
  "dependencies": [
    "@mui/material",
    "ai",
    "lucide-react",
    "nanoid",
    "@emotion/react",
    "@emotion/styled"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "components/ai-prompt-input/ai-prompt-input.tsx",
      "target": "src/mui-treasury/components/ai-prompt-input/ai-prompt-input.tsx",
      "content": "'use client';\n\nimport React, {\n  type ChangeEventHandler,\n  Children,\n  type ComponentProps,\n  type FormEvent,\n  type FormEventHandler,\n  Fragment,\n  type KeyboardEventHandler,\n  type MouseEvent,\n  type RefObject,\n  createContext,\n  memo,\n  useCallback,\n  useContext,\n  useEffect,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n} from 'react';\n\nimport Box from '@mui/material/Box';\nimport Button from '@mui/material/Button';\nimport CircularProgress from '@mui/material/CircularProgress';\nimport IconButton from '@mui/material/IconButton';\nimport InputBase from '@mui/material/InputBase';\nimport Menu from '@mui/material/Menu';\nimport MenuItem from '@mui/material/MenuItem';\nimport Select from '@mui/material/Select';\nimport type { SxProps, Theme } from '@mui/material/styles';\nimport type { ChatStatus, FileUIPart } from 'ai';\nimport {\n  ImageIcon,\n  PaperclipIcon,\n  PlusIcon,\n  SendIcon,\n  SquareIcon,\n  XIcon,\n} from 'lucide-react';\nimport { nanoid } from 'nanoid';\n\ntype AttachmentsContext = {\n  files: (FileUIPart & { id: string })[];\n  add: (files: File[] | FileList) => void;\n  remove: (id: string) => void;\n  clear: () => void;\n  openFileDialog: () => void;\n  fileInputRef: RefObject<HTMLInputElement | null>;\n};\n\nconst AttachmentsContext = createContext<AttachmentsContext | null>(null);\n\nexport const usePromptInputAttachments = () => {\n  const context = useContext(AttachmentsContext);\n\n  if (!context) {\n    throw new Error(\n      'usePromptInputAttachments must be used within a PromptInput',\n    );\n  }\n\n  return context;\n};\n\nexport type PromptInputAttachmentProps = {\n  data: FileUIPart & { id: string };\n  sx?: SxProps<Theme>;\n};\n\nexport function PromptInputAttachment({\n  data,\n  sx,\n}: PromptInputAttachmentProps) {\n  const attachments = usePromptInputAttachments();\n\n  return (\n    <Box\n      key={data.id}\n      sx={{\n        position: 'relative',\n        width: 56,\n        height: 56,\n        borderRadius: 1,\n        border: 1,\n        borderColor: 'divider',\n        '&:hover .remove-button': {\n          opacity: 1,\n        },\n        ...sx,\n      }}\n    >\n      {data.mediaType?.startsWith('image/') && data.url ? (\n        <Box\n          component=\"img\"\n          alt={data.filename || 'attachment'}\n          src={data.url}\n          sx={{\n            width: '100%',\n            height: '100%',\n            objectFit: 'cover',\n            borderRadius: 1,\n          }}\n        />\n      ) : (\n        <Box\n          sx={{\n            display: 'flex',\n            width: '100%',\n            height: '100%',\n            alignItems: 'center',\n            justifyContent: 'center',\n            color: 'text.secondary',\n          }}\n        >\n          <PaperclipIcon size={16} />\n        </Box>\n      )}\n      <IconButton\n        className=\"remove-button\"\n        aria-label=\"Remove attachment\"\n        onClick={() => attachments.remove(data.id)}\n        size=\"small\"\n        sx={{\n          position: 'absolute',\n          top: -6,\n          right: -6,\n          width: 24,\n          height: 24,\n          bgcolor: 'background.paper',\n          border: 1,\n          borderColor: 'divider',\n          opacity: 0,\n          transition: 'opacity 0.2s',\n          '&:hover': {\n            bgcolor: 'action.hover',\n          },\n        }}\n      >\n        <XIcon size={12} />\n      </IconButton>\n    </Box>\n  );\n}\n\nexport type PromptInputAttachmentsProps = {\n  children: (attachment: FileUIPart & { id: string }) => React.ReactNode;\n  sx?: SxProps<Theme>;\n};\n\nexport function PromptInputAttachments({\n  children,\n  sx,\n}: PromptInputAttachmentsProps) {\n  const attachments = usePromptInputAttachments();\n  const [height, setHeight] = useState(0);\n  const contentRef = useRef<HTMLDivElement>(null);\n\n  useLayoutEffect(() => {\n    const el = contentRef.current;\n    if (!el) {\n      return;\n    }\n    const ro = new ResizeObserver(() => {\n      setHeight(el.getBoundingClientRect().height);\n    });\n    ro.observe(el);\n    setHeight(el.getBoundingClientRect().height);\n    return () => ro.disconnect();\n  }, []);\n\n  return (\n    <Box\n      aria-live=\"polite\"\n      sx={{\n        overflow: 'hidden',\n        transition: 'height 200ms ease-out',\n        height: attachments.files.length ? height : 0,\n        ...sx,\n      }}\n    >\n      <Box\n        ref={contentRef}\n        sx={{\n          display: 'flex',\n          flexWrap: 'wrap',\n          gap: 1,\n          p: 1.5,\n          pt: 1.5,\n        }}\n      >\n        {attachments.files.map((file) => (\n          <Fragment key={file.id}>{children(file)}</Fragment>\n        ))}\n      </Box>\n    </Box>\n  );\n}\n\nexport type PromptInputActionAddAttachmentsProps = ComponentProps<\n  typeof MenuItem\n> & {\n  label?: string;\n};\n\nexport const PromptInputActionAddAttachments = ({\n  label = 'Add photos or files',\n  onClick,\n  ...props\n}: PromptInputActionAddAttachmentsProps) => {\n  const attachments = usePromptInputAttachments();\n\n  return (\n    <MenuItem\n      {...props}\n      onClick={(e) => {\n        e.preventDefault();\n        attachments.openFileDialog();\n        onClick?.(e);\n      }}\n    >\n      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>\n        <ImageIcon size={16} />\n        {label}\n      </Box>\n    </MenuItem>\n  );\n};\n\nexport type PromptInputMessage = {\n  text?: string;\n  files?: FileUIPart[];\n};\n\nexport type PromptInputProps = {\n  sx?: SxProps<Theme>;\n  accept?: string; // e.g., \"image/*\" or leave undefined for any\n  multiple?: boolean;\n  // When true, accepts drops anywhere on document. Default false (opt-in).\n  globalDrop?: boolean;\n  // Render a hidden input with given name and keep it in sync for native form posts. Default false.\n  syncHiddenInput?: boolean;\n  // Minimal constraints\n  maxFiles?: number;\n  maxFileSize?: number; // bytes\n  onError?: (err: {\n    code: 'max_files' | 'max_file_size' | 'accept';\n    message: string;\n  }) => void;\n  onSubmit: (\n    message: PromptInputMessage,\n    event: FormEvent<HTMLFormElement>,\n  ) => void;\n};\n\nexport const PromptInput = ({\n  sx,\n  accept,\n  multiple,\n  globalDrop,\n  syncHiddenInput,\n  maxFiles,\n  maxFileSize,\n  onError,\n  onSubmit,\n  children,\n}: React.PropsWithChildren<PromptInputProps>) => {\n  const [items, setItems] = useState<(FileUIPart & { id: string })[]>([]);\n  const inputRef = useRef<HTMLInputElement | null>(null);\n  const anchorRef = useRef<HTMLSpanElement>(null);\n  const formRef = useRef<HTMLFormElement | null>(null);\n\n  // Find nearest form to scope drag & drop\n  useEffect(() => {\n    const root = anchorRef.current?.closest('form');\n    if (root instanceof HTMLFormElement) {\n      formRef.current = root;\n    }\n  }, []);\n\n  const openFileDialog = useCallback(() => {\n    inputRef.current?.click();\n  }, []);\n\n  const matchesAccept = useCallback(\n    (f: File) => {\n      if (!accept || accept.trim() === '') {\n        return true;\n      }\n      // Simple check: if accept includes \"image/*\", filter to images; otherwise allow.\n      if (accept.includes('image/*')) {\n        return f.type.startsWith('image/');\n      }\n      return true;\n    },\n    [accept],\n  );\n\n  const add = useCallback(\n    (files: File[] | FileList) => {\n      const incoming = Array.from(files);\n      const accepted = incoming.filter((f) => matchesAccept(f));\n      if (accepted.length === 0) {\n        onError?.({\n          code: 'accept',\n          message: 'No files match the accepted types.',\n        });\n        return;\n      }\n      const withinSize = (f: File) =>\n        maxFileSize ? f.size <= maxFileSize : true;\n      const sized = accepted.filter(withinSize);\n      if (sized.length === 0 && accepted.length > 0) {\n        onError?.({\n          code: 'max_file_size',\n          message: 'All files exceed the maximum size.',\n        });\n        return;\n      }\n      setItems((prev) => {\n        const capacity =\n          typeof maxFiles === 'number'\n            ? Math.max(0, maxFiles - prev.length)\n            : undefined;\n        const capped =\n          typeof capacity === 'number' ? sized.slice(0, capacity) : sized;\n        if (typeof capacity === 'number' && sized.length > capacity) {\n          onError?.({\n            code: 'max_files',\n            message: 'Too many files. Some were not added.',\n          });\n        }\n        const next: (FileUIPart & { id: string })[] = [];\n        for (const file of capped) {\n          next.push({\n            id: nanoid(),\n            type: 'file',\n            url: URL.createObjectURL(file),\n            mediaType: file.type,\n            filename: file.name,\n          });\n        }\n        return prev.concat(next);\n      });\n    },\n    [matchesAccept, maxFiles, maxFileSize, onError],\n  );\n\n  const remove = useCallback((id: string) => {\n    setItems((prev) => {\n      const found = prev.find((file) => file.id === id);\n      if (found?.url) {\n        URL.revokeObjectURL(found.url);\n      }\n      return prev.filter((file) => file.id !== id);\n    });\n  }, []);\n\n  const clear = useCallback(() => {\n    setItems((prev) => {\n      for (const file of prev) {\n        if (file.url) {\n          URL.revokeObjectURL(file.url);\n        }\n      }\n      return [];\n    });\n  }, []);\n\n  // Note: File input cannot be programmatically set for security reasons\n  // The syncHiddenInput prop is no longer functional\n  useEffect(() => {\n    if (syncHiddenInput && inputRef.current) {\n      // Clear the input when items are cleared\n      if (items.length === 0) {\n        inputRef.current.value = '';\n      }\n    }\n  }, [items, syncHiddenInput]);\n\n  // Attach drop handlers on nearest form and document (opt-in)\n  useEffect(() => {\n    const form = formRef.current;\n    if (!form) {\n      return;\n    }\n    const onDragOver = (e: DragEvent) => {\n      if (e.dataTransfer?.types?.includes('Files')) {\n        e.preventDefault();\n      }\n    };\n    const onDrop = (e: DragEvent) => {\n      if (e.dataTransfer?.types?.includes('Files')) {\n        e.preventDefault();\n      }\n      if (e.dataTransfer?.files && e.dataTransfer.files.length > 0) {\n        add(e.dataTransfer.files);\n      }\n    };\n    form.addEventListener('dragover', onDragOver);\n    form.addEventListener('drop', onDrop);\n    return () => {\n      form.removeEventListener('dragover', onDragOver);\n      form.removeEventListener('drop', onDrop);\n    };\n  }, [add]);\n\n  useEffect(() => {\n    if (!globalDrop) {\n      return;\n    }\n    const onDragOver = (e: DragEvent) => {\n      if (e.dataTransfer?.types?.includes('Files')) {\n        e.preventDefault();\n      }\n    };\n    const onDrop = (e: DragEvent) => {\n      if (e.dataTransfer?.types?.includes('Files')) {\n        e.preventDefault();\n      }\n      if (e.dataTransfer?.files && e.dataTransfer.files.length > 0) {\n        add(e.dataTransfer.files);\n      }\n    };\n    document.addEventListener('dragover', onDragOver);\n    document.addEventListener('drop', onDrop);\n    return () => {\n      document.removeEventListener('dragover', onDragOver);\n      document.removeEventListener('drop', onDrop);\n    };\n  }, [add, globalDrop]);\n\n  const handleChange: ChangeEventHandler<HTMLInputElement> = (event) => {\n    if (event.currentTarget.files) {\n      add(event.currentTarget.files);\n    }\n  };\n\n  const handleSubmit: FormEventHandler<HTMLFormElement> = (event) => {\n    event.preventDefault();\n\n    const files: FileUIPart[] = items.map(({ ...item }) => ({\n      ...item,\n    }));\n\n    onSubmit({ text: event.currentTarget.message.value, files }, event);\n  };\n\n  const ctx = useMemo<AttachmentsContext>(\n    () => ({\n      files: items.map((item) => ({ ...item, id: item.id })),\n      add,\n      remove,\n      clear,\n      openFileDialog,\n      fileInputRef: inputRef,\n    }),\n    [items, add, remove, clear, openFileDialog],\n  );\n\n  return (\n    <AttachmentsContext.Provider value={ctx}>\n      <Box\n        component=\"span\"\n        aria-hidden=\"true\"\n        ref={anchorRef}\n        sx={{ display: 'none' }}\n      />\n      <Box\n        component=\"input\"\n        accept={accept}\n        multiple={multiple}\n        onChange={handleChange}\n        ref={inputRef}\n        type=\"file\"\n        sx={{ display: 'none' }}\n      />\n      <Box\n        component=\"form\"\n        onSubmit={handleSubmit}\n        sx={{\n          width: '100%',\n          overflow: 'hidden',\n          borderRadius: 2,\n          border: 1,\n          borderColor: 'divider',\n          bgcolor: 'background.paper',\n          boxShadow: 1,\n          '& > *:not(:last-child)': {\n            borderBottom: 1,\n            borderColor: 'divider',\n          },\n          ...sx,\n        }}\n      >\n        {children}\n      </Box>\n    </AttachmentsContext.Provider>\n  );\n};\n\nexport type PromptInputBodyProps = {\n  children?: React.ReactNode;\n  sx?: SxProps<Theme>;\n};\n\nexport const PromptInputBody = ({ children, sx }: PromptInputBodyProps) => (\n  <Box sx={{ display: 'flex', flexDirection: 'column', ...sx }}>{children}</Box>\n);\n\nexport type PromptInputTextareaProps = ComponentProps<typeof InputBase> & {\n  placeholder?: string;\n};\n\nexport const PromptInputTextarea = ({\n  onChange,\n  placeholder = 'What would you like to know?',\n  sx,\n  ...props\n}: PromptInputTextareaProps) => {\n  const handleKeyDown: KeyboardEventHandler<HTMLTextAreaElement> = (e) => {\n    if (e.key === 'Enter') {\n      // Don't submit if IME composition is in progress\n      if (e.nativeEvent.isComposing) {\n        return;\n      }\n\n      if (e.shiftKey) {\n        // Allow newline\n        return;\n      }\n\n      // Submit on Enter (without Shift)\n      e.preventDefault();\n      const form = e.currentTarget.form;\n      if (form) {\n        form.requestSubmit();\n      }\n    }\n  };\n\n  return (\n    <InputBase\n      multiline\n      name=\"message\"\n      onChange={onChange}\n      onKeyDown={handleKeyDown}\n      placeholder={placeholder}\n      maxRows={3}\n      sx={{\n        width: '100%',\n        p: 1.5,\n        '& .MuiInputBase-input': {\n          resize: 'none',\n          overflow: 'auto',\n          fieldSizing: 'content',\n        },\n        ...sx,\n      }}\n      {...props}\n    />\n  );\n};\n\nexport type PromptInputToolbarProps = {\n  children?: React.ReactNode;\n  sx?: SxProps<Theme>;\n};\n\nexport const PromptInputToolbar = ({\n  children,\n  sx,\n}: PromptInputToolbarProps) => (\n  <Box\n    sx={{\n      display: 'flex',\n      alignItems: 'center',\n      justifyContent: 'space-between',\n      p: 0.5,\n      ...sx,\n    }}\n  >\n    {children}\n  </Box>\n);\n\nexport type PromptInputToolsProps = {\n  children?: React.ReactNode;\n  sx?: SxProps<Theme>;\n};\n\nexport const PromptInputTools = ({ children, sx }: PromptInputToolsProps) => (\n  <Box\n    sx={{\n      display: 'flex',\n      alignItems: 'center',\n      gap: 0.5,\n      '& > button:first-of-type': {\n        borderBottomLeftRadius: 12,\n      },\n      ...sx,\n    }}\n  >\n    {children}\n  </Box>\n);\n\nexport type PromptInputButtonProps = ComponentProps<typeof Button> & {\n  variant?: 'text' | 'contained' | 'outlined';\n};\n\nexport const PromptInputButton = memo(\n  ({\n    variant = 'text',\n    size,\n    children,\n    sx,\n    ...props\n  }: PromptInputButtonProps) => {\n    const isIconButton = Children.count(children) === 1;\n\n    if (isIconButton) {\n      return (\n        <IconButton\n          size={size || 'medium'}\n          sx={{\n            borderRadius: 2,\n            color: variant === 'text' ? 'text.secondary' : undefined,\n            ...sx,\n          }}\n          {...props}\n        >\n          {children}\n        </IconButton>\n      );\n    }\n\n    return (\n      <Button\n        variant={variant}\n        size={size || 'medium'}\n        sx={{\n          minWidth: 'auto',\n          px: 1.5,\n          gap: 0.75,\n          borderRadius: 2,\n          flexShrink: 0,\n          color: variant === 'text' ? 'text.secondary' : undefined,\n          ...sx,\n        }}\n        {...props}\n      >\n        {children}\n      </Button>\n    );\n  },\n);\n\nPromptInputButton.displayName = 'PromptInputButton';\n\nexport type PromptInputActionMenuProps = {\n  children?: React.ReactNode;\n};\n\nexport const PromptInputActionMenu = ({\n  children,\n}: PromptInputActionMenuProps) => {\n  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);\n  const open = Boolean(anchorEl);\n\n  const childrenArray = Children.toArray(children);\n  const trigger = childrenArray.find(\n    (child): child is React.ReactElement<PromptInputActionMenuTriggerProps> =>\n      React.isValidElement(child) &&\n      child.type === PromptInputActionMenuTrigger,\n  );\n  const content = childrenArray.find(\n    (child): child is React.ReactElement<PromptInputActionMenuContentProps> =>\n      React.isValidElement(child) &&\n      child.type === PromptInputActionMenuContent,\n  );\n\n  return (\n    <>\n      {trigger &&\n        React.cloneElement(trigger, {\n          onClick: (e: MouseEvent<HTMLElement>) => setAnchorEl(e.currentTarget),\n        })}\n      <Menu\n        anchorEl={anchorEl}\n        open={open}\n        onClose={() => setAnchorEl(null)}\n        anchorOrigin={{\n          vertical: 'top',\n          horizontal: 'left',\n        }}\n        transformOrigin={{\n          vertical: 'bottom',\n          horizontal: 'left',\n        }}\n      >\n        {content &&\n          React.cloneElement(content, {\n            onClose: () => setAnchorEl(null),\n          })}\n      </Menu>\n    </>\n  );\n};\n\nexport type PromptInputActionMenuTriggerProps = ComponentProps<\n  typeof Button\n> & {\n  onClick?: (e: MouseEvent<HTMLElement>) => void;\n};\n\nexport const PromptInputActionMenuTrigger = ({\n  children,\n  onClick,\n  sx,\n  ...props\n}: PromptInputActionMenuTriggerProps) => (\n  <PromptInputButton onClick={onClick} sx={sx} {...props}>\n    {children ?? <PlusIcon size={16} />}\n  </PromptInputButton>\n);\n\nexport type PromptInputActionMenuContentProps = {\n  children?: React.ReactNode;\n  onClose?: () => void;\n};\n\nexport const PromptInputActionMenuContent = ({\n  children,\n  onClose,\n}: PromptInputActionMenuContentProps) => (\n  <Box onClick={onClose}>{children}</Box>\n);\n\nexport type PromptInputActionMenuItemProps = ComponentProps<typeof MenuItem>;\n\nexport const PromptInputActionMenuItem = (\n  props: PromptInputActionMenuItemProps,\n) => <MenuItem {...props} />;\n\n// Note: Actions that perform side-effects (like opening a file dialog)\n// are provided in opt-in modules (e.g., prompt-input-attachments).\n\nexport type PromptInputSubmitProps = ComponentProps<typeof Button> & {\n  status?: ChatStatus;\n};\n\nexport const PromptInputSubmit = memo(\n  ({\n    variant = 'contained',\n    size = 'medium',\n    status,\n    children,\n    sx,\n    ...props\n  }: PromptInputSubmitProps) => {\n    let Icon = <SendIcon size={16} />;\n\n    if (status === 'submitted') {\n      Icon = <CircularProgress size={16} />;\n    } else if (status === 'streaming') {\n      Icon = <SquareIcon size={16} />;\n    } else if (status === 'error') {\n      Icon = <XIcon size={16} />;\n    }\n\n    const isIconOnly = !children;\n\n    if (isIconOnly) {\n      return (\n        <IconButton\n          type=\"submit\"\n          size={size}\n          sx={{\n            borderRadius: 2,\n            ...sx,\n          }}\n          {...props}\n        >\n          {Icon}\n        </IconButton>\n      );\n    }\n\n    return (\n      <Button\n        type=\"submit\"\n        variant={variant}\n        size={size}\n        sx={{\n          gap: 0.75,\n          borderRadius: 2,\n          ...sx,\n        }}\n        {...props}\n      >\n        {children}\n      </Button>\n    );\n  },\n);\n\nPromptInputSubmit.displayName = 'PromptInputSubmit';\n\nexport type PromptInputModelSelectProps = ComponentProps<typeof Select>;\n\nexport const PromptInputModelSelect = (props: PromptInputModelSelectProps) => (\n  <Select\n    variant=\"standard\"\n    sx={{\n      minWidth: 120,\n      '& .MuiInput-root': {\n        border: 'none',\n        bgcolor: 'transparent',\n        fontWeight: 500,\n        color: 'text.secondary',\n        transition: 'all 0.2s',\n        '&:hover': {\n          bgcolor: 'action.hover',\n          color: 'text.primary',\n        },\n        '&.Mui-focused': {\n          bgcolor: 'action.hover',\n          color: 'text.primary',\n        },\n        '&:before, &:after': {\n          display: 'none',\n        },\n      },\n      '& .MuiSelect-select': {\n        px: 1,\n        py: 0.5,\n        borderRadius: 1,\n      },\n    }}\n    {...props}\n  />\n);\n",
      "type": "registry:item"
    },
    {
      "path": "components/ai-prompt-input/index.ts",
      "target": "src/mui-treasury/components/ai-prompt-input/index.ts",
      "content": "export * from './ai-prompt-input';\n",
      "type": "registry:item"
    }
  ],
  "meta": {
    "category": "ai",
    "subcategory": "elements"
  }
}