update loyout

This commit is contained in:
hobby
2025-03-25 08:25:40 +08:00
parent 6c495ac631
commit 487621a645
19 changed files with 229 additions and 100 deletions

View File

@@ -0,0 +1,237 @@
import React, { useState } from 'react';
import { cn } from '@/lib/utils';
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
interface AdSectionProps {
isOpen: boolean;
closeAd?: () => void;
}
interface AdBannerProps {
show: boolean;
closeAd: () => void;
}
const AdSection: React.FC<AdSectionProps> = ({ isOpen}) => {
const [isMobile, setIsMobile] = useState(false);
React.useEffect(() => {
const checkDevice = () => {
setIsMobile(window.innerWidth <= 768);
};
checkDevice();
window.addEventListener('resize', checkDevice);
return () => window.removeEventListener('resize', checkDevice);
}, []);
return (
<div className="p-3 border-t border-border/40">
<div className={cn(
"rounded-lg p-2 text-center relative overflow-hidden min-h-[120px] flex flex-col justify-center",
"transition-all duration-200 bg-cover bg-center bg-no-repeat",
isOpen ? "block" : "hidden"
)}
style={{
backgroundImage: "url('https://files.monica.cn/assets/botgroup/background.png')",
}}
>
<div className="absolute top-0 left-0 bg-gray-300/40 text-gray-400 text-[10px] px-1.5 py-0.5 rounded">
广
</div>
<div className="relative z-10">
<div className="flex flex-col items-center gap-2">
<div className="flex items-center justify-center px-6">
<img src="https://files.monica.cn/assets/botgroup/monica.png"/>
</div>
<div className="text-sm font-medium text-center text-gray-400">, </div>
<div className="text-[10px] font-medium text-center text-gray-400 flex items-center justify-center gap-1"> <img src="https://files.monica.cn/assets/botgroup/deepseek.png" className="inline-block w-16"/> </div>
<div className="flex flex-col items-center justify-center gap-2 mt-3">
{isMobile ? (
<button onClick={() => {
window.open('https://mp.weixin.qq.com/s/9l9zz_8wXOmxkKIVd0j9Nw', '_blank');
}} className="p-1 bg-white rounded-full text-xs font-medium text-blue-500 font-bold hover:bg-gray-50 transition-colors shadow-sm flex items-center gap-1 group">
<img src="https://files.monica.cn/assets/botgroup/wechat.png" className="w-4 h-4" alt="WeChat" />
使
<img src="https://files.monica.cn/assets/botgroup/arrow-up.png" className="w-4 h-4" alt="WeChat" />
</button> ) :
(
<Popover>
<PopoverTrigger asChild>
<button className="p-2 bg-white rounded-full text-xs font-medium text-blue-500 font-bold hover:bg-gray-50 transition-colors shadow-sm flex items-center gap-1 group">
<img src="https://files.monica.cn/assets/botgroup/wechat.png" className="w-4 h-4" alt="WeChat" />
使
<img src="https://files.monica.cn/assets/botgroup/arrow-up.png" className="w-4 h-4" alt="WeChat" />
</button>
</PopoverTrigger>
<PopoverContent className="w-40 p-0" side="top" align="center" sideOffset={5} onPointerDownOutside={(e) => e.preventDefault()}>
<div className="flex flex-col items-center">
<img
src="https://assets.monica.cn/home-web/_next/static/media/wechatQrcode.29848e06.png"
alt="公众号二维码"
className="w-40 h-40"
/>
</div>
</PopoverContent>
</Popover>)
}
{isMobile ? (
<button
onClick={() => {
window.open('https://app.adjust.com/1mh0qgab?fallback=https%3A%2F%2Fmonica.cn%2Fapp-download&redirect_macos=https%3A%2F%2Fmonica.cn%2Fapp-download', '_blank');
}}
className="p-2 bg-white rounded-full text-xs font-medium text-blue-500 font-bold hover:bg-gray-50 transition-colors shadow-sm flex items-center gap-1"
>
<img src="https://files.monica.cn/assets/botgroup/mobile-banner-mobile.png" className="w-4 h-4" alt="Mobile" />
APP
<img src="https://files.monica.cn/assets/botgroup/arrow-up.png" className="w-4 h-4" alt="Arrow" />
</button>
) : (
<button
onClick={() => {
window.open('https://monica.cn/home/chat/Monica/monica', '_blank');
}}
className="p-2 bg-white rounded-full text-xs font-medium text-blue-500 font-bold hover:bg-gray-50 transition-colors shadow-sm flex items-center gap-1"
>
<img src="https://files.monica.cn/assets/botgroup/computer.png" className="w-4 h-4" alt="Computer" />
<img src="https://files.monica.cn/assets/botgroup/arrow-up.png" className="w-4 h-4" alt="Arrow" />
</button>
)}
</div>
</div>
</div>
</div>
</div>
);
};
const AdBanner: React.FC<AdBannerProps> = ({ show, closeAd }) => {
if (!show) return null;
return (
<div className="rounded-lg text-center relative overflow-hidden py-2 pl-1 h-8 mr-2 flex flex-col justify-center transition-all duration-200 bg-cover bg-center bg-no-repeat"
style={{
backgroundImage: "url('https://files.monica.cn/assets/botgroup/banner-background.png')"
}}>
<div className="absolute top-0 left-0 bg-gray-300/40 text-gray-400 text-[8px] px-1 py-1.5 rounded">
广<br/>
</div>
<div className="relative z-10">
<div className="flex items-center gap-0 justify-center">
<div className="flex items-center justify-center w-20 pl-2">
<img src="https://files.monica.cn/assets/botgroup/monica.png"/>
</div>
<div className="flex items-center justify-between gap-3 px-2 flex-1">
<div className="flex items-center gap-3">
<Popover>
<PopoverTrigger asChild>
<button className="p-1 bg-white rounded-full text-xs font-medium text-blue-500 font-bold hover:bg-gray-50 transition-colors shadow-sm flex items-center gap-1 group">
<img src="https://files.monica.cn/assets/botgroup/wechat.png" className="w-4 h-4" alt="WeChat" />
使
<img src="https://files.monica.cn/assets/botgroup/arrow-up.png" className="w-4 h-4" alt="WeChat" />
</button>
</PopoverTrigger>
<PopoverContent className="w-40 p-0" side="top" align="center" sideOffset={5} onPointerDownOutside={(e) => e.preventDefault()}>
<div className="flex flex-col items-center">
<img
src="https://assets.monica.cn/home-web/_next/static/media/wechatQrcode.29848e06.png"
alt="公众号二维码"
className="w-40 h-40"
/>
</div>
</PopoverContent>
</Popover>
<button
onClick={() => {
window.open('https://monica.cn/home/chat/Monica/monica', '_blank');
}}
className="p-1 bg-white rounded-full text-xs font-medium text-blue-500 font-bold hover:bg-gray-50 transition-colors shadow-sm flex items-center gap-1"
>
<img src="https://files.monica.cn/assets/botgroup/computer.png" className="w-4 h-4" alt="Computer" />
<img src="https://files.monica.cn/assets/botgroup/arrow-up.png" className="w-4 h-4" alt="Arrow" />
</button>
</div>
<button onClick={closeAd} className="flex items-center">
<img src="https://files.monica.cn/assets/botgroup/banner-delete.png" className="w-4 h-4" alt="Delete" />
</button>
</div>
</div>
</div>
</div>
);
};
const AdBannerMobile: React.FC<AdBannerProps> = ({ show, closeAd }) => {
const [isMobile, setIsMobile] = useState(false);
React.useEffect(() => {
const checkDevice = () => {
setIsMobile(window.innerWidth <= 768);
};
checkDevice();
window.addEventListener('resize', checkDevice);
return () => window.removeEventListener('resize', checkDevice);
}, []);
if (!show) return null;
return (
<div className="w-full relative overflow-hidden py-2 pl-2 h-8 flex flex-col justify-center transition-all duration-200 bg-cover bg-center bg-no-repeat"
style={{
backgroundImage: "url('https://files.monica.cn/assets/botgroup/mobile-banner-background.png')"
}}>
<div className="absolute top-0 left-0 bg-gray-300/40 text-gray-400 text-[8px] px-1 py-1.5">
广<br/>
</div>
<div className="relative z-10">
<div className="flex items-center gap-1 justify-center">
<div className="flex items-center justify-center w-20 pl-2">
<img src="https://files.monica.cn/assets/botgroup/monica.png"/>
</div>
<div className="flex items-center justify-between gap-3 px-2 flex-1">
<div className="flex items-center gap-3">
<button onClick={() => {
window.open('https://mp.weixin.qq.com/s/9l9zz_8wXOmxkKIVd0j9Nw', '_blank');
}} className="p-1 bg-white rounded-full text-xs font-medium text-blue-500 font-bold hover:bg-gray-50 transition-colors shadow-sm flex items-center gap-1 group">
<img src="https://files.monica.cn/assets/botgroup/wechat.png" className="w-4 h-4" alt="WeChat" />
使
<img src="https://files.monica.cn/assets/botgroup/arrow-up.png" className="w-4 h-4" alt="WeChat" />
</button>
<button
onClick={() => {
window.open('https://app.adjust.com/1mh0qgab?fallback=https%3A%2F%2Fmonica.cn%2Fapp-download&redirect_macos=https%3A%2F%2Fmonica.cn%2Fapp-download', '_blank');
}}
className="p-1 bg-white rounded-full text-xs font-medium text-blue-500 font-bold hover:bg-gray-50 transition-colors shadow-sm flex items-center gap-1"
>
<img src="https://files.monica.cn/assets/botgroup/mobile-banner-mobile.png" className="w-4 h-4" alt="Mobile" />
APP
<img src="https://files.monica.cn/assets/botgroup/arrow-up.png" className="w-4 h-4" alt="Arrow" />
</button>
</div>
<button onClick={closeAd} className="flex items-center">
<img src="https://files.monica.cn/assets/botgroup/banner-delete.png" className="w-4 h-4" alt="Delete" />
</button>
</div>
</div>
</div>
</div>
);
};
export { AdSection, AdBanner, AdBannerMobile };

