跳至正文
获取 Pro
业务区块B.01

AI 对话工作台

FreeRegistry
components/linyi/ai-workspace.tsx
lucide-reactmotion
"use client";
 
import * as React from "react";
import { motion, AnimatePresence } from "motion/react";
import { Send, Copy, Check, Sparkles, CornerDownLeft } from "lucide-react";
import { cn } from "@/lib/cn";
import { SPRING_SNAPPY, SPRING_SMOOTH } from "@/lib/motion";
 
export interface AIWorkspaceMessage {
id: string;
role: "user" | "assistant";
content: string;
model?: string;
time?: string;
}
 
export interface AIWorkspaceModel {
id: string;
label: string;
badge?: string;
}
 
export interface AIWorkspaceProps {
models?: AIWorkspaceModel[];
defaultModel?: string;
initialMessages?: AIWorkspaceMessage[];
suggestions?: string[];
onGenerateReply?: (prompt: string, modelId: string) => string;
placeholder?: string;
compact?: boolean;
className?: string;
}
 
const DEFAULT_MODELS: AIWorkspaceModel[] = [
{ id: "linyi-4", label: "Linyi-4.0", badge: "均衡" },
{ id: "linyi-fast", label: "Linyi-Fast", badge: "快速" },
];
 
const DEFAULT_MESSAGES: AIWorkspaceMessage[] = [
{
id: "m-1",
role: "user",
content: "按 Linyi UI 规范生成一个顶部导航栏",
time: "14:02",
},
{
id: "m-2",
role: "assistant",
content: "已输出双主题语义令牌版本:外框 1px 发丝描边、等宽数字索引,并内置液态玻璃胶囊操作栏。",
model: "Linyi-4.0",
time: "14:02",
},
];
 
const DEFAULT_SUGGESTIONS = [
"生成定价双栏卡片",
"补充键盘无障碍焦点",
"输出深浅双主题令牌",
];
 
function buildDefaultReply(prompt: string, modelId: string): string {
const speedNote = modelId === "linyi-fast" ? "(快速模式)" : "";
if (prompt.includes("定价")) {
return `已生成双栏定价结构${speedNote}:左栏采用素宣浅色纸面,右栏使用端砚反色并突出朱砂主按钮。`;
}
if (prompt.includes("键盘") || prompt.includes("无障碍")) {
return `已补全键盘导航${speedNote}:所有可聚焦元素统一配置 2px 朱砂 focus-visible 焦点环与标准 ARIA 属性。`;
}
if (prompt.includes("令牌") || prompt.includes("主题")) {
return `已整理双主题变量${speedNote}:覆盖 bg-canvas、bg-surface、border-line 与等宽数字字体规范。`;
}
return `已按 Linyi UI 规范处理「${prompt.slice(0, 18)}${prompt.length > 18 ? "…" : ""}」${speedNote},结构与样式均已对齐设计令牌。`;
}
 
function formatCurrentTime() {
const now = new Date();
return `${String(now.getHours()).padStart(2, "0")}:${String(now.getMinutes()).padStart(2, "0")}`;
}
 
function DotMatrixThinking() {
const dots = [0, 1, 2, 3, 4, 5, 6, 7, 8];
return (
<div
className="inline-flex items-center gap-2.5 rounded-well border border-line bg-surface px-3 py-2 text-xs text-fg-secondary"
role="status"
aria-live="polite"
>
<div className="grid grid-cols-3 gap-[3px]" aria-hidden="true">
{dots.map((idx) => (
<motion.span
key={idx}
className="h-1 w-1 rounded-full bg-accent"
animate={{ opacity: [0.22, 1, 0.22], scale: [0.82, 1.12, 0.82] }}
transition={{
duration: 1.05,
repeat: Infinity,
ease: "easeInOut",
delay: (idx % 3) * 0.14 + Math.floor(idx / 3) * 0.1,
}}
/>
))}
</div>
<span className="font-mono-num text-[11px] text-fg-muted">正在推演组件结构...</span>
</div>
);
}
 
export function AIWorkspace({
models = DEFAULT_MODELS,
defaultModel = models[0]?.id ?? "linyi-4",
initialMessages = DEFAULT_MESSAGES,
suggestions = DEFAULT_SUGGESTIONS,
onGenerateReply = buildDefaultReply,
placeholder = "描述需要生成的界面或规范...",
compact = false,
className,
}: AIWorkspaceProps) {
const uid = React.useId();
const [activeModel, setActiveModel] = React.useState(defaultModel);
const [messages, setMessages] = React.useState<AIWorkspaceMessage[]>(initialMessages);
const [input, setInput] = React.useState("");
const [thinking, setThinking] = React.useState(false);
const [copiedId, setCopiedId] = React.useState<string | null>(null);
 
const replyTimerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null);
const copyTimerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null);
const listEndRef = React.useRef<HTMLDivElement | null>(null);
 
