跳至正文
获取 Pro
AI 代理A.07

流式输出块

FreeRegistry
components/linyi/streaming-response.tsx
lucide-react
"use client";
 
import * as React from "react";
import { AlertCircle, Check, Copy, RotateCw, Square } from "lucide-react";
import { cn } from "@/lib/cn";
 
export type StreamingStatus = "idle" | "streaming" | "done" | "error";
 
export interface StreamingResponseProps {
text: string;
status?: StreamingStatus;
errorMessage?: string;
speedMs?: number;
chunkSize?: number;
autoStart?: boolean;
compact?: boolean;
onStop?: () => void;
onRetry?: () => void;
onCopy?: (text: string) => void;
onComplete?: () => void;
className?: string;
}
 
export function StreamingResponse({
text,
status: controlledStatus,
errorMessage,
speedMs = 38,
chunkSize = 2,
autoStart = false,
compact = false,
onStop,
onRetry,
onCopy,
onComplete,
className,
}: StreamingResponseProps) {
const isControlled = controlledStatus !== undefined;
const [length, setLength] = React.useState(autoStart && !isControlled ? 0 : text.length);
const [internalStreaming, setInternalStreaming] = React.useState(autoStart && !isControlled);
const [stopped, setStopped] = React.useState(false);
const [copied, setCopied] = React.useState(false);
 
const intervalRef = React.useRef<number | null>(null);
const copyTimerRef = React.useRef<number | null>(null);
const onCompleteRef = React.useRef(onComplete);
onCompleteRef.current = onComplete;
 
const clearStreamTimer = React.useCallback(() => {
if (intervalRef.current !== null) {
window.clearInterval(intervalRef.current);
intervalRef.current = null;
}
}, []);
 
const startStream = React.useCallback(() => {
if (isControlled) {
onRetry?.();
return;
}
clearStreamTimer();
const reduced = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? false;
if (reduced) {
setLength(text.length);
setInternalStreaming(false);
setStopped(false);
onCompleteRef.current?.();
return;
}
 
setStopped(false);
setInternalStreaming(true);
setLength(Math.min(chunkSize, text.length));
 
let current = Math.min(chunkSize, text.length);
intervalRef.current = window.setInterval(() => {
current += chunkSize;
if (current >= text.length) {
setLength(text.length);
setInternalStreaming(false);
clearStreamTimer();
onCompleteRef.current?.();
} else {
setLength(current);
}
}, speedMs);
}, [isControlled, onRetry, text, speedMs, chunkSize, clearStreamTimer]);
 
const stopStream = React.useCallback(() => {
clearStreamTimer();
setInternalStreaming(false);
setStopped(true);
onStop?.();
}, [clearStreamTimer, onStop]);
 
React.useEffect(() => {
if (isControlled) {
clearStreamTimer();
setLength(text.length);
return;
}
if (autoStart) {
startStream();
} else {
clearStreamTimer();
setLength(text.length);
setInternalStreaming(false);
setStopped(false);
}
return () => {
clearStreamTimer();
if (copyTimerRef.current !== null) window.clearTimeout(copyTimerRef.current);
};
}, [isControlled, autoStart, text, startStream, clearStreamTimer]);
 
const status: StreamingStatus =
controlledStatus ?? (internalStreaming ? "streaming" : "done");
const streaming = status === "streaming";
const isError = status === "error";
const isIdle = status === "idle";
const visibleText = isControlled ? text : text.slice(0, length);
const shownLength = visibleText.length;
 
const handleCopy = async () => {
try {
await navigator.clipboard?.writeText(visibleText);
} catch {
// Ignore clipboard permission errors in restricted sandboxes
}
onCopy?.(visibleText);
setCopied(true);
if (copyTimerRef.current !== null) window.clearTimeout(copyTimerRef.current);
copyTimerRef.current = window.setTimeout(() => setCopied(false), 1400);
};
 
const statusLabel = isError
? "生成异常"
: isIdle
? "等待输入"
: streaming
? "生成中"
: stopped
? "已停止"
: "完成";
 
return (
<div
data-status={status}
className={cn(
"w-full rounded-[14px] bg-surface border shadow-panel flex flex-col",
isError ? "border-danger-border" : "border-line",
compact ? "p-3 gap-2.5" : "p-4 gap-3",
className
)}
>
<div
aria-live="polite"
className={cn(
"text-fg leading-relaxed whitespace-pre-wrap break-words",
compact ? "text-xs min-h-[38px]" : "text-[13px] min-h-[58px]"
)}
>
{isError ? (
<div role="alert" className="flex items-start gap-2 text-danger">
<AlertCircle className="h-4 w-4 mt-0.5 flex-shrink-0" aria-hidden="true" />
<span>{errorMessage ?? (visibleText || "流式响应中断,请点击重新生成重试。")}</span>
</div>
) : isIdle && !visibleText ? (
<span className="text-fg-muted">等待模型返回内容...</span>
) : (
<>
<span>{visibleText}</span>
{streaming && (
<span
aria-hidden="true"
className="inline-block w-[6px] h-[14px] ml-0.5 align-middle rounded-[1px] bg-accent animate-pulse"
/>
)}
</>
)}
</div>
 
<div className="flex items-center justify-between gap-2 pt-2 border-t border-line">
<div className="flex items-center gap-1.5">
{streaming ? (
<button
type="button"
onClick={stopStream}
className="inline-flex items-center gap-1 h-7 px-2.5 rounded-pill bg-danger-soft text-danger border border-danger-border text-[11px] font-medium cursor-pointer transition-colors hover:opacity-90"
>
<Square className="w-2.5 h-2.5 fill-current" aria-hidden="true" />
<span>停止</span>
</button>
) : (
<button
type="button"
onClick={startStream}
className="inline-flex items-center gap-1 h-7 px-2.5 rounded-pill bg-well hover:bg-well/80 border border-line text-[11px] text-fg-secondary hover:text-fg cursor-pointer transition-colors"
>
<RotateCw className="w-3 h-3" aria-hidden="true" />
<span>{isError ? "重试" : "重新生成"}</span>
</button>
)}
 
{!compact && visibleText && !isError && (
<button
type="button"
onClick={handleCopy}
className="inline-flex items-center gap-1 h-7 px-2.5 rounded-pill bg-transparent hover:bg-well border border-line text-[11px] text-fg-secondary hover:text-fg cursor-pointer transition-colors"
>
{copied ? (
<Check className="w-3 h-3 text-success" aria-hidden="true" />
) : (
<Copy className="w-3 h-3" aria-hidden="true" />
)}
<span>{copied ? "已复制" : "复制文本"}</span>
</button>
)}
</div>
 
<span className="font-mono-num text-[10px] text-fg-muted">
{statusLabel} · {shownLength}/{text.length}
</span>
</div>
</div>
);
}