View File

@@ -0,0 +1,733 @@
import React, { useState, useRef, useEffect } from 'react';
import { Send, Share2, Settings2, ChevronLeft } from 'lucide-react';
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger
} from "@/components/ui/tooltip";
import type { AICharacter } from "@/config/aiCharacters";
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm'
import remarkMath from 'remark-math'
import rehypeKatex from 'rehype-katex'
import { SharePoster } from '@/pages/chat/components/SharePoster';
import { MembersManagement } from '@/pages/chat/components/MembersManagement';
import Sidebar from './Sidebar';
import { AdBanner, AdBannerMobile } from './AdSection';
// 使用本地头像数据,避免外部依赖
const getAvatarData = (name: string) => {
const colors = ['#1abc9c', '#3498db', '#9b59b6', '#f1c40f', '#e67e22'];
const index = (name.charCodeAt(0) + (name.charCodeAt(1) || 0 )) % colors.length;
return {
backgroundColor: colors[index],
text: name[0],
};
};
// 单个完整头像
const SingleAvatar = ({ user }: { user: User | AICharacter }) => {
// 如果有头像就使用头像,否则使用默认的文字头像
if ('avatar' in user && user.avatar) {
return (
<div className="w-full h-full">
<img src={user.avatar} alt={user.name} className="w-full h-full object-cover" />
</div>
);
}
const avatarData = getAvatarData(user.name);
return (
<div
className="w-full h-full flex items-center justify-center text-xs text-white font-medium"
style={{ backgroundColor: avatarData.backgroundColor }}
>
{avatarData.text}
</div>
);
};
// 左右分半头像
const HalfAvatar = ({ user, isFirst }: { user: User, isFirst: boolean }) => {
if ('avatar' in user && user.avatar) {
return (
<div
className="w-1/2 h-full"
style={{
borderRight: isFirst ? '1px solid white' : 'none'
}}
>
<img src={user.avatar} alt={user.name} className="w-full h-full object-cover" />
</div>
);
}
const avatarData = getAvatarData(user.name);
return (
<div
className="w-1/2 h-full flex items-center justify-center text-xs text-white font-medium"
style={{
backgroundColor: avatarData.backgroundColor,
borderRight: isFirst ? '1px solid white' : 'none'
}}
>
{avatarData.text}
</div>
);
};
// 四分之一头像
const QuarterAvatar = ({ user, index }: { user: User, index: number }) => {
if ('avatar' in user && user.avatar) {
return (
<div
className="aspect-square"
style={{
borderRight: index % 2 === 0 ? '1px solid white' : 'none',
borderBottom: index < 2 ? '1px solid white' : 'none'
}}
>
<img src={user.avatar} alt={user.name} className="w-full h-full object-cover" />
</div>
);
}
const avatarData = getAvatarData(user.name);
return (
<div
className="aspect-square flex items-center justify-center text-[8px] text-white font-medium"
style={{
backgroundColor: avatarData.backgroundColor,
borderRight: index % 2 === 0 ? '1px solid white' : 'none',
borderBottom: index < 2 ? '1px solid white' : 'none'
}}
>
{avatarData.text}
</div>
);
};
// 修改 KaTeXStyle 组件
const KaTeXStyle = () => (
<style dangerouslySetInnerHTML={{ __html: `
/* 只在聊天消息内应用 KaTeX 样式 */
.chat-message .katex-html {
display: none;
}
.chat-message .katex {
font: normal 1.1em KaTeX_Main, Times New Roman, serif;
line-height: 1.2;
text-indent: 0;
white-space: nowrap;
text-rendering: auto;
}
.chat-message .katex-display {
display: block;
margin: 1em 0;
text-align: center;
}
/* 其他必要的 KaTeX 样式 */
@import "katex/dist/katex.min.css";
`}} />
);
// Vite环境变量访问方式
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || '';
const ChatUI = () => {
//获取url参数
const urlParams = new URLSearchParams(window.location.search);
const id = urlParams.get('id')? parseInt(urlParams.get('id')!) : 0;
// 1. 所有的 useState 声明
const [groups, setGroups] = useState([]);
const [selectedGroupIndex, setSelectedGroupIndex] = useState(id);
const [group, setGroup] = useState(null);
const [groupAiCharacters, setGroupAiCharacters] = useState([]);
const [isLoading, setIsLoading] = useState(false);
const [isInitializing, setIsInitializing] = useState(false);
const [isGroupDiscussionMode, setIsGroupDiscussionMode] = useState(false);
const [users, setUsers] = useState([]);
const [allNames, setAllNames] = useState([]);
const [showMembers, setShowMembers] = useState(false);
const [messages, setMessages] = useState([]);
const [showAd, setShowAd] = useState(true);
const [inputMessage, setInputMessage] = useState("");
const [pendingContent, setPendingContent] = useState("");
const [isTyping, setIsTyping] = useState(false);
const [mutedUsers, setMutedUsers] = useState<string[]>([]);
const [showPoster, setShowPoster] = useState(false);
const [sidebarOpen, setSidebarOpen] = useState(false);
// 2. 所有的 useRef 声明
const currentMessageRef = useRef<number | null>(null);
const typewriterRef = useRef<NodeJS.Timeout | null>(null);
const accumulatedContentRef = useRef("");
const messagesEndRef = useRef<HTMLDivElement>(null);
const chatAreaRef = useRef<HTMLDivElement>(null);
const abortController = useRef(new AbortController());
// 添加一个 ref 来跟踪是否已经初始化
const isInitialized = useRef(false);
// 3. 所有的 useEffect
useEffect(() => {
// 如果已经初始化过,则直接返回
if (isInitialized.current) return;
const initData = async () => {
try {
const response = await fetch(`${API_BASE_URL}/api/init`);
if (!response.ok) {
throw new Error('初始化数据失败');
}
const {data} = await response.json();
console.log("初始化数据", data);
const group = data.groups[selectedGroupIndex];
const characters = data.characters;
setGroups(data.groups);
setGroup(group);
setIsInitializing(false);
setIsGroupDiscussionMode(group.isGroupDiscussionMode);
const groupAiCharacters = characters
.filter(character => group.members.includes(character.id))
.filter(character => character.personality !== "sheduler")
.sort((a, b) => {
return group.members.indexOf(a.id) - group.members.indexOf(b.id);
});
setGroupAiCharacters(groupAiCharacters);
const allNames = groupAiCharacters.map(character => character.name);
allNames.push('user');
setAllNames(allNames);
setUsers([
{ id: 1, name: "我" },
...groupAiCharacters
]);
} catch (error) {
console.error("初始化数据失败:", error);
setIsInitializing(false);
}
};
initData();
// 标记为已初始化
isInitialized.current = true;
}, []); // 依赖数组保持为空
useEffect(() => {
scrollToBottom();
}, [messages]);
useEffect(() => {
if (messages.length > 0) {
setShowAd(false);
}
}, [messages]);
useEffect(() => {
return () => {
if (typewriterRef.current) {
clearInterval(typewriterRef.current);
}
};
}, []);
// 4. 工具函数
const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
};
const handleRemoveUser = (userId: number) => {
setUsers(users.filter(user => user.id !== userId));
};
const handleToggleMute = (userId: string) => {
setMutedUsers(prev =>
prev.includes(userId)
? prev.filter(id => id !== userId)
: [...prev, userId]
);
};
const handleShareChat = () => {
setShowPoster(true);
};
const toggleSidebar = () => {
setSidebarOpen(!sidebarOpen);
};
// 5. 加载检查
if (isInitializing || !group) {
return (
<div className="fixed inset-0 bg-gradient-to-br from-orange-50 via-orange-50/70 to-orange-100 flex items-center justify-center">
<div className="w-8 h-8 animate-spin rounded-full border-4 border-orange-500 border-t-transparent"></div>
</div>
);
}
const handleSendMessage = async () => {
//判断是否Loding
if (isLoading) return;
if (!inputMessage.trim()) return;
// 添加用户消息
const userMessage = {
id: messages.length + 1,
sender: users[0],
content: inputMessage,
isAI: false
};
setMessages(prev => [...prev, userMessage]);
setInputMessage("");
setIsLoading(true);
setPendingContent("");
accumulatedContentRef.current = "";
// 构建历史消息数组
let messageHistory = messages.map(msg => ({
role: 'user',
content: msg.sender.name == "我" ? 'user' + msg.content : msg.sender.name + '' + msg.content,
name: msg.sender.name
}));
let selectedGroupAiCharacters = groupAiCharacters;
if (!isGroupDiscussionMode) {
const shedulerResponse = await fetch(`${API_BASE_URL}/api/scheduler`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ message: inputMessage, history: messageHistory, availableAIs: groupAiCharacters })
});
const shedulerData = await shedulerResponse.json();
const selectedAIs = shedulerData.selectedAIs;
selectedGroupAiCharacters = selectedAIs.map(ai => groupAiCharacters.find(c => c.id === ai));
}
for (let i = 0; i < selectedGroupAiCharacters.length; i++) {
//禁言
if (mutedUsers.includes(selectedGroupAiCharacters[i].id)) {
continue;
}
// 创建当前 AI 角色的消息
const aiMessage = {
id: messages.length + 2 + i,
sender: { id: selectedGroupAiCharacters[i].id, name: selectedGroupAiCharacters[i].name, avatar: selectedGroupAiCharacters[i].avatar },
content: "",
isAI: true
};
// 添加当前 AI 的消息
setMessages(prev => [...prev, aiMessage]);
try {
const response = await fetch(`${API_BASE_URL}/api/chat`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: selectedGroupAiCharacters[i].model,
message: inputMessage,
personality: selectedGroupAiCharacters[i].personality,
history: messageHistory,
index: i,
aiName: selectedGroupAiCharacters[i].name,
custom_prompt: selectedGroupAiCharacters[i].custom_prompt.replace('#groupName#', group.name) + "\n" + group.description
}),
});
if (!response.ok) {
throw new Error('请求失败');
}
const reader = response.body?.getReader();
const decoder = new TextDecoder();
if (!reader) {
throw new Error('无法获取响应流');
}
let buffer = '';
let completeResponse = ''; // 用于跟踪完整的响应
// 添加超时控制
const timeout = 10000; // 10秒超时
while (true) {
//console.log("读取中")
const startTime = Date.now();
let { done, value } = await Promise.race([
reader.read(),
new Promise((_, reject) =>
setTimeout(() => reject(new Error('响应超时')), timeout - (Date.now() - startTime))
)
]);
if (Date.now() - startTime > timeout) {
reader.cancel();
console.log("读取超时")
if (completeResponse.trim() === "") {
throw new Error('响应超时');
}
done = true;
}
if (done) {
//如果completeResponse为空
if (completeResponse.trim() === "") {
completeResponse = "对不起,我还不够智能,服务又断开了。";
setMessages(prev => {
const newMessages = [...prev];
const aiMessageIndex = newMessages.findIndex(msg => msg.id === aiMessage.id);
if (aiMessageIndex !== -1) {
newMessages[aiMessageIndex] = {
...newMessages[aiMessageIndex],
content: completeResponse
};
}
return newMessages;
});}
break;
}
buffer += decoder.decode(value, { stream: true });
let newlineIndex;
while ((newlineIndex = buffer.indexOf('\n')) >= 0) {
const line = buffer.slice(0, newlineIndex);
buffer = buffer.slice(newlineIndex + 1);
if (line.startsWith('data: ')) {
try {
const data = JSON.parse(line.slice(6));
if (data.content) {
completeResponse += data.content;
//正则去掉前面的任何AI名称格式
completeResponse = completeResponse.replace(new RegExp(`^(${allNames.join('|')})`, 'i'), '');
setMessages(prev => {
const newMessages = [...prev];
const aiMessageIndex = newMessages.findIndex(msg => msg.id === aiMessage.id);
if (aiMessageIndex !== -1) {
newMessages[aiMessageIndex] = {
...newMessages[aiMessageIndex],
content: completeResponse
};
}
return newMessages;
});
}
} catch (e) {
console.error('解析响应数据失败:', e);
}
}
}
}
// 将当前AI的回复添加到消息历史中供下一个AI使用
messageHistory.push({
role: 'user',
content: aiMessage.sender.name + '' + completeResponse,
name: aiMessage.sender.name
});
// 等待一小段时间再开始下一个 AI 的回复
if (i < groupAiCharacters.length - 1) {
await new Promise(resolve => setTimeout(resolve, 1000));
}
} catch (error) {
console.error("发送消息失败:", error);
messageHistory.push({
role: 'user',
content: aiMessage.sender.name + "对不起,我还不够智能,服务又断开了(错误:" + error.message + ")。",
name: aiMessage.sender.name
});
setMessages(prev => prev.map(msg =>
msg.id === aiMessage.id
? { ...msg, content: "对不起,我还不够智能,服务又断开了(错误:" + error.message + ")。", isError: true }
: msg
));
}
}
setIsLoading(false);
};
const handleCancel = () => {
abortController.current.abort();
};
// 处理群组选择
const handleSelectGroup = (index: number) => {
//进行跳转到?id=index
window.location.href = `?id=${index}`;
return;
/*
//跳转后,关闭当前页面
setSelectedGroupIndex(index);
const newGroup = groups[index];
setGroup(newGroup);
// 重新生成当前群组的 AI 角色,并按照 members 数组的顺序排序
const newGroupAiCharacters = generateAICharacters(newGroup.name)
.filter(character => newGroup.members.includes(character.id))
.sort((a, b) => {
return newGroup.members.indexOf(a.id) - newGroup.members.indexOf(b.id);
});
// 更新用户列表
setUsers([
{ id: 1, name: "我" },
...newGroupAiCharacters
]);
setIsGroupDiscussionMode(newGroup.isGroupDiscussionMode);
// 重置消息
setMessages([]);
// 可选:关闭侧边栏(在移动设备上)
if (window.innerWidth < 768) {
setSidebarOpen(false);
}
*/
};
return (
<>
<KaTeXStyle />
<div className="fixed inset-0 bg-gradient-to-br from-orange-50 via-orange-50/70 to-orange-100 flex items-start md:items-center justify-center overflow-hidden">
<div className="h-full flex bg-white w-full mx-auto relative shadow-xl md:max-w-5xl md:h-[96dvh] md:my-auto md:rounded-lg">
{/* 传递 selectedGroupIndex 和 onSelectGroup 回调给 Sidebar */}
<Sidebar
isOpen={sidebarOpen}
toggleSidebar={toggleSidebar}
selectedGroupIndex={selectedGroupIndex}
onSelectGroup={handleSelectGroup}
groups={groups}
/>
{/* 聊天主界面 */}
<div className="flex flex-col flex-1">
{/* Header */}
<header className="bg-white shadow flex-none md:rounded-t-lg">
<div className="flex items-center justify-between px-0 py-1.5">
{/* 左侧群组信息 */}
<div className="flex items-center md:px-2.5">
<div
className="md:hidden flex items-center justify-center m-1 cursor-pointer"
onClick={toggleSidebar}
>
<ChevronLeft className="w-6 h-6" />
</div>
<h1 className="font-medium text-base -ml-1">{group.name}({users.length})</h1>
</div>
{/* 右侧头像组和按钮 */}
<div className="flex items-center">
{/* 广告位 手机端不展示*/}
<div className="hidden md:block">
<AdBanner show={showAd} closeAd={() => setShowAd(false)} />
</div>
<div className="flex -space-x-2 ">
{users.slice(0, 4).map((user) => {
const avatarData = getAvatarData(user.name);
return (
<TooltipProvider key={user.id}>
<Tooltip>
<TooltipTrigger>
<Avatar className="w-7 h-7 border-2 border-white">
{'avatar' in user && user.avatar ? (
<AvatarImage src={user.avatar} />
) : (
<AvatarFallback style={{ backgroundColor: avatarData.backgroundColor, color: 'white' }}>
{avatarData.text}
</AvatarFallback>
)}
</Avatar>
</TooltipTrigger>
<TooltipContent>
<p>{user.name}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
);
})}
{users.length > 4 && (
<div className="w-7 h-7 rounded-full bg-gray-200 flex items-center justify-center text-xs border-2 border-white">
+{users.length - 4}
</div>
)}
</div>
<Button variant="ghost" size="icon" onClick={() => setShowMembers(true)}>
<Settings2 className="w-5 h-5" />
</Button>
</div>
</div>
</header>
{/* Main Chat Area */}
<div className="flex-1 overflow-hidden bg-gray-100">
<ScrollArea className={`h-full ${!showAd ? 'px-2 py-1' : ''} md:px-2 md:py-1`} ref={chatAreaRef}>
<div className="md:hidden">
<AdBannerMobile show={showAd} closeAd={() => setShowAd(false)} />
</div>
<div className="space-y-4">
{messages.map((message) => (
<div key={message.id}
className={`flex items-start gap-2 ${message.sender.name === "我" ? "justify-end" : ""}`}>
{message.sender.name !== "我" && (
<Avatar>
{'avatar' in message.sender && message.sender.avatar ? (
<AvatarImage src={message.sender.avatar} className="w-10 h-10" />
) : (
<AvatarFallback style={{ backgroundColor: getAvatarData(message.sender.name).backgroundColor, color: 'white' }}>
{message.sender.name[0]}
</AvatarFallback>
)}
</Avatar>
)}
<div className={message.sender.name === "我" ? "text-right" : ""}>
<div className="text-sm text-gray-500">{message.sender.name}</div>
<div className={`mt-1 p-3 rounded-lg shadow-sm chat-message ${
message.sender.name === "我" ? "bg-blue-500 text-white text-left" : "bg-white"
}`}>
<ReactMarkdown
remarkPlugins={[remarkGfm, remarkMath]}
rehypePlugins={[rehypeKatex]}
className={`prose dark:prose-invert max-w-none ${
message.sender.name === "我" ? "text-white [&_*]:text-white" : ""
}
[&_h2]:py-1
[&_h2]:m-0
[&_h3]:py-1.5
[&_h3]:m-0
[&_p]:m-0
[&_pre]:bg-gray-900
[&_pre]:p-2
[&_pre]:m-0
[&_pre]:rounded-lg
[&_pre]:text-gray-100
[&_pre]:whitespace-pre-wrap
[&_pre]:break-words
[&_pre_code]:whitespace-pre-wrap
[&_pre_code]:break-words
[&_code]:text-sm
[&_code]:text-gray-400
[&_code:not(:where([class~="language-"]))]:text-pink-500
[&_code:not(:where([class~="language-"]))]:bg-transparent
[&_a]:text-blue-500
[&_a]:no-underline
[&_ul]:my-2
[&_ol]:my-2
[&_li]:my-1
[&_blockquote]:border-l-4
[&_blockquote]:border-gray-300
[&_blockquote]:pl-4
[&_blockquote]:my-2
[&_blockquote]:italic`}
>
{message.content}
</ReactMarkdown>
{message.isAI && isTyping && currentMessageRef.current === message.id && (
<span className="typing-indicator ml-1"></span>
)}
</div>
</div>
{message.sender.name === "我" && (
<Avatar>
{'avatar' in message.sender && message.sender.avatar ? (
<AvatarImage src={message.sender.avatar} className="w-10 h-10" />
) : (
<AvatarFallback style={{ backgroundColor: getAvatarData(message.sender.name).backgroundColor, color: 'white' }}>
{message.sender.name[0]}
</AvatarFallback>
)}
</Avatar>
)}
</div>
))}
<div ref={messagesEndRef} />
{/* 添加一个二维码 */}
<div id="qrcode" className="flex flex-col items-center hidden">
<img src="/img/qr.png" alt="QR Code" className="w-24 h-24" />
<p className="text-sm text-gray-500 mt-2 font-medium tracking-tight bg-gray-50 px-3 py-1 rounded-full">AI群聊</p>
</div>
</div>
</ScrollArea>
</div>
{/* Input Area */}
<div className="bg-white border-t py-3 px-2 md:rounded-b-lg">
<div className="flex gap-1 pb-[env(safe-area-inset-bottom)]">
{messages.length > 0 && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="outline"
size="icon"
onClick={handleShareChat}
className="px-3"
>
<Share2 className="w-4 h-4" />
</Button>
</TooltipTrigger>
<TooltipContent>
<p></p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
<Input
placeholder="输入消息..."
className="flex-1"
value={inputMessage}
onChange={(e) => setInputMessage(e.target.value)}
onKeyPress={(e) => e.key === 'Enter' && handleSendMessage()}
/>
<Button
onClick={handleSendMessage}
disabled={isLoading}
>
{isLoading ? (
<div className="w-4 h-4 mr-2 animate-spin rounded-full border-2 border-white border-t-transparent" />
) : (
<Send className="w-4 h-4" />
)}
</Button>
</div>
</div>
</div>
</div>
{/* Members Management Dialog */}
<MembersManagement
showMembers={showMembers}
setShowMembers={setShowMembers}
users={users}
mutedUsers={mutedUsers}
handleToggleMute={handleToggleMute}
isGroupDiscussionMode={isGroupDiscussionMode}
onToggleGroupDiscussion={() => setIsGroupDiscussionMode(!isGroupDiscussionMode)}
getAvatarData={getAvatarData}
/>
</div>
{/* 添加 SharePoster 组件 */}
<SharePoster
isOpen={showPoster}
onClose={() => setShowPoster(false)}
chatAreaRef={chatAreaRef}
/>
</>
);
};
export default ChatUI;