React.useEffect(() => {
return () => {
if (replyTimerRef.current) clearTimeout(replyTimerRef.current);
if (copyTimerRef.current) clearTimeout(copyTimerRef.current);
};
}, []);
 
React.useEffect(() => {
if (!compact) {
listEndRef.current?.scrollIntoView({ behavior: "smooth", block: "nearest" });
}
}, [messages.length, thinking, compact]);
 
const currentModelObj = models.find((m) => m.id === activeModel) ?? models[0];
 
const handleSend = (rawText?: string) => {
const text = (rawText ?? input).trim();
if (!text || thinking) return;
 
const userMsg: AIWorkspaceMessage = {
id: `u-${Date.now()}`,
role: "user",
content: text,
time: formatCurrentTime(),
};
 
setMessages((prev) => [...prev, userMsg]);
if (rawText === undefined) setInput("");
setThinking(true);
 
if (replyTimerRef.current) clearTimeout(replyTimerRef.current);
const delay = activeModel === "linyi-fast" ? 520 : 880;
const modelLabel = currentModelObj?.label ?? activeModel;
 
replyTimerRef.current = setTimeout(() => {
const replyText = onGenerateReply(text, activeModel);
setMessages((prev) => [
...prev,
{
id: `a-${Date.now()}`,
role: "assistant",
content: replyText,
model: modelLabel,
time: formatCurrentTime(),
},
]);
setThinking(false);
replyTimerRef.current = null;
}, delay);
};
 
const handleCopy = (id: string, content: string) => {
if (typeof navigator !== "undefined" && navigator.clipboard) {
navigator.clipboard.writeText(content).catch(() => {});
}
setCopiedId(id);
if (copyTimerRef.current) clearTimeout(copyTimerRef.current);
copyTimerRef.current = setTimeout(() => {
setCopiedId(null);
copyTimerRef.current = null;
}, 1500);
};
 
if (compact) {
const visible = messages.slice(-2);
return (
<div className={cn("w-full max-w-[264px] space-y-2", className)}>
<div className="flex items-center justify-between px-0.5">
<div className="inline-flex items-center gap-1 rounded-pill border border-line bg-surface px-2 py-0.5 text-[10px] font-medium text-fg-secondary">
<span className="h-1.5 w-1.5 rounded-full bg-accent" />
<span className="font-mono-num">{currentModelObj?.label}</span>
</div>
<span className="font-mono-num text-[10px] text-fg-muted">
{thinking ? "思考中" : `${messages.length} 条`}
</span>
</div>
 
<div className="space-y-1.5">
{visible.map((m) => (
<div
key={m.id}
className={cn(
"truncate rounded-control px-2.5 py-1.5 text-[11px]",
m.role === "user"
? "bg-inverse text-fg-inverse"
: "border border-line bg-surface text-fg"
)}
>
{m.content}
</div>
))}
</div>
 
<div className="lg-bar flex items-center gap-1.5 rounded-pill p-1">
<input
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") {
e.preventDefault();
handleSend();
}
}}
placeholder="输入指令..."
aria-label="对话输入"
className="min-w-0 flex-1 bg-transparent px-2.5 text-[11px] text-fg placeholder:text-fg-muted outline-none"
/>
<button
type="button"
onClick={() => handleSend()}
disabled={!input.trim() || thinking}
className="ui-btn ui-btn-accent h-7 w-7 flex-shrink-0 p-0"
aria-label="发送消息"
>
<Send className="h-3 w-3" />
</button>
</div>
</div>
);
}
 
