feat: 第五轮开发 - 14项未来路线图功能完整实现

W1-W14 全部完成:
- W1: 消息搜索 (ILIKE全文检索 + SearchModal)
- W2: 对话导出 (JSON/Markdown/TXT三格式)
- W3: 记忆时间线 DevTools 可视化
- W4: 通知推送系统 (WebSocket + Browser Notification API)
- W5: 定时提醒 (30s轮询 + 重复提醒 + WebSocket推送)
- W6: 每日简报 (08:00自动生成: 天气+新闻+提醒+AI摘要)
- W7: IoT场景自动化 (规则引擎 10s轮询 + 条件评估 + 场景执行)
- W8: 语音输入 (浏览器 Speech Recognition API)
- W9: STT服务 (voice-service + whisper.cpp)
- W10: TTS服务 (浏览器 Speech Synthesis + edge-tts三档回退)
- W11: 文件管理 (上传/下载/缩略图/纯Go bilinear缩放)
- W12: 知识库RAG (PostgreSQL tsvector + 文档分块 + 检索)
- W13: 多模态 (图片上传+分析: Vision API + 本地Go分析回退)
- W14: PWA (Service Worker + 离线页 + install prompt)

总计: 6个Go微服务 + 10+前端组件 + 10+ PostgreSQL表 + 4个后台调度器
This commit is contained in:
2026-05-19 12:01:09 +08:00
parent 78e3f450c2
commit bcf4d4e621
69 changed files with 14599 additions and 150 deletions
+389 -61
View File
@@ -1,28 +1,111 @@
import { useState, useRef, useCallback } from 'react';
import type { ChatMode } from '@/types/chat';
import { useState, useRef, useCallback, useEffect } from 'react';
import type { ChatMode, MessageAttachment } from '@/types/chat';
import { useSpeechRecognition } from '@/hooks/useSpeechRecognition';
import { uploadFile } from '@/api/files';
interface ChatInputProps {
onSend: (content: string, mode: ChatMode) => void;
onSend: (content: string, mode: ChatMode, attachments?: MessageAttachment[]) => void;
disabled?: boolean;
}
interface PendingImage {
file: File;
previewUrl: string;
id: string; // 临时 ID
}
const MAX_IMAGE_SIZE = 10 * 1024 * 1024; // 10MB
const SUPPORTED_IMAGE_TYPES = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/bmp'];
const MAX_IMAGES = 5;
export function ChatInput({ onSend, disabled }: ChatInputProps) {
const [content, setContent] = useState('');
const [mode, setMode] = useState<ChatMode>('text');
const [pendingImages, setPendingImages] = useState<PendingImage[]>([]);
const [uploading, setUploading] = useState(false);
const [uploadError, setUploadError] = useState('');
const textareaRef = useRef<HTMLTextAreaElement>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const handleSend = useCallback(() => {
const {
isListening,
isSupported,
interimText,
finalText,
error,
startListening,
stopListening,
resetText,
} = useSpeechRecognition();
// 当 finalText 更新时,追加到输入框
useEffect(() => {
if (finalText) {
setContent((prev) => {
const trimmed = prev.trimEnd();
return (trimmed ? trimmed + ' ' : '') + finalText;
});
resetText();
}
}, [finalText, resetText]);
const handleSend = useCallback(async () => {
const trimmed = content.trim();
if (!trimmed || disabled) return;
const hasImages = pendingImages.length > 0;
if ((!trimmed && !hasImages) || disabled || uploading) return;
onSend(trimmed, mode);
let attachments: MessageAttachment[] | undefined;
if (hasImages) {
setUploading(true);
setUploadError('');
try {
const uploadedAttachments: MessageAttachment[] = [];
for (const img of pendingImages) {
try {
const result = await uploadFile(img.file);
uploadedAttachments.push({
type: 'image',
url: result.url,
thumbnail_url: result.thumbnail_url,
filename: result.filename,
size: result.size,
});
} catch (err) {
console.error('[ChatInput] 图片上传失败:', img.file.name, err);
// 使用 data URL 作为降级
uploadedAttachments.push({
type: 'image',
url: img.previewUrl,
filename: img.file.name,
size: img.file.size,
});
}
}
if (uploadedAttachments.length > 0) {
attachments = uploadedAttachments;
}
} catch (err) {
setUploadError('图片上传失败,请重试');
setUploading(false);
return;
}
setUploading(false);
}
onSend(trimmed, mode, attachments);
setContent('');
setPendingImages([]);
// 重置文本框高度
if (textareaRef.current) {
textareaRef.current.style.height = 'auto';
}
}, [content, mode, disabled, onSend]);
}, [content, mode, disabled, onSend, pendingImages, uploading]);
const handleKeyDown = useCallback(
(e: React.KeyboardEvent) => {
@@ -30,8 +113,92 @@ export function ChatInput({ onSend, disabled }: ChatInputProps) {
e.preventDefault();
handleSend();
}
// Ctrl+Shift+V 触发语音输入
if (e.key === 'V' && e.ctrlKey && e.shiftKey) {
e.preventDefault();
if (isListening) {
stopListening();
} else {
startListening();
}
}
},
[handleSend]
[handleSend, isListening, startListening, stopListening]
);
// 粘贴图片
const handlePaste = useCallback(
(e: React.ClipboardEvent) => {
const items = e.clipboardData?.items;
if (!items) return;
for (let i = 0; i < items.length; i++) {
const item = items[i];
if (item.type.startsWith('image/')) {
e.preventDefault();
const file = item.getAsFile();
if (file) {
addImageFile(file);
}
}
}
},
[]
);
// 添加图片文件
const addImageFile = useCallback(
(file: File) => {
setUploadError('');
// 检查文件大小
if (file.size > MAX_IMAGE_SIZE) {
setUploadError(`图片 "${file.name}" 超过 10MB 限制`);
return;
}
// 检查文件类型
if (!SUPPORTED_IMAGE_TYPES.includes(file.type)) {
setUploadError(`不支持的图片格式: ${file.type}`);
return;
}
// 检查数量限制
setPendingImages((prev) => {
if (prev.length >= MAX_IMAGES) {
setUploadError(`最多同时上传 ${MAX_IMAGES} 张图片`);
return prev;
}
const previewUrl = URL.createObjectURL(file);
return [...prev, { file, previewUrl, id: `img_${Date.now()}_${Math.random().toString(36).slice(2)}` }];
});
},
[]
);
// 移除待上传图片
const removeImage = useCallback((id: string) => {
setPendingImages((prev) => {
const img = prev.find((p) => p.id === id);
if (img) {
URL.revokeObjectURL(img.previewUrl);
}
return prev.filter((p) => p.id !== id);
});
}, []);
// 文件选择
const handleFileSelect = useCallback(
(e: React.ChangeEvent<HTMLInputElement>) => {
const files = e.target.files;
if (!files) return;
for (let i = 0; i < files.length; i++) {
addImageFile(files[i]);
}
// 重置 input 以便再次选择相同文件
e.target.value = '';
},
[addImageFile]
);
const handleInput = useCallback(() => {
@@ -42,70 +209,231 @@ export function ChatInput({ onSend, disabled }: ChatInputProps) {
}
}, []);
const handleVoiceToggle = useCallback(() => {
if (isListening) {
stopListening();
} else {
startListening();
}
}, [isListening, startListening, stopListening]);
return (
<div className="border-t border-pink-100 dark:border-pink-900 bg-white/80 dark:bg-gray-900/80 backdrop-blur-sm px-4 py-3">
<div className="flex items-end gap-2 max-w-3xl mx-auto">
{/* 模式切换 */}
<div className="flex gap-1">
<button
onClick={() => setMode('text')}
className={`p-2 rounded-lg text-xs transition-colors ${
mode === 'text'
? 'bg-pink-100 text-pink-600 dark:bg-pink-900 dark:text-pink-300'
: 'text-gray-400 hover:text-gray-600'
}`}
title="文字模式"
<div className="flex flex-col gap-2 max-w-3xl mx-auto">
{/* 实时识别文本提示 */}
{isListening && interimText && (
<div
className="interim-text text-sm text-pink-500 dark:text-pink-400 italic px-1"
aria-live="polite"
aria-atomic="true"
>
💬
{interimText}
</div>
)}
{/* 错误提示 */}
{error && (
<div
className="text-xs text-red-500 dark:text-red-400 px-1"
role="alert"
>
{error}
</div>
)}
{/* 上传错误提示 */}
{uploadError && (
<div
className="text-xs text-red-500 dark:text-red-400 px-1"
role="alert"
>
{uploadError}
</div>
)}
{/* 图片预览区 */}
{pendingImages.length > 0 && (
<div className="flex gap-2 flex-wrap px-1">
{pendingImages.map((img) => (
<div
key={img.id}
className="relative group w-16 h-16 rounded-lg overflow-hidden border border-pink-200 dark:border-pink-800 flex-shrink-0"
>
<img
src={img.previewUrl}
alt={img.file.name}
className="w-full h-full object-cover"
/>
{uploading && (
<div className="absolute inset-0 bg-black/40 flex items-center justify-center">
<svg className="animate-spin h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
</div>
)}
{!uploading && (
<button
onClick={() => removeImage(img.id)}
className="absolute top-0.5 right-0.5 w-5 h-5 rounded-full bg-black/50 text-white opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center"
aria-label="移除图片"
>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" className="w-3.5 h-3.5">
<path fillRule="evenodd" d="M5.47 5.47a.75.75 0 011.06 0L12 10.94l5.47-5.47a.75.75 0 111.06 1.06L13.06 12l5.47 5.47a.75.75 0 11-1.06 1.06L12 13.06l-5.47 5.47a.75.75 0 01-1.06-1.06L10.94 12 5.47 6.53a.75.75 0 010-1.06z" clipRule="evenodd" />
</svg>
</button>
)}
</div>
))}
</div>
)}
<div className="flex items-end gap-2">
{/* 模式切换 */}
<div className="flex gap-1">
<button
onClick={() => setMode('text')}
className={`p-2 rounded-lg text-xs transition-colors ${
mode === 'text'
? 'bg-pink-100 text-pink-600 dark:bg-pink-900 dark:text-pink-300'
: 'text-gray-400 hover:text-gray-600'
}`}
title="文字模式"
>
💬
</button>
<button
onClick={() => setMode('voice_msg')}
className={`p-2 rounded-lg text-xs transition-colors ${
mode === 'voice_msg'
? 'bg-pink-100 text-pink-600 dark:bg-pink-900 dark:text-pink-300'
: 'text-gray-400 hover:text-gray-600'
}`}
title="语音消息"
>
🎤
</button>
</div>
{/* 图片上传按钮 */}
<button
onClick={() => fileInputRef.current?.click()}
disabled={disabled || uploading}
className="p-2 rounded-lg text-xs transition-colors text-gray-400 hover:text-pink-500 hover:bg-pink-50 dark:hover:bg-pink-900/30 disabled:opacity-40 disabled:cursor-not-allowed"
title="上传图片"
aria-label="上传图片"
>
📷
</button>
<input
ref={fileInputRef}
type="file"
accept="image/jpeg,image/png,image/gif,image/webp,image/bmp"
multiple
onChange={handleFileSelect}
className="hidden"
aria-hidden="true"
/>
{/* 输入框 */}
<textarea
ref={textareaRef}
value={content}
onChange={(e) => setContent(e.target.value)}
onKeyDown={handleKeyDown}
onPaste={handlePaste}
onInput={handleInput}
placeholder="和昔涟说点什么吧... 支持粘贴图片"
disabled={disabled || uploading}
rows={1}
className="flex-1 resize-none rounded-xl border border-pink-200 dark:border-pink-800 bg-white dark:bg-gray-800 px-4 py-2 text-sm text-gray-700 dark:text-gray-200 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-pink-400 focus:border-transparent disabled:opacity-50"
/>
{/* 语音输入按钮 (仅浏览器支持时显示) */}
{isSupported && (
<button
onClick={handleVoiceToggle}
disabled={disabled || uploading}
aria-label={isListening ? '停止语音输入' : '开始语音输入'}
aria-pressed={isListening}
title={isListening ? '停止聆听 (Ctrl+Shift+V)' : '语音输入 (Ctrl+Shift+V)'}
className={`p-2 rounded-xl transition-all flex-shrink-0 border-2 ${
isListening
? 'voice-btn-active bg-red-500 border-red-500 text-white'
: 'bg-gray-100 dark:bg-gray-700 border-gray-200 dark:border-gray-600 text-gray-500 hover:text-red-500 hover:border-red-300'
} disabled:opacity-40 disabled:cursor-not-allowed`}
>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="currentColor"
className="w-5 h-5"
>
<path d="M12 2a3 3 0 0 0-3 3v6a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z" />
<path d="M7.5 11a4.5 4.5 0 0 0 9 0h1.5a6 6 0 0 1-5.25 5.95V20h3.75v1.5h-9v-1.5h3.75v-2.05A6 6 0 0 1 6 11h1.5Z" />
</svg>
</button>
)}
{/* 不支持时显示禁用按钮 */}
{!isSupported && (
<button
disabled
title="您的浏览器不支持语音识别"
className="p-2 rounded-xl bg-gray-100 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 text-gray-300 dark:text-gray-600 flex-shrink-0 cursor-not-allowed"
aria-label="语音输入不可用"
>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="currentColor"
className="w-5 h-5"
>
<path d="M12 2a3 3 0 0 0-3 3v6a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z" />
<path d="M7.5 11a4.5 4.5 0 0 0 9 0h1.5a6 6 0 0 1-5.25 5.95V20h3.75v1.5h-9v-1.5h3.75v-2.05A6 6 0 0 1 6 11h1.5Z" />
<line x1="4" y1="4" x2="20" y2="20" stroke="currentColor" strokeWidth="2" />
</svg>
</button>
)}
{/* 发送按钮 */}
<button
onClick={() => setMode('voice_msg')}
className={`p-2 rounded-lg text-xs transition-colors ${
mode === 'voice_msg'
? 'bg-pink-100 text-pink-600 dark:bg-pink-900 dark:text-pink-300'
: 'text-gray-400 hover:text-gray-600'
}`}
title="语音消息"
onClick={handleSend}
disabled={disabled || uploading || (!content.trim() && pendingImages.length === 0)}
className="p-2 rounded-xl bg-pink-400 text-white hover:bg-pink-500 disabled:opacity-40 disabled:cursor-not-allowed transition-colors flex-shrink-0"
>
🎤
{uploading ? (
<svg className="animate-spin h-5 w-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
) : (
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="currentColor"
className="w-5 h-5"
>
<path d="M3.478 2.404a.75.75 0 0 0-.926.941l2.432 7.905H13.5a.75.75 0 0 1 0 1.5H4.984l-2.432 7.905a.75.75 0 0 0 .926.94 60.519 60.519 0 0 0 18.445-8.986.75.75 0 0 0 0-1.218A60.517 60.517 0 0 0 3.478 2.404Z" />
</svg>
)}
</button>
</div>
{/* 输入框 */}
<textarea
ref={textareaRef}
value={content}
onChange={(e) => setContent(e.target.value)}
onKeyDown={handleKeyDown}
onInput={handleInput}
placeholder="和昔涟说点什么吧..."
disabled={disabled}
rows={1}
className="flex-1 resize-none rounded-xl border border-pink-200 dark:border-pink-800 bg-white dark:bg-gray-800 px-4 py-2 text-sm text-gray-700 dark:text-gray-200 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-pink-400 focus:border-transparent disabled:opacity-50"
/>
{/* 语音输入状态提示 */}
{isListening && (
<p className="text-xs text-red-400 text-center animate-pulse">
🎤 ...
<span className="text-gray-400 ml-2">(Ctrl+Shift+V )</span>
</p>
)}
{/* 发送按钮 */}
<button
onClick={handleSend}
disabled={disabled || !content.trim()}
className="p-2 rounded-xl bg-pink-400 text-white hover:bg-pink-500 disabled:opacity-40 disabled:cursor-not-allowed transition-colors flex-shrink-0"
>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="currentColor"
className="w-5 h-5"
>
<path d="M3.478 2.404a.75.75 0 0 0-.926.941l2.432 7.905H13.5a.75.75 0 0 1 0 1.5H4.984l-2.432 7.905a.75.75 0 0 0 .926.94 60.519 60.519 0 0 0 18.445-8.986.75.75 0 0 0 0-1.218A60.517 60.517 0 0 0 3.478 2.404Z" />
</svg>
</button>
{mode !== 'text' && !isListening && (
<p className="text-xs text-gray-400 text-center">
{mode === 'voice_msg' ? '语音消息功能即将上线 ♪' : ''}
</p>
)}
</div>
{mode !== 'text' && (
<p className="text-xs text-gray-400 text-center mt-2">
{mode === 'voice_msg' ? '语音消息功能即将上线 ♪' : ''}
</p>
)}
</div>
);
}
@@ -0,0 +1,216 @@
import { useEffect, useCallback, useRef, useState } from 'react';
import type { MessageAttachment } from '@/types/chat';
interface ImageLightboxProps {
attachments: MessageAttachment[];
currentIndex: number;
onClose: () => void;
}
export function ImageLightbox({ attachments, currentIndex, onClose }: ImageLightboxProps) {
const [index, setIndex] = useState(currentIndex);
const [imgLoaded, setImgLoaded] = useState(false);
const [imgError, setImgError] = useState(false);
const overlayRef = useRef<HTMLDivElement>(null);
const current = attachments[index];
const hasMultiple = attachments.length > 1;
// 键盘导航
const handleKeyDown = useCallback(
(e: KeyboardEvent) => {
switch (e.key) {
case 'Escape':
onClose();
break;
case 'ArrowLeft':
if (hasMultiple) {
setIndex((prev) => (prev - 1 + attachments.length) % attachments.length);
setImgLoaded(false);
setImgError(false);
}
break;
case 'ArrowRight':
if (hasMultiple) {
setIndex((prev) => (prev + 1) % attachments.length);
setImgLoaded(false);
setImgError(false);
}
break;
}
},
[onClose, hasMultiple, attachments.length]
);
useEffect(() => {
document.addEventListener('keydown', handleKeyDown);
document.body.style.overflow = 'hidden';
return () => {
document.removeEventListener('keydown', handleKeyDown);
document.body.style.overflow = '';
};
}, [handleKeyDown]);
// 点击背景关闭
const handleOverlayClick = useCallback(
(e: React.MouseEvent) => {
if (e.target === overlayRef.current) {
onClose();
}
},
[onClose]
);
// 下载当前图片
const handleDownload = useCallback(async () => {
if (!current?.url) return;
try {
const token = localStorage.getItem('token');
const resp = await fetch(current.url, {
headers: token ? { Authorization: `Bearer ${token}` } : {},
});
if (!resp.ok) throw new Error('Download failed');
const blob = await resp.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = current.filename || 'image';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
} catch (err) {
console.error('[ImageLightbox] 下载失败:', err);
// 降级:在新窗口打开
window.open(current.url, '_blank');
}
}, [current]);
if (!current) return null;
return (
<div
ref={overlayRef}
onClick={handleOverlayClick}
className="fixed inset-0 z-50 flex items-center justify-center bg-black/85 backdrop-blur-sm animate-fade-in"
role="dialog"
aria-modal="true"
aria-label="图片预览"
>
{/* 关闭按钮 */}
<button
onClick={onClose}
className="absolute top-4 right-4 z-10 p-2 rounded-full bg-white/10 hover:bg-white/20 text-white transition-colors"
aria-label="关闭"
>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" className="w-6 h-6">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
{/* 左箭头 */}
{hasMultiple && (
<button
onClick={() => {
setIndex((prev) => (prev - 1 + attachments.length) % attachments.length);
setImgLoaded(false);
setImgError(false);
}}
className="absolute left-4 top-1/2 -translate-y-1/2 z-10 p-3 rounded-full bg-white/10 hover:bg-white/20 text-white transition-colors"
aria-label="上一张"
>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" className="w-6 h-6">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
</svg>
</button>
)}
{/* 右箭头 */}
{hasMultiple && (
<button
onClick={() => {
setIndex((prev) => (prev + 1) % attachments.length);
setImgLoaded(false);
setImgError(false);
}}
className="absolute right-4 top-1/2 -translate-y-1/2 z-10 p-3 rounded-full bg-white/10 hover:bg-white/20 text-white transition-colors"
aria-label="下一张"
>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" className="w-6 h-6">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
</svg>
</button>
)}
{/* 图片容器 */}
<div className="flex flex-col items-center max-w-[90vw] max-h-[90vh] gap-4">
{/* 加载中状态 */}
{!imgLoaded && !imgError && (
<div className="flex items-center justify-center w-64 h-64 text-white/60">
<svg className="animate-spin h-10 w-10" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
</div>
)}
{/* 加载失败 */}
{imgError && (
<div className="flex flex-col items-center gap-2 text-white/60">
<span className="text-4xl">🖼</span>
<span className="text-sm"></span>
</div>
)}
{/* 图片 */}
<img
src={current.url}
alt={current.filename || '图片'}
className={`max-w-[85vw] max-h-[70vh] object-contain rounded-lg shadow-2xl ${imgLoaded ? 'block' : 'hidden'}`}
onLoad={() => setImgLoaded(true)}
onError={() => setImgError(true)}
/>
{/* 底部信息栏 */}
<div className="flex flex-col items-center gap-1 text-white/80 text-sm">
{/* 计数器 */}
{hasMultiple && (
<span className="text-white/50 text-xs">
{index + 1} / {attachments.length}
</span>
)}
{/* 文件名 */}
{current.filename && (
<span className="text-white/70 text-xs">{current.filename}</span>
)}
{/* 尺寸信息 */}
{current.width && current.height && (
<span className="text-white/50 text-xs">
{current.width} × {current.height}
</span>
)}
{/* AI 描述 */}
{current.description && (
<p className="text-white/80 text-xs text-center max-w-lg mt-1 px-4">
{current.description}
</p>
)}
{/* 下载按钮 */}
<button
onClick={handleDownload}
className="mt-2 inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-white/10 hover:bg-white/20 text-white text-xs transition-colors"
>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" className="w-4 h-4">
<path fillRule="evenodd" d="M12 2.25a.75.75 0 01.75.75v11.69l3.22-3.22a.75.75 0 111.06 1.06l-4.5 4.5a.75.75 0 01-1.06 0l-4.5-4.5a.75.75 0 111.06-1.06l3.22 3.22V3a.75.75 0 01.75-.75zm-9 13.5a.75.75 0 01.75.75v2.25a1.5 1.5 0 001.5 1.5h13.5a1.5 1.5 0 001.5-1.5V16.5a.75.75 0 011.5 0v2.25a3 3 0 01-3 3H5.25a3 3 0 01-3-3V16.5a.75.75 0 01.75-.75z" clipRule="evenodd" />
</svg>
</button>
</div>
</div>
</div>
);
}
@@ -1,12 +1,16 @@
import { useState, useEffect, useRef } from 'react';
import { useState, useEffect, useRef, useCallback } from 'react';
import { CyreneAvatar } from '@/components/persona/CyreneAvatar';
import { useAuthStore } from '@/store/authStore';
import { useSpeechSynthesis } from '@/hooks/useSpeechSynthesis';
import type { MessageAttachment } from '@/types/chat';
import { ImageLightbox } from './ImageLightbox';
interface MessageBubbleProps {
role: 'user' | 'assistant' | 'system';
content: string;
timestamp: number;
isStreaming?: boolean;
attachments?: MessageAttachment[];
}
/**
@@ -72,8 +76,70 @@ function useTypewriter(content: string, isStreaming: boolean): string {
return displayed;
}
export function MessageBubble({ role, content, timestamp, isStreaming }: MessageBubbleProps) {
/**
* AI 消息的操作栏 — 包含 TTS 朗读按钮
*/
function AIMessageActions({ content }: { content: string }) {
const { isSpeaking, isSupported, speak, stop } = useSpeechSynthesis();
const [isThisSpeaking, setIsThisSpeaking] = useState(false);
const contentRef = useRef(content);
// 当全局 TTS 正在朗读且对应的是本条消息时,设置 isThisSpeaking
useEffect(() => {
if (!isSpeaking) {
setIsThisSpeaking(false);
}
}, [isSpeaking]);
const handleToggleTTS = useCallback(() => {
if (isThisSpeaking) {
stop();
setIsThisSpeaking(false);
} else {
setIsThisSpeaking(true);
speak(content, { lang: 'zh-CN' });
// 朗读结束后重置
const checkEnd = setInterval(() => {
if (!window.speechSynthesis.speaking) {
setIsThisSpeaking(false);
clearInterval(checkEnd);
}
}, 200);
}
}, [content, isThisSpeaking, speak, stop]);
if (!isSupported) return null;
return (
<div className="flex items-center gap-1 mt-1.5">
<button
onClick={handleToggleTTS}
className={`inline-flex items-center gap-1 text-xs px-2 py-1 rounded-full transition-all duration-200 ${
isThisSpeaking
? 'bg-pink-100 text-pink-600 tts-playing'
: 'text-gray-400 hover:text-pink-500 hover:bg-pink-50'
}`}
title={isThisSpeaking ? '停止朗读' : '朗读此消息'}
>
{isThisSpeaking ? (
<>
<span className="text-sm"></span>
<span></span>
</>
) : (
<>
<span className="text-sm">🔊</span>
<span></span>
</>
)}
</button>
</div>
);
}
export function MessageBubble({ role, content, timestamp, isStreaming, attachments }: MessageBubbleProps) {
const isUser = role === 'user';
const [lightboxIndex, setLightboxIndex] = useState<number | null>(null);
const time = new Date(timestamp).toLocaleTimeString('zh-CN', {
hour: '2-digit',
minute: '2-digit',
@@ -84,6 +150,9 @@ export function MessageBubble({ role, content, timestamp, isStreaming }: Message
// 判断是否还有未显示完的字符
const hasMoreChars = isStreaming && displayedContent.length < content.length;
// 图片附件
const imageAttachments = attachments?.filter((a) => a.type === 'image') ?? [];
return (
<div className={`flex px-4 py-2 gap-3 ${isUser ? 'flex-row-reverse' : ''}`}>
{/* 头像 */}
@@ -110,23 +179,114 @@ export function MessageBubble({ role, content, timestamp, isStreaming }: Message
<span className="animate-streaming-cursor" />
)}
</p>
{!isStreaming && (
<p
className={`text-xs mt-1 ${
isUser ? 'text-pink-100' : 'text-gray-400'
{/* 图片附件网格 */}
{!isStreaming && imageAttachments.length > 0 && (
<div
className={`grid gap-1.5 mt-2 ${
imageAttachments.length === 1
? 'grid-cols-1'
: imageAttachments.length === 2
? 'grid-cols-2'
: 'grid-cols-3'
}`}
>
{time}
</p>
{imageAttachments.map((att, idx) => (
<ImageThumbnail
key={idx}
attachment={att}
onClick={() => setLightboxIndex(idx)}
/>
))}
</div>
)}
{!isStreaming && (
<>
{/* AI 消息操作栏(朗读按钮) */}
{!isUser && <AIMessageActions content={content} />}
<p
className={`text-xs mt-1 ${
isUser ? 'text-pink-100' : 'text-gray-400'
}`}
>
{time}
</p>
</>
)}
</div>
{/* 用户头像 */}
{isUser && <UserAvatar />}
{/* Lightbox */}
{lightboxIndex !== null && (
<ImageLightbox
attachments={imageAttachments}
currentIndex={lightboxIndex}
onClose={() => setLightboxIndex(null)}
/>
)}
</div>
);
}
/** 图片缩略图组件 */
function ImageThumbnail({
attachment,
onClick,
}: {
attachment: MessageAttachment;
onClick: () => void;
}) {
const [loaded, setLoaded] = useState(false);
const [error, setError] = useState(false);
const url = attachment.thumbnail_url || attachment.url;
return (
<button
onClick={onClick}
className="relative w-full aspect-square rounded-lg overflow-hidden border border-pink-100 dark:border-pink-800 bg-gray-100 dark:bg-gray-700 hover:ring-2 hover:ring-pink-400 transition-all cursor-pointer group"
aria-label={`查看图片: ${attachment.filename || '未命名图片'}`}
>
{/* 加载中 */}
{!loaded && !error && (
<div className="absolute inset-0 flex items-center justify-center text-gray-400">
<svg className="animate-spin h-5 w-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
</div>
)}
{/* 加载失败 */}
{error && (
<div className="absolute inset-0 flex items-center justify-center text-gray-400">
<span className="text-2xl">🖼</span>
</div>
)}
{/* 图片 */}
<img
src={url}
alt={attachment.filename || '图片'}
className={`w-full h-full object-cover transition-transform group-hover:scale-105 ${loaded ? 'block' : 'hidden'}`}
onLoad={() => setLoaded(true)}
onError={() => setError(true)}
/>
{/* 悬停遮罩 */}
{loaded && (
<div className="absolute inset-0 bg-black/0 group-hover:bg-black/20 transition-colors flex items-center justify-center">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" className="w-6 h-6 text-white opacity-0 group-hover:opacity-100 transition-opacity">
<path fillRule="evenodd" d="M15 3.75a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0V5.56l-3.97 3.97a.75.75 0 11-1.06-1.06l3.97-3.97h-3.69a.75.75 0 010-1.5h4.5zM5.25 6.75a3 3 0 00-3 3v7.5a3 3 0 003 3h13.5a3 3 0 003-3v-7.5a3 3 0 00-3-3H15a.75.75 0 000 1.5h3.75a1.5 1.5 0 011.5 1.5v7.5a1.5 1.5 0 01-1.5 1.5H5.25a1.5 1.5 0 01-1.5-1.5v-7.5a1.5 1.5 0 011.5-1.5H9a.75.75 0 000-1.5H5.25z" clipRule="evenodd" />
</svg>
</div>
)}
</button>
);
}
/** 用户头像组件:管理员使用 Admin_Avatar.jpg,普通用户使用 Default_Avatar.png */
function UserAvatar() {
const [imgError, setImgError] = useState(false);
@@ -39,6 +39,7 @@ export function MessageList({ messages, isTyping }: MessageListProps) {
content={msg.content}
timestamp={msg.timestamp}
isStreaming={msg.isStreaming}
attachments={msg.attachments}
/>
))}
{isTyping && !messages.some((m) => m.isStreaming) && <TypingIndicator />}