View File

@@ -0,0 +1,38 @@
import React, { useEffect } from 'react';
import GitHubButton from 'react-github-btn';
import '@fontsource/audiowide';
const Header: React.FC = () => {
return (
<header className="bg-transparent fixed top-0 left-0 right-0 z-50 hidden md:block">
<div className="w-full px-2 h-10 flex items-center" >
{/* Logo */}
<div className="flex-1 flex items-center">
<a href="/" className="flex items-center">
<img src="/img/logo.svg" alt="logo" className="h-6 w-6 mr-2" />
<span style={{ fontFamily: 'Audiowide, system-ui', color: '#ff6600' }} className="text-2xl">
botgroup.chat
</span>
</a>
</div>
{/* GitHub Star Button */}
<div className="flex items-center justify-end">
<GitHubButton
href="https://github.com/maojindao55/botgroup.chat"
data-color-scheme="no-preference: light; light: light; dark: light;"
data-size="large"
data-show-count="true"
aria-label="Star maojindao55/botgroup.chat on GitHub"
>
Star
</GitHubButton>
</div>
</div>
</header>
);
};
export default Header;

View File

@@ -0,0 +1,16 @@
import React from 'react';
import Header from './Header';
const Layout: React.FC<{ children: React.ReactNode }> = ({ children }) => {
return (
<div className="flex flex-col min-h-screen">
<div className="flex flex-1">
<main className="flex-1 pt-14">
{children}
</main>
</div>
</div>
);
};
export default Layout;

