components/linyi/prompt-input.tsx
lucide-react
"use client"; import * as React from "react";import { AlertCircle, Check, ChevronDown, Code2, Globe, Paperclip, Send, Square, X,} from "lucide-react";import { cn } from "@/lib/cn";import { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuTrigger,} from "@/components/linyi/dropdown-menu"; export type PromptStatus = "idle" | "streaming" | "done" | "error"; export interface PromptModelOption { id: string; label: string; description?: string;} export interface PromptContextOption { id: string; label: string; compactLabel?: string; icon?: React.ReactNode;} export interface PromptAttachment { id: string; name: string; sizeLabel?: string;} export interface PromptSubmitPayload { prompt: string; model: string; contexts: string[]; attachments?: PromptAttachment[];} export const DEFAULT_PROMPT_MODELS: PromptModelOption[] = [ { id: "linyi-4.0", label: "Linyi-4.0", description: "综合推理" }, { id: "linyi-code", label: "Linyi-Code", description: "代码工程" }, { id: "linyi-fast", label: "Linyi-Fast", description: "低延迟响应" },]; export const DEFAULT_CONTEXT_OPTIONS: PromptContextOption[] = [ { id: "codebase", label: "附带代码库", compactLabel: "代码库" }, { id: "web", label: "联网检索", compactLabel: "联网" },]; export interface PromptInputProps { value?: string; defaultValue?: string; onValueChange?: (value: string) => void; model?: string; defaultModel?: string; onModelChange?: (modelId: string) => void; models?: PromptModelOption[]; contextOptions?: PromptContextOption[]; contexts?: string[]; defaultContexts?: string[]; onContextsChange?: (contexts: string[]) => void; attachments?: PromptAttachment[]; onRemoveAttachment?: (id: string) => void; attachmentSlot?: React.ReactNode; leadingActions?: React.ReactNode; status?: PromptStatus; errorMessage?: string | null; onSubmit?: (payload: PromptSubmitPayload) => void; onStop?: () => void; placeholder?: string; maxLength?: number; compact?: boolean; disabled?: boolean; className?: string;} export function PromptInput({ value: controlledValue, defaultValue = "", onValueChange, model: controlledModel, defaultModel = DEFAULT_PROMPT_MODELS[0].id, onModelChange, models = DEFAULT_PROMPT_MODELS, contextOptions = DEFAULT_CONTEXT_OPTIONS, contexts: controlledContexts, defaultContexts = ["codebase"], onContextsChange, attachments = [], onRemoveAttachment, attachmentSlot, leadingActions, status = "idle", errorMessage, onSubmit, onStop, placeholder = "输入组件需求,Enter 发送,Shift+Enter 换行...", maxLength = 400, compact = false, disabled = false, className,}: PromptInputProps) { const [uncontrolledValue, setUncontrolledValue] = React.useState(defaultValue); const [uncontrolledModel, setUncontrolledModel] = React.useState(defaultModel); const [uncontrolledContexts, setUncontrolledContexts] = React.useState<string[]>(defaultContexts); const [justSent, setJustSent] = React.useState(false); const textareaRef = React.useRef<HTMLTextAreaElement>(null); const sentTimerRef = React.useRef<number | null>(null); const value = controlledValue ?? uncontrolledValue; const currentModelId = controlledModel ?? uncontrolledModel; const activeContexts = controlledContexts ?? uncontrolledContexts; const activeModel = models.find((m) => m.id === currentModelId) ?? models[0]; const isStreaming = status === "streaming"; React.useEffect(() => { return () => { if (sentTimerRef.current !== null) window.clearTimeout(sentTimerRef.current); }; }, []); React.useEffect(() => { const el = textareaRef.current; if (!el) return; el.style.height = "auto"; const maxHeight = compact ? 52 : 128; el.style.height = `${Math.min(el.scrollHeight, maxHeight)}px`; }, [value, compact]); const updateValue = (next: string) => { const clipped = maxLength ? next.slice(0, maxLength) : next; if (controlledValue === undefined) setUncontrolledValue(clipped); onValueChange?.(clipped); }; const selectModel = (id: string) => { if (controlledModel === undefined) setUncontrolledModel(id); onModelChange?.(id); }; const toggleContext = (id: string) => { const next = activeContexts.includes(id) ? activeContexts.filter((item) => item !== id) : [...activeContexts, id]; if (controlledContexts === undefined) setUncontrolledContexts(next); onContextsChange?.(next); }; const handleSubmit = () => { if (disabled || isStreaming) return; const trimmed = value.trim(); if (!trimmed) return; onSubmit?.({ prompt: trimmed, model: activeModel.id, contexts: activeContexts, attachments, }); updateValue(""); setJustSent(true); if (sentTimerRef.current !== null) window.clearTimeout(sentTimerRef.current); sentTimerRef.current = window.setTimeout(() => setJustSent(false), 1200); }; const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => { if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) { e.preventDefault(); handleSubmit(); } }; const handlePointerMove = (e: React.PointerEvent<HTMLButtonElement>) => { const rect = e.currentTarget.getBoundingClientRect(); if (rect.width > 0 && rect.height > 0) { e.currentTarget.style.setProperty( "--mx", `${(((e.clientX - rect.left) / rect.width) * 100).toFixed(1)}%` ); e.currentTarget.style.setProperty( "--my", `${(((e.clientY - rect.top) / rect.height) * 100).toFixed(1)}%` ); } }; const visibleContexts = compact ? contextOptions.slice(0, 1) : contextOptions; const canSend = value.trim().length > 0 && !disabled && !isStreaming; return ( <div data-status={status} className={cn( "w-full rounded-[16px] bg-surface border shadow-panel transition-colors focus-within:border-accent-border", status === "error" ? "border-danger-border" : "border-line-strong", compact ? "p-2.5 space-y-2" : "p-3 space-y-2.5", className )} > {/* Attachment Chips or Custom Attachment Slot */} {!compact && (attachments.length > 0 || attachmentSlot) && ( <div className="flex flex-wrap items-center gap-1.5 px-1"> {attachments.map((att) => ( <span key={att.id} className="inline-flex items-center gap-1.5 rounded-pill border border-line bg-well px-2.5 py-0.5 text-[11px] text-fg-secondary" > <Paperclip className="h-3 w-3 text-fg-muted flex-shrink-0" aria-hidden="true" /> <span className="max-w-[140px] truncate">{att.name}</span> {att.sizeLabel && ( <span className="font-mono-num text-[10px] text-fg-muted">{att.sizeLabel}</span> )} {onRemoveAttachment && ( <button type="button" onClick={() => onRemoveAttachment(att.id)} aria-label={`移除附件:${att.name}`} className="ml-0.5 inline-flex h-4 w-4 cursor-pointer items-center justify-center rounded-full text-fg-muted hover:bg-surface hover:text-fg" > <X className="h-2.5 w-2.5" aria-hidden="true" /> </button> )} </span> ))} {attachmentSlot} </div> )} <textarea ref={textareaRef} rows={compact ? 1 : 2} value={value} disabled={disabled} onChange={(e) => updateValue(e.target.value)} onKeyDown={handleKeyDown} placeholder={compact ? "输入组件需求..." : placeholder} aria-label="指令输入" className={cn( "w-full resize-none bg-transparent text-fg placeholder:text-fg-muted outline-none leading-relaxed block", compact ? "text-xs px-1 py-0.5 min-h-[26px]" : "text-[13px] px-1.5 py-1 min-h-[46px]" )} /> {status === "error" && errorMessage && !compact && ( <div role="alert" className="flex items-center gap-1.5 rounded-control border border-danger-border bg-danger-soft px-2.5 py-1.5 text-[11px] text-danger" > <AlertCircle className="h-3.5 w-3.5 flex-shrink-0" aria-hidden="true" /> <span>{errorMessage}</span> </div> )} <div className="flex items-center justify-between gap-2 flex-wrap"> <div className="flex items-center gap-1.5 flex-wrap min-w-0"> {leadingActions} <DropdownMenu> <DropdownMenuTrigger render={ <button type="button" disabled={disabled} className="inline-flex items-center gap-1 h-7 px-2.5 rounded-pill bg-well hover:bg-well/80 border border-line font-mono-num text-[11px] text-fg-secondary hover:text-fg cursor-pointer transition-colors" > <span className="truncate max-w-[92px]">{activeModel.label}</span> <ChevronDown className="w-3 h-3 opacity-70 flex-shrink-0" aria-hidden="true" /> </button> } /> <DropdownMenuContent align="start" sideOffset={6} className="min-w-[180px]"> <DropdownMenuGroup> <DropdownMenuLabel>选择推理模型</DropdownMenuLabel> {models.map((item) => { const selected = item.id === activeModel.id; return ( <DropdownMenuItem key={item.id} onClick={() => selectModel(item.id)}> <span className="flex flex-col"> <span className="font-mono-num text-xs text-fg">{item.label}</span> {item.description && ( <span className="text-[10px] text-fg-muted">{item.description}</span> )} </span> {selected && ( <Check className="w-3.5 h-3.5 text-accent flex-shrink-0" aria-hidden="true" /> )} </DropdownMenuItem> ); })} </DropdownMenuGroup> </DropdownMenuContent> </DropdownMenu> {visibleContexts.map((opt) => { const active = activeContexts.includes(opt.id); const DefaultIcon = opt.id === "web" ? Globe : Code2; return ( <button key={opt.id} type="button" aria-pressed={active} disabled={disabled} onClick={() => toggleContext(opt.id)} className={cn( "inline-flex items-center gap-1 h-7 px-2.5 rounded-pill border text-[11px] cursor-pointer transition-colors", active ? "bg-accent-soft text-accent border-accent-border" : "bg-transparent text-fg-secondary border-line hover:border-line-strong hover:text-fg" )} > {opt.icon ?? <DefaultIcon className="w-3 h-3 flex-shrink-0" aria-hidden="true" />} <span>{compact ? (opt.compactLabel ?? opt.label) : opt.label}</span> </button> ); })} </div> <div className="flex items-center gap-2 ml-auto"> {!compact && ( <span className="font-mono-num text-[10px] text-fg-muted"> {value.length}/{maxLength} </span> )} {isStreaming ? ( <button type="button" onClick={onStop} className="inline-flex items-center gap-1 h-7 px-3 rounded-pill bg-danger-soft text-danger border border-danger-border text-[11px] font-medium cursor-pointer transition-opacity hover:opacity-90" > <Square className="w-2.5 h-2.5 fill-current" aria-hidden="true" /> <span>停止生成</span> </button> ) : ( <button type="button" disabled={!canSend && !justSent} onClick={handleSubmit} onPointerMove={handlePointerMove} className="ui-btn ui-btn-accent h-7 px-3 text-[11px]" > {justSent ? ( <Check className="w-3 h-3" aria-hidden="true" /> ) : ( <Send className="w-3 h-3" aria-hidden="true" /> )} <span>{justSent ? "已发送" : "发送"}</span> </button> )} </div> </div> </div> );}