return (
<div
className={cn(
"flex w-full max-w-xl flex-col overflow-hidden rounded-panel border border-line bg-surface shadow-panel",
className
)}
>
{/* Top Bar: Model Switcher */}
<div className="flex flex-wrap items-center justify-between gap-2 border-b border-line bg-surface-2 px-4 py-2.5">
<div className="flex items-center gap-2">
<span className="flex h-6 w-6 items-center justify-center rounded-control bg-accent-soft text-accent">
<Sparkles className="h-3.5 w-3.5" aria-hidden="true" />
</span>
<span className="text-xs font-medium text-fg">AI 协作会话</span>
</div>
 
<div
className="inline-flex items-center gap-1 rounded-pill border border-line bg-well p-0.5"
role="tablist"
aria-label="切换模型"
>
{models.map((m) => {
const active = m.id === activeModel;
return (
<button
key={m.id}
type="button"
role="tab"
aria-selected={active}
onClick={() => setActiveModel(m.id)}
className={cn(
"relative cursor-pointer rounded-pill px-2.5 py-1 text-[11px] font-medium transition-colors",
active ? "text-fg" : "text-fg-muted hover:text-fg-secondary"
)}
>
{active && (
<motion.span
layoutId={`ai-workspace-model-pill-${uid}`}
transition={SPRING_SNAPPY}
className="absolute inset-0 rounded-pill border border-line bg-surface shadow-panel"
/>
)}
<span className="relative z-10 inline-flex items-center gap-1 font-mono-num">
{m.label}
{m.badge && (
<span className="text-[10px] font-normal text-fg-muted">{m.badge}</span>
)}
</span>
</button>
);
})}
</div>
</div>
 
{/* Conversation Thread */}
<div className="no-scrollbar flex max-h-[280px] min-h-[210px] flex-col gap-3 overflow-y-auto bg-canvas/50 p-4">
<AnimatePresence initial={false}>
{messages.map((msg) => {
const isUser = msg.role === "user";
const isCopied = copiedId === msg.id;
return (
<motion.div
key={msg.id}
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -4 }}
transition={SPRING_SMOOTH}
className={cn("flex flex-col gap-1", isUser ? "items-end" : "items-start")}
>
<div
className={cn(
"max-w-[88%] rounded-well px-3.5 py-2.5 text-xs leading-relaxed",
isUser
? "bg-inverse text-fg-inverse"
: "border border-line bg-surface text-fg shadow-panel"
)}
>
<p className="whitespace-pre-wrap">{msg.content}</p>
</div>
 
<div className="flex items-center gap-2 px-1 text-[10px] text-fg-muted">
{!isUser && msg.model && <span className="font-mono-num">{msg.model}</span>}
{msg.time && <span className="font-mono-num">{msg.time}</span>}
{!isUser && (
<button
type="button"
onClick={() => handleCopy(msg.id, msg.content)}
className="inline-flex cursor-pointer items-center gap-1 rounded px-1 py-0.5 text-fg-muted transition-colors hover:bg-well hover:text-fg"
aria-label="复制回复内容"
>
{isCopied ? (
<>
<Check className="h-3 w-3 text-success" />
<span className="text-success">已复制</span>
</>
) : (
<>
<Copy className="h-3 w-3" />
<span>复制</span>
</>
)}
</button>
)}
</div>
</motion.div>
);
})}
</AnimatePresence>
 
<AnimatePresence>
{thinking && (
<motion.div
initial={{ opacity: 0, y: 6 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -4 }}
transition={SPRING_SNAPPY}
className="flex items-start"
>
<DotMatrixThinking />
</motion.div>
)}
</AnimatePresence>
<div ref={listEndRef} />
</div>
 
{/* Suggestions & Liquid Glass Composer */}
<div className="space-y-2.5 border-t border-line bg-surface p-3.5">
{suggestions.length > 0 && (
<div className="flex flex-wrap items-center gap-1.5">
{suggestions.map((item) => (
<button
key={item}
type="button"
disabled={thinking}
onClick={() => handleSend(item)}
className="cursor-pointer rounded-pill border border-line bg-surface-2 px-2.5 py-1 text-[11px] text-fg-secondary transition-colors hover:border-line-strong hover:bg-well hover:text-fg disabled:cursor-not-allowed disabled:opacity-45"
>
{item}
</button>
))}
</div>
)}
 
<div className="lg-bar flex items-center gap-2 rounded-pill p-1.5 pl-3.5">
<input
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
handleSend();
}
}}
placeholder={placeholder}
aria-label="向 AI 发送消息"
className="min-w-0 flex-1 bg-transparent text-xs text-fg placeholder:text-fg-muted outline-none"
/>
<span className="hidden items-center gap-0.5 rounded bg-well px-1.5 py-0.5 font-mono-num text-[10px] text-fg-muted sm:inline-flex">
<CornerDownLeft className="h-2.5 w-2.5" />
<span>发送</span>
</span>
<button
type="button"
onClick={() => handleSend()}
disabled={!input.trim() || thinking}
className="ui-btn ui-btn-accent h-control-sm px-3.5 text-xs"
aria-label="发送"
>
<span>发送</span>
<Send className="h-3 w-3" />
</button>
</div>
</div>
</div>
);
}