View File

@@ -0,0 +1,116 @@
import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@/components/ui/sheet";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Button } from "@/components/ui/button";
import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { UserPlus, Mic, MicOff } from 'lucide-react';
import { type AICharacter } from "@/config/aiCharacters";
import { Switch } from "@/components/ui/switch";
interface User {
id: number | string;
name: string;
avatar?: string;
}
interface MembersManagementProps {
showMembers: boolean;
setShowMembers: (show: boolean) => void;
users: (User | AICharacter)[];
mutedUsers: string[];
handleToggleMute: (userId: string) => void;
getAvatarData: (name: string) => { backgroundColor: string; text: string };
isGroupDiscussionMode: boolean;
onToggleGroupDiscussion: () => void;
}
export const MembersManagement = ({
showMembers,
setShowMembers,
users,
mutedUsers,
handleToggleMute,
getAvatarData,
isGroupDiscussionMode,
onToggleGroupDiscussion
}: MembersManagementProps) => {
return (
<Sheet open={showMembers} onOpenChange={setShowMembers}>
<SheetContent side="right" className="w-[300px] sm:w-[400px]">
<SheetHeader>
<SheetTitle></SheetTitle>
</SheetHeader>
<div className="mt-4">
<div className="mb-6 p-4 bg-gray-50 rounded-lg">
<div className="flex items-center justify-between">
<div>
<div className="text-sm"></div>
<div className="text-xs text-gray-500"></div>
</div>
<Switch
checked={isGroupDiscussionMode}
onCheckedChange={onToggleGroupDiscussion}
/>
</div>
</div>
<div className="flex justify-between items-center mb-4">
<span className="text-sm text-gray-500">{users.length}</span>
<Button variant="outline" size="sm">
<UserPlus className="w-4 h-4 mr-2" />
</Button>
</div>
<ScrollArea className="h-[calc(100vh-150px)]">
<div className="space-y-2 pr-4">
{users.map((user) => (
<div key={user.id} className="flex items-center justify-between p-2 hover:bg-gray-100 rounded-lg">
<div className="flex items-center gap-3">
<Avatar>
{'avatar' in user && user.avatar ? (
<AvatarImage src={user.avatar} className="w-10 h-10" />
) : (
<AvatarFallback style={{ backgroundColor: getAvatarData(user.name).backgroundColor, color: 'white' }}>
{user.name[0]}
</AvatarFallback>
)}
</Avatar>
<div className="flex flex-col">
<span>{user.name}</span>
{mutedUsers.includes(user.id as string) && (
<span className="text-xs text-red-500"></span>
)}
</div>
</div>
{user.name !== "我" && (
<div className="flex gap-2">
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
onClick={() => handleToggleMute(user.id as string)}
>
{mutedUsers.includes(user.id as string) ? (
<MicOff className="w-4 h-4 text-red-500" />
) : (
<Mic className="w-4 h-4 text-green-500" />
)}
</Button>
</TooltipTrigger>
<TooltipContent>
{mutedUsers.includes(user.id as string) ? '取消禁言' : '禁言'}
</TooltipContent>
</Tooltip>
</TooltipProvider>
</div>
)}
</div>
))}
</div>
</ScrollArea>
</div>
</SheetContent>
</Sheet>
);
};

View File

@@ -0,0 +1,199 @@
import React, { useRef, useEffect } from 'react';
import domtoimage from 'dom-to-image';
import { Dialog, DialogContent, DialogClose } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Share2, Download } from 'lucide-react';
import { toast } from 'sonner';
interface SharePosterProps {
isOpen: boolean;
onClose: () => void;
chatAreaRef: React.RefObject<HTMLDivElement>;
}
export function SharePoster({ isOpen, onClose, chatAreaRef }: SharePosterProps) {
const posterRef = useRef<HTMLDivElement>(null);
const [posterImage, setPosterImage] = React.useState<string>('');
useEffect(() => {
if (isOpen && chatAreaRef.current) {
generatePoster();
}
}, [isOpen]);
const generatePoster = async () => {
if (!chatAreaRef.current) return;
await document.fonts.ready;
try {
const messageContainer = chatAreaRef.current.querySelector('.space-y-4');
if (!messageContainer) return;
const qrCode = messageContainer.querySelector('#qrcode');
if (qrCode) {
qrCode.classList.remove('hidden');
}
// 预处理所有图片
const preloadImages = async () => {
const images = Array.from(messageContainer.getElementsByTagName('img'));
await Promise.all(images.map(async (img) => {
try {
const response = await fetch(img.src, {
mode: 'cors',
credentials: 'omit'
});
const blob = await response.blob();
const base64 = await new Promise((resolve) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result);
reader.readAsDataURL(blob);
});
img.src = base64 as string;
} catch (error) {
console.error('图片预处理失败:', error);
}
}));
};
await preloadImages();
const originalScroll = chatAreaRef.current.scrollTop;
chatAreaRef.current.scrollTop = 0;
const viewportWidth = Math.min(window.innerWidth, document.documentElement.clientWidth);
const extraSpace = 6;
const targetWidth = viewportWidth * 0.95 - (extraSpace * 2);
const currentWidth = messageContainer.getBoundingClientRect().width;
const scale = targetWidth / currentWidth;
const currentHeight = messageContainer.scrollHeight;
const adjustedHeight = currentHeight * scale;
const dataUrl = await domtoimage.toSvg(messageContainer as HTMLElement, {
bgcolor: '#f3f4f6',
scale: 1, // 回到较安全的值
width: targetWidth + (extraSpace * 5),
height: adjustedHeight + (extraSpace * 5),
style: {
padding: `${extraSpace}px`,
margin: '0 auto',
width: '120%',
height: '110%',
transform: `scale(${scale})`,
transformOrigin: 'top left',
background: '#f3f4f6',
boxSizing: 'border-box'
},
quality: 1.0
});
chatAreaRef.current.scrollTop = originalScroll;
setPosterImage(dataUrl);
} catch (error) {
console.error('生成海报失败:', error);
}
};
const handleDownload = async () => {
if (!posterImage) return;
try {
// 创建一个新的图片对象
const img = new Image();
img.crossOrigin = 'anonymous';
// 等待图片加载完成
await new Promise((resolve, reject) => {
img.onload = resolve;
img.onerror = reject;
img.src = posterImage;
});
// 创建高分辨率canvas
const scale = 2;
const canvas = document.createElement('canvas');
canvas.width = img.width * scale;
canvas.height = img.height * scale;
const ctx = canvas.getContext('2d');
if (!ctx) {
throw new Error('无法创建canvas上下文');
}
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = 'high';
ctx.scale(scale, scale);
ctx.drawImage(img, 0, 0);
// 转换为Blob
const blob = await new Promise<Blob>((resolve) => {
canvas.toBlob((blob) => {
resolve(blob!);
}, 'image/png', 1.0);
});
// 检查是否为移动设备
if (/Android|iPhone|iPad|iPod/i.test(navigator.userAgent) && navigator.share) {
// 使用系统分享
await navigator.share({
files: [new File([blob], 'chat-history.png', { type: 'image/png' })],
title: '聊天记录',
});
} else {
// PC端使用传统下载方式
const pngUrl = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = pngUrl;
a.download = 'chat-history.png';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(pngUrl);
}
} catch (error) {
console.error('转换图片失败:', error);
toast.error('保存图片失败,请重试');
}
};
return (
<Dialog open={isOpen} onOpenChange={(open) => {
if (!open) {
// Hide QR code when dialog closes
const qrCode = chatAreaRef.current?.querySelector('#qrcode');
if (qrCode) {
qrCode.classList.add('hidden');
}
onClose();
}
}}>
<DialogContent className="max-w-[100vw] w-full sm:max-w-[50vw] max-h-[90vh] flex flex-col p-0">
{/* 图片容器 */}
<div className="flex-1 overflow-auto ">
{posterImage && (
<div className="flex items-center justify-center min-h-full">
<img
src={posterImage}
alt="Share Poster"
className="w-full w-auto h-auto"
style={{
objectFit: 'contain',
imageRendering: 'crisp-edges',
WebkitFontSmoothing: 'antialiased'
}}
/>
</div>
)}
</div>
<div className="flex items-center justify-center gap-2 p-2 sm:p-4 border-t">
<Button onClick={handleDownload}>
</Button>
</div>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,171 @@
import React from 'react';
import { Button } from "@/components/ui/button";
import { MessageSquareIcon, PlusCircleIcon, MenuIcon, PanelLeftCloseIcon } from "lucide-react";
import { cn } from "@/lib/utils";
import GitHubButton from 'react-github-btn';
import '@fontsource/audiowide';
//import { groups } from "@/config/groups";
import { AdSection } from './AdSection';
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip";
// 根据群组ID生成固定的随机颜色
const getRandomColor = (index: number) => {
const colors = ['blue', 'green', 'yellow', 'purple', 'pink', 'indigo', 'red', 'orange', 'teal'];
//增加hash
const hashCode = index.toString().split('').reduce((acc, char) => {
return char.charCodeAt(0) + ((acc << 5) - acc);
}, 0);
return colors[hashCode % colors.length];
};
interface SidebarProps {
isOpen: boolean;
toggleSidebar: () => void;
selectedGroupIndex?: number;
onSelectGroup?: (index: number) => void;
groups: Group[];
}
const Sidebar = ({ isOpen, toggleSidebar, selectedGroupIndex = 0, onSelectGroup, groups }: SidebarProps) => {
return (
<>
{/* 侧边栏 - 在移动设备上可以隐藏,在桌面上始终显示 */}
<div
className={cn(
"transition-all duration-300 ease-in-out",
"fixed md:relative z-20 h-full",
isOpen ? "w-48 translate-x-0" : "w-0 md:w-14 -translate-x-full md:translate-x-0"
)}
>
<div className="h-full border-r bg-background rounded-l-lg overflow-hidden flex flex-col">
<div className="flex items-center justify-between px-2 py-1.5 border-b border-border/40">
<div className="flex-1 flex items-center">
<span className={cn(
"font-medium text-base text-foreground/90 transition-all duration-200 whitespace-nowrap overflow-hidden",
isOpen ? "opacity-100 max-w-full mr-2 pl-3" : "opacity-0 max-w-0 md:max-w-0"
)}>
</span>
<Button
variant="ghost"
size="icon"
onClick={toggleSidebar}
className={cn(
"text-muted-foreground hover:text-primary",
isOpen ? "ml-auto" : "mx-auto md:ml-auto"
)}
>
{isOpen ? <PanelLeftCloseIcon className="h-4 w-4" /> : <MenuIcon className="h-4 w-4" />}
</Button>
</div>
</div>
<div className="flex-1 overflow-auto p-2">
<nav className="space-y-1.5">
{groups.map((group, index) => (
<a
key={group.id}
href="#"
onClick={(e) => {
e.preventDefault();
onSelectGroup?.(index);
}}
className={cn(
"flex items-center gap-1 rounded-md px-3 py-2.5 text-sm font-medium transition-all hover:bg-accent/80 group",
!isOpen && "md:justify-center",
selectedGroupIndex === index && "bg-accent"
)}
>
<MessageSquareIcon
className={`h-5 w-5 flex-shrink-0 group-hover:opacity-80 text-${getRandomColor(index)}-500 group-hover:text-${getRandomColor(index)}-600`}
/>
<span className={cn(
"transition-all duration-200 whitespace-nowrap overflow-hidden text-foreground/90",
isOpen ? "opacity-100 max-w-full" : "opacity-0 max-w-0 md:max-w-0"
)}>{group.name}</span>
</a>
))}
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<a
href="#"
className={cn(
"flex items-center gap-1 rounded-md px-3 py-2.5 text-sm font-medium transition-all hover:bg-accent/80 group mt-3",
!isOpen && "md:justify-center"
)}
onClick={(e) => {
e.preventDefault();
}}
>
<PlusCircleIcon className="h-5 w-5 flex-shrink-0 text-amber-500 group-hover:text-amber-600" />
<span className={cn(
"transition-all duration-200 whitespace-nowrap overflow-hidden text-foreground/90",
isOpen ? "opacity-100 max-w-full" : "opacity-0 max-w-0 md:max-w-0"
)}></span>
</a>
</TooltipTrigger>
<TooltipContent>
<p>,</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
</nav>
</div>
{/* 广告位 */}
<AdSection isOpen={isOpen} />
{/* GitHub Star Button - 只在侧边栏打开时显示,放在底部 */}
<div className="px-3 py-2 mt-auto">
{/* 标题移至底部 */}
<div className="flex items-center justify-left mb-3">
<a href="/" className="flex items-center">
<span
style={{ fontFamily: 'Audiowide, system-ui', color: '#ff6600' }}
className={cn(
"transition-all duration-200 whitespace-nowrap overflow-hidden",
isOpen ? "text-lg" : "text-xs max-w-0 opacity-0 md:max-w-0"
)}
>
botgroup.chat
</span>
</a>
</div>
{isOpen && (
<div className="flex items-center justify-left">
<GitHubButton
href="https://github.com/maojindao55/botgroup.chat"
data-color-scheme="no-preference: light; light: light; dark: light;"
data-size="large"
data-show-count="true"
aria-label="Star maojindao55/botgroup.chat on GitHub"
>
Star
</GitHubButton>
</div>
)}
</div>
</div>
</div>
{/* 移动设备上的遮罩层,点击时关闭侧边栏 */}
{isOpen && (
<div
className="fixed inset-0 bg-black/50 z-10 md:hidden"
onClick={toggleSidebar}
/>
)}
</>
);
};
export default Sidebar;

7
src/pages/chat/index.tsx Normal file
View File

@@ -0,0 +1,7 @@
import ChatUI from './components/ChatUI';
export default function Chat() {
return (
<ChatUI />
);
}

View File

@@ -0,0 +1,159 @@
import React, { useState } from 'react';
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
interface PhoneLoginProps {
onLogin: (phone: string, code: string) => void;
}
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || '';
const PhoneLogin: React.FC<PhoneLoginProps> = ({ onLogin }) => {
const [phone, setPhone] = useState('');
const [code, setCode] = useState('');
const [countdown, setCountdown] = useState(0);
const [isLoading, setIsLoading] = useState(false);
// 发送验证码
const handleSendCode = async () => {
if (!phone || !/^1[3-9]\d{9}$/.test(phone)) {
alert('请输入正确的手机号');
return;
}
//setIsLoading(true);
try {
const response = await fetch(`${API_BASE_URL}/api/sendcode`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ phone }),
});
if (!response.ok) {
throw new Error('发送验证码失败');
}
// 开始倒计时
setCountdown(60);
const timer = setInterval(() => {
setCountdown((prev) => {
if (prev <= 1) {
clearInterval(timer);
return 0;
}
return prev - 1;
});
}, 1000);
} catch (error) {
console.error('发送验证码失败:', error);
alert('发送验证码失败,请重试');
} finally {
setIsLoading(false);
}
};
// 提交登录
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!phone || !code) {
alert('请输入手机号和验证码');
return;
}
setIsLoading(true);
try {
const response = await fetch(`${API_BASE_URL}/api/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ phone, code }),
});
const data = await response.json();
console.log(data);
if (!response.ok) {
throw new Error(data.message || '登录失败');
}
// 保存 token 到 localStorage
localStorage.setItem('token', data.data.token);
localStorage.setItem('phone', data.data.phone);
} catch (error) {
console.error('登录失败:', error);
alert(error instanceof Error ? error.message : '登录失败,请重试');
} finally {
setIsLoading(false);
}
};
return (
<div className="fixed inset-0 bg-white flex items-center justify-center">
<div className="w-full max-w-md p-8">
{/* Logo */}
<div className="flex items-center justify-center mb-4">
<span style={{fontFamily: 'Audiowide, system-ui', color: '#ff6600'}} className="text-3xl ml-2">botgroup.chat</span>
</div>
<div className="text-gray-500 mb-4 text-center">
</div>
<form onSubmit={handleSubmit} className="space-y-6">
<div>
<div className="flex items-center border rounded-lg p-3 h-[46px] focus-within:border-[#ff6600]">
<span className="text-gray-400 mr-2">+86</span>
<Input
type="tel"
placeholder="请输入手机号"
value={phone}
onChange={(e) => setPhone(e.target.value)}
maxLength={11}
className="border-none focus:ring-0 focus-visible:ring-0 focus-visible:ring-offset-0 shadow-none p-0"
/>
</div>
</div>
<div>
<div className="flex gap-3">
<Input
type="text"
placeholder="请输入验证码"
value={code}
onChange={(e) => setCode(e.target.value)}
maxLength={6}
className="border rounded-lg p-3 h-[46px] focus:border-[#ff6600] focus:ring-0 focus-visible:ring-0 focus-visible:ring-offset-0 shadow-none"
/>
<Button
type="button"
onClick={handleSendCode}
disabled={countdown > 0 || isLoading}
className="bg-white text-[#ff6600] border border-[#ff6600] hover:bg-[#ff6600] hover:text-white rounded-lg px-6 h-[46px]"
>
{countdown > 0 ? `${countdown}秒后重试` : '发送验证码'}
</Button>
</div>
</div>
<Button
type="submit"
className="w-full bg-[#ff6600] hover:bg-[#e65c00] text-white rounded-lg py-3"
disabled={isLoading}
>
{isLoading ? (
<div className="w-4 h-4 mr-2 animate-spin rounded-full border-2 border-white border-t-transparent" />
) : '登录'}
</Button>
</form>
</div>
</div>
);
};
export default PhoneLogin;

17
src/pages/login/index.jsx Normal file
View File

@@ -0,0 +1,17 @@
import { useNavigate } from 'react-router-dom';
import PhoneLogin from './comonents/PhoneLogin';
export default function Login() {
const navigate = useNavigate();
const handleLoginSuccess = (token) => {
localStorage.setItem('token', token);
navigate('/');
};
return (
<div className="login-container">
<PhoneLogin onSuccess={handleLoginSuccess} />
</div>
);
}