Checkpoint: v3.0 - 新增训练视频教程库(分类浏览、自评系统)、训练提醒通知(多类型提醒、浏览器推送)、通知记录管理、去除冗余文字。65个测试全部通过。

这个提交包含在:
Manus
2026-03-14 08:28:57 -04:00
父节点 2c418b482e
当前提交 27083d5af9
修改 19 个文件,包含 2856 行新增32 行删除

查看文件

@@ -315,7 +315,7 @@ export default function Analysis() {
<div className="space-y-6">
<div>
<h1 className="text-2xl font-bold tracking-tight">姿</h1>
<p className="text-muted-foreground text-sm mt-1">AI自动识别姿势并给出矫正建议</p>
<p className="text-muted-foreground text-sm mt-1">AI姿势识别与矫正反馈</p>
</div>
{/* Upload section */}

查看文件

@@ -19,7 +19,7 @@ export default function Home() {
<header className="container py-6 flex items-center justify-between">
<div className="flex items-center gap-2">
<Target className="h-6 w-6 text-primary" />
<span className="font-bold text-lg tracking-tight">Tennis Training Hub</span>
<span className="font-bold text-lg tracking-tight">Tennis Hub</span>
</div>
<Button onClick={() => setLocation("/login")} variant="default" size="sm">
使
@@ -30,19 +30,18 @@ export default function Home() {
<div className="max-w-3xl mx-auto text-center">
<div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-primary/10 text-primary text-sm font-medium mb-6">
<Zap className="h-3.5 w-3.5" />
AI驱动的网球训练助手
AI网球训练助手
</div>
<h1 className="text-4xl md:text-5xl lg:text-6xl font-bold tracking-tight leading-tight">
<span className="text-primary block mt-1"></span>
<span className="text-primary block mt-1"></span>
</h1>
<p className="text-lg text-muted-foreground mt-6 max-w-xl mx-auto leading-relaxed">
AI姿势识别和智能训练计划
AI姿势识别 · · ·
</p>
<div className="flex items-center justify-center gap-3 mt-8">
<Button onClick={() => setLocation("/login")} size="lg" className="gap-2 h-12 px-6">
<ChevronRight className="h-4 w-4" />
</Button>
</div>
@@ -57,37 +56,37 @@ export default function Home() {
{
icon: Video,
title: "AI姿势识别",
desc: "基于MediaPipe的浏览器端实时姿势分析,识别33个身体关键点,精准评估挥拍动作",
desc: "MediaPipe实时分析33个关键点,精准评估挥拍动作",
color: "bg-blue-50 text-blue-600",
},
{
icon: Target,
title: "智能训练计划",
desc: "根据您的水平和分析结果,AI自动生成和调整个性化训练方案,只需球拍即可在家训练",
desc: "根据水平和分析结果,AI自动生成和调整训练方案",
color: "bg-green-50 text-green-600",
},
{
icon: Award,
title: "NTRP自动评分",
desc: "基于美国网球协会标准,从5个维度综合评估您的技术水平,自动更新评分",
desc: "USTA标准五维度评估,每次分析自动更新评分",
color: "bg-purple-50 text-purple-600",
},
{
icon: Zap,
title: "击球统计分析",
desc: "自动检测击球次数、挥拍速度、击球一致性,量化每次训练效果",
title: "击球统计",
desc: "击球次数、挥拍速度、一致性,量化训练效果",
color: "bg-orange-50 text-orange-600",
},
{
icon: Footprints,
title: "运动轨迹追踪",
desc: "记录身体重心移动轨迹分析脚步移动模式,提升步法灵活性",
title: "运动轨迹",
desc: "重心移动轨迹分析,优化脚步移动模式",
color: "bg-teal-50 text-teal-600",
},
{
icon: TrendingUp,
title: "进度可视化",
desc: "直观展示训练历史、能力提升趋势评分变化,激励持续进步",
title: "进度追踪",
desc: "训练历史、能力趋势评分变化一目了然",
color: "bg-indigo-50 text-indigo-600",
},
].map((feature) => (
@@ -107,10 +106,10 @@ export default function Home() {
<h2 className="text-2xl font-bold text-center mb-12">使</h2>
<div className="grid grid-cols-1 md:grid-cols-4 gap-6 max-w-4xl mx-auto">
{[
{ step: "1", title: "输入用户名", desc: "无需注册,输入用户名即可开始" },
{ step: "2", title: "生成训练计划", desc: "选择水平,AI生成个性化方案" },
{ step: "3", title: "上传训练视频", desc: "录制挥拍视频并上传分析" },
{ step: "4", title: "获取评分建议", desc: "查看分析结果和矫正建议" },
{ step: "1", title: "输入用户名", desc: "用户名登录即可" },
{ step: "2", title: "生成计划", desc: "AI个性化训练方案" },
{ step: "3", title: "上传视频", desc: "录制挥拍分析" },
{ step: "4", title: "获取反馈", desc: "评分与矫正建议" },
].map((item) => (
<div key={item.step} className="text-center">
<div className="h-12 w-12 rounded-full bg-primary text-primary-foreground flex items-center justify-center text-lg font-bold mx-auto mb-3">
@@ -126,8 +125,8 @@ export default function Home() {
{/* CTA */}
<section className="container py-16">
<div className="max-w-2xl mx-auto text-center p-8 rounded-2xl bg-primary/5">
<h2 className="text-2xl font-bold mb-3"></h2>
<p className="text-muted-foreground mb-6"></p>
<h2 className="text-2xl font-bold mb-3"></h2>
<p className="text-muted-foreground mb-6">使</p>
<Button onClick={() => setLocation("/login")} size="lg" className="gap-2">
<ChevronRight className="h-4 w-4" />
@@ -140,9 +139,9 @@ export default function Home() {
<div className="flex items-center justify-between text-xs text-muted-foreground">
<div className="flex items-center gap-2">
<Target className="h-4 w-4" />
<span>Tennis Training Hub</span>
<span>Tennis Hub</span>
</div>
<span>AI驱动的在家网球训练助手</span>
<span>AI网球训练助手</span>
</div>
</footer>
</div>

查看文件

@@ -36,8 +36,8 @@ export default function Login() {
<div className="inline-flex items-center justify-center w-16 h-16 rounded-2xl bg-primary/10 mb-4">
<Target className="w-8 h-8 text-primary" />
</div>
<h1 className="text-3xl font-bold tracking-tight">Tennis Training Hub</h1>
<p className="text-muted-foreground mt-2">AI驱动的在家网球训练助手</p>
<h1 className="text-3xl font-bold tracking-tight">Tennis Hub</h1>
<p className="text-muted-foreground mt-2">AI网球训练助手</p>
</div>
<Card className="border-0 shadow-xl">
@@ -94,7 +94,7 @@ export default function Login() {
</Card>
<p className="text-center text-xs text-muted-foreground mt-6">
使
使
</p>
</div>
</div>

查看文件

@@ -0,0 +1,472 @@
import { useAuth } from "@/_core/hooks/useAuth";
import { trpc } from "@/lib/trpc";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, DialogFooter } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Separator } from "@/components/ui/separator";
import { toast } from "sonner";
import { useState, useEffect, useCallback, useMemo } from "react";
import {
Bell, BellRing, Plus, Trash2, Clock, Calendar,
CheckCircle2, XCircle, Settings, BellOff, Volume2
} from "lucide-react";
const DAY_NAMES = ["日", "一", "二", "三", "四", "五", "六"];
const REMINDER_TYPES = [
{ value: "training", label: "训练提醒", icon: <Clock className="w-4 h-4" /> },
{ value: "checkin", label: "打卡提醒", icon: <CheckCircle2 className="w-4 h-4" /> },
{ value: "analysis", label: "分析提醒", icon: <Settings className="w-4 h-4" /> },
];
export default function Reminders() {
const { user } = useAuth();
const [showCreate, setShowCreate] = useState(false);
const [newReminder, setNewReminder] = useState({
reminderType: "training",
title: "",
message: "",
timeOfDay: "08:00",
daysOfWeek: [1, 2, 3, 4, 5] as number[],
});
const utils = trpc.useUtils();
const { data: reminders, isLoading } = trpc.reminder.list.useQuery(undefined, { enabled: !!user });
const { data: notifications } = trpc.notification.list.useQuery(undefined, { enabled: !!user });
const { data: unreadCount } = trpc.notification.unreadCount.useQuery(undefined, { enabled: !!user });
const createReminder = trpc.reminder.create.useMutation({
onSuccess: () => {
toast.success("提醒已创建");
setShowCreate(false);
setNewReminder({ reminderType: "training", title: "", message: "", timeOfDay: "08:00", daysOfWeek: [1, 2, 3, 4, 5] });
utils.reminder.list.invalidate();
},
});
const deleteReminder = trpc.reminder.delete.useMutation({
onSuccess: () => {
toast.success("提醒已删除");
utils.reminder.list.invalidate();
},
});
const toggleReminder = trpc.reminder.toggle.useMutation({
onSuccess: () => {
utils.reminder.list.invalidate();
},
});
const markAllRead = trpc.notification.markAllRead.useMutation({
onSuccess: () => {
utils.notification.list.invalidate();
utils.notification.unreadCount.invalidate();
toast.success("全部已读");
},
});
const markRead = trpc.notification.markRead.useMutation({
onSuccess: () => {
utils.notification.list.invalidate();
utils.notification.unreadCount.invalidate();
},
});
const toggleDay = useCallback((day: number) => {
setNewReminder(prev => ({
...prev,
daysOfWeek: prev.daysOfWeek.includes(day)
? prev.daysOfWeek.filter(d => d !== day)
: [...prev.daysOfWeek, day].sort(),
}));
}, []);
const handleCreate = () => {
if (!newReminder.title.trim()) {
toast.error("请输入提醒标题");
return;
}
if (newReminder.daysOfWeek.length === 0) {
toast.error("请至少选择一天");
return;
}
createReminder.mutate(newReminder);
};
// Browser notification permission
const [notifPermission, setNotifPermission] = useState<NotificationPermission>("default");
useEffect(() => {
if ("Notification" in window) {
setNotifPermission(Notification.permission);
}
}, []);
const requestPermission = async () => {
if ("Notification" in window) {
const perm = await Notification.requestPermission();
setNotifPermission(perm);
if (perm === "granted") {
toast.success("通知权限已开启");
new Notification("Tennis Training Hub", { body: "训练提醒已开启!" });
}
}
};
// Check reminders and trigger browser notifications
useEffect(() => {
if (!reminders || notifPermission !== "granted") return;
const checkInterval = setInterval(() => {
const now = new Date();
const currentTime = `${String(now.getHours()).padStart(2, "0")}:${String(now.getMinutes()).padStart(2, "0")}`;
const currentDay = now.getDay();
reminders.forEach((r: any) => {
if (r.isActive && r.timeOfDay === currentTime) {
const days = typeof r.daysOfWeek === "string" ? JSON.parse(r.daysOfWeek) : r.daysOfWeek;
if (Array.isArray(days) && days.includes(currentDay)) {
new Notification(r.title, {
body: r.message || "该训练了!",
icon: "/favicon.ico",
});
}
}
});
}, 60000); // Check every minute
return () => clearInterval(checkInterval);
}, [reminders, notifPermission]);
const activeReminders = useMemo(() => reminders?.filter((r: any) => r.isActive) || [], [reminders]);
const inactiveReminders = useMemo(() => reminders?.filter((r: any) => !r.isActive) || [], [reminders]);
if (isLoading) {
return (
<div className="flex items-center justify-center min-h-[60vh]">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
</div>
);
}
return (
<div className="space-y-6">
{/* Header */}
<div className="flex items-center justify-between flex-wrap gap-3">
<div>
<h1 className="text-2xl font-bold flex items-center gap-2">
<Bell className="w-6 h-6 text-primary" />
</h1>
<p className="text-muted-foreground mt-1"></p>
</div>
<div className="flex gap-2">
{notifPermission !== "granted" && (
<Button variant="outline" size="sm" onClick={requestPermission} className="gap-1">
<Volume2 className="w-4 h-4" />
</Button>
)}
<Dialog open={showCreate} onOpenChange={setShowCreate}>
<DialogTrigger asChild>
<Button size="sm" className="gap-1">
<Plus className="w-4 h-4" />
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle></DialogTitle>
</DialogHeader>
<div className="space-y-4">
<div>
<Label></Label>
<Select value={newReminder.reminderType} onValueChange={v => setNewReminder(p => ({ ...p, reminderType: v }))}>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
{REMINDER_TYPES.map(t => (
<SelectItem key={t.value} value={t.value}>
<span className="flex items-center gap-2">{t.icon} {t.label}</span>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div>
<Label></Label>
<Input
placeholder="例:每日正手练习"
value={newReminder.title}
onChange={e => setNewReminder(p => ({ ...p, title: e.target.value }))}
/>
</div>
<div>
<Label></Label>
<Textarea
placeholder="例记得做10分钟影子挥拍..."
value={newReminder.message}
onChange={e => setNewReminder(p => ({ ...p, message: e.target.value }))}
rows={2}
/>
</div>
<div>
<Label></Label>
<Input
type="time"
value={newReminder.timeOfDay}
onChange={e => setNewReminder(p => ({ ...p, timeOfDay: e.target.value }))}
/>
</div>
<div>
<Label></Label>
<div className="flex gap-1.5 mt-1.5">
{DAY_NAMES.map((name, i) => (
<button
key={i}
onClick={() => toggleDay(i)}
className={`w-9 h-9 rounded-full text-sm font-medium transition-colors ${
newReminder.daysOfWeek.includes(i)
? "bg-primary text-primary-foreground"
: "bg-muted text-muted-foreground hover:bg-muted/80"
}`}
>
{name}
</button>
))}
</div>
<div className="flex gap-2 mt-2">
<Button variant="ghost" size="sm" onClick={() => setNewReminder(p => ({ ...p, daysOfWeek: [1, 2, 3, 4, 5] }))}>
</Button>
<Button variant="ghost" size="sm" onClick={() => setNewReminder(p => ({ ...p, daysOfWeek: [0, 6] }))}>
</Button>
<Button variant="ghost" size="sm" onClick={() => setNewReminder(p => ({ ...p, daysOfWeek: [0, 1, 2, 3, 4, 5, 6] }))}>
</Button>
</div>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setShowCreate(false)}></Button>
<Button onClick={handleCreate} disabled={createReminder.isPending}>
{createReminder.isPending ? "创建中..." : "创建"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
</div>
{/* Notification Permission Banner */}
{notifPermission === "default" && (
<Card className="border-amber-200 bg-amber-50">
<CardContent className="pt-4 flex items-center justify-between">
<div className="flex items-center gap-3">
<BellRing className="w-5 h-5 text-amber-600" />
<div>
<p className="font-medium text-amber-900"></p>
<p className="text-sm text-amber-700"></p>
</div>
</div>
<Button size="sm" onClick={requestPermission}></Button>
</CardContent>
</Card>
)}
{notifPermission === "denied" && (
<Card className="border-red-200 bg-red-50">
<CardContent className="pt-4 flex items-center gap-3">
<BellOff className="w-5 h-5 text-red-600" />
<div>
<p className="font-medium text-red-900"></p>
<p className="text-sm text-red-700"></p>
</div>
</CardContent>
</Card>
)}
{/* Active Reminders */}
<div>
<h2 className="text-lg font-semibold mb-3 flex items-center gap-2">
<BellRing className="w-5 h-5 text-green-600" />
({activeReminders.length})
</h2>
{activeReminders.length === 0 ? (
<Card>
<CardContent className="pt-6 text-center text-muted-foreground">
<Bell className="w-10 h-10 mx-auto mb-2 opacity-50" />
<p>"新建提醒"</p>
</CardContent>
</Card>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
{activeReminders.map((reminder: any) => {
const days = typeof reminder.daysOfWeek === "string" ? JSON.parse(reminder.daysOfWeek) : reminder.daysOfWeek;
const type = REMINDER_TYPES.find(t => t.value === reminder.reminderType);
return (
<Card key={reminder.id} className="hover:shadow-sm transition-shadow">
<CardContent className="pt-4">
<div className="flex items-start justify-between">
<div className="flex-1">
<div className="flex items-center gap-2 mb-1">
{type?.icon}
<span className="font-medium">{reminder.title}</span>
</div>
{reminder.message && (
<p className="text-sm text-muted-foreground mb-2">{reminder.message}</p>
)}
<div className="flex items-center gap-3 text-sm">
<span className="flex items-center gap-1 text-primary font-mono">
<Clock className="w-3.5 h-3.5" />
{reminder.timeOfDay}
</span>
<div className="flex gap-0.5">
{DAY_NAMES.map((name, i) => (
<span
key={i}
className={`w-5 h-5 rounded-full text-xs flex items-center justify-center ${
Array.isArray(days) && days.includes(i)
? "bg-primary/10 text-primary font-medium"
: "text-muted-foreground/40"
}`}
>
{name}
</span>
))}
</div>
</div>
</div>
<div className="flex items-center gap-2 ml-2">
<Switch
checked={!!reminder.isActive}
onCheckedChange={checked => toggleReminder.mutate({ reminderId: reminder.id, isActive: checked ? 1 : 0 })}
/>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-destructive hover:text-destructive"
onClick={() => deleteReminder.mutate({ reminderId: reminder.id })}
>
<Trash2 className="w-4 h-4" />
</Button>
</div>
</div>
</CardContent>
</Card>
);
})}
</div>
)}
</div>
{/* Inactive Reminders */}
{inactiveReminders.length > 0 && (
<div>
<h2 className="text-lg font-semibold mb-3 flex items-center gap-2">
<BellOff className="w-5 h-5 text-muted-foreground" />
({inactiveReminders.length})
</h2>
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
{inactiveReminders.map((reminder: any) => {
const days = typeof reminder.daysOfWeek === "string" ? JSON.parse(reminder.daysOfWeek) : reminder.daysOfWeek;
return (
<Card key={reminder.id} className="opacity-60">
<CardContent className="pt-4">
<div className="flex items-start justify-between">
<div>
<span className="font-medium">{reminder.title}</span>
<div className="flex items-center gap-2 text-sm text-muted-foreground mt-1">
<Clock className="w-3.5 h-3.5" />
{reminder.timeOfDay}
</div>
</div>
<div className="flex items-center gap-2">
<Switch
checked={false}
onCheckedChange={checked => toggleReminder.mutate({ reminderId: reminder.id, isActive: checked ? 1 : 0 })}
/>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-destructive hover:text-destructive"
onClick={() => deleteReminder.mutate({ reminderId: reminder.id })}
>
<Trash2 className="w-4 h-4" />
</Button>
</div>
</div>
</CardContent>
</Card>
);
})}
</div>
</div>
)}
<Separator />
{/* Notification History */}
<div>
<div className="flex items-center justify-between mb-3">
<h2 className="text-lg font-semibold flex items-center gap-2">
<Calendar className="w-5 h-5" />
{(unreadCount as number) > 0 && (
<Badge variant="destructive" className="ml-1">{unreadCount as number}</Badge>
)}
</h2>
{(unreadCount as number) > 0 && (
<Button variant="ghost" size="sm" onClick={() => markAllRead.mutate()}>
</Button>
)}
</div>
<ScrollArea className="h-[300px]">
{(!notifications || notifications.length === 0) ? (
<div className="text-center py-8 text-muted-foreground">
<Bell className="w-8 h-8 mx-auto mb-2 opacity-50" />
<p></p>
</div>
) : (
<div className="space-y-2">
{notifications.map((notif: any) => (
<div
key={notif.id}
className={`p-3 rounded-lg border transition-colors cursor-pointer ${
notif.isRead ? "bg-background" : "bg-blue-50 border-blue-200"
}`}
onClick={() => !notif.isRead && markRead.mutate({ notificationId: notif.id })}
>
<div className="flex items-start justify-between">
<div className="flex items-start gap-2">
{notif.isRead ? (
<CheckCircle2 className="w-4 h-4 text-muted-foreground mt-0.5" />
) : (
<BellRing className="w-4 h-4 text-blue-600 mt-0.5" />
)}
<div>
<p className={`text-sm ${notif.isRead ? "" : "font-medium"}`}>{notif.title}</p>
{notif.message && <p className="text-xs text-muted-foreground mt-0.5">{notif.message}</p>}
</div>
</div>
<span className="text-xs text-muted-foreground whitespace-nowrap ml-2">
{new Date(notif.createdAt).toLocaleString("zh-CN", { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" })}
</span>
</div>
</div>
))}
</div>
)}
</ScrollArea>
</div>
</div>
);
}

查看文件

@@ -96,7 +96,7 @@ export default function Training() {
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold tracking-tight"></h1>
<p className="text-muted-foreground text-sm mt-1">AI为您定制的在家网球训练方案</p>
<p className="text-muted-foreground text-sm mt-1">AI个性化训练方案</p>
</div>
</div>
@@ -109,7 +109,7 @@ export default function Training() {
</CardTitle>
<CardDescription>
AI生成个性化的在家训练方案
AI生成个性化训练方案
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">

查看文件

@@ -0,0 +1,320 @@
import { useAuth } from "@/_core/hooks/useAuth";
import { trpc } from "@/lib/trpc";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Textarea } from "@/components/ui/textarea";
import { Progress } from "@/components/ui/progress";
import { ScrollArea } from "@/components/ui/scroll-area";
import { toast } from "sonner";
import { useState, useMemo } from "react";
import {
BookOpen, Play, CheckCircle2, Star, Target,
ChevronRight, Filter, AlertTriangle, Lightbulb,
ArrowUpDown, Clock, Dumbbell
} from "lucide-react";
const CATEGORY_LABELS: Record<string, { label: string; icon: React.ReactNode; color: string }> = {
forehand: { label: "正手", icon: <Target className="w-4 h-4" />, color: "bg-green-100 text-green-700" },
backhand: { label: "反手", icon: <ArrowUpDown className="w-4 h-4" />, color: "bg-blue-100 text-blue-700" },
serve: { label: "发球", icon: <Dumbbell className="w-4 h-4" />, color: "bg-purple-100 text-purple-700" },
volley: { label: "截击", icon: <Target className="w-4 h-4" />, color: "bg-orange-100 text-orange-700" },
footwork: { label: "脚步", icon: <Dumbbell className="w-4 h-4" />, color: "bg-yellow-100 text-yellow-700" },
shadow: { label: "影子挥拍", icon: <Play className="w-4 h-4" />, color: "bg-indigo-100 text-indigo-700" },
wall: { label: "墙壁练习", icon: <Target className="w-4 h-4" />, color: "bg-pink-100 text-pink-700" },
fitness: { label: "体能", icon: <Dumbbell className="w-4 h-4" />, color: "bg-red-100 text-red-700" },
strategy: { label: "战术", icon: <Lightbulb className="w-4 h-4" />, color: "bg-teal-100 text-teal-700" },
};
const SKILL_LABELS: Record<string, { label: string; color: string }> = {
beginner: { label: "初级", color: "bg-emerald-100 text-emerald-700" },
intermediate: { label: "中级", color: "bg-amber-100 text-amber-700" },
advanced: { label: "高级", color: "bg-rose-100 text-rose-700" },
};
export default function Tutorials() {
const { user } = useAuth();
const [selectedCategory, setSelectedCategory] = useState<string>("all");
const [selectedSkill, setSelectedSkill] = useState<string>("all");
const [selectedTutorial, setSelectedTutorial] = useState<number | null>(null);
const [notes, setNotes] = useState("");
const { data: tutorials, isLoading } = trpc.tutorial.list.useQuery({
category: selectedCategory === "all" ? undefined : selectedCategory,
skillLevel: selectedSkill === "all" ? undefined : selectedSkill,
});
const { data: progressData } = trpc.tutorial.progress.useQuery(undefined, { enabled: !!user });
const updateProgress = trpc.tutorial.updateProgress.useMutation({
onSuccess: () => toast.success("进度已更新"),
});
const progressMap = useMemo(() => {
const map: Record<number, any> = {};
progressData?.forEach((p: any) => { map[p.tutorialId] = p; });
return map;
}, [progressData]);
const totalTutorials = tutorials?.length || 0;
const watchedCount = tutorials?.filter((t: any) => progressMap[t.id]?.watched).length || 0;
const progressPercent = totalTutorials > 0 ? Math.round((watchedCount / totalTutorials) * 100) : 0;
const categories = useMemo(() => {
const cats = new Set<string>();
tutorials?.forEach((t: any) => cats.add(t.category));
return Array.from(cats);
}, [tutorials]);
const handleMarkWatched = (tutorialId: number) => {
updateProgress.mutate({ tutorialId, watched: 1 });
};
const handleSaveNotes = (tutorialId: number) => {
updateProgress.mutate({ tutorialId, notes });
setNotes("");
toast.success("笔记已保存");
};
const handleSelfScore = (tutorialId: number, score: number) => {
updateProgress.mutate({ tutorialId, selfScore: score });
};
if (isLoading) {
return (
<div className="flex items-center justify-center min-h-[60vh]">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
</div>
);
}
return (
<div className="space-y-6">
{/* Header */}
<div>
<h1 className="text-2xl font-bold flex items-center gap-2">
<BookOpen className="w-6 h-6 text-primary" />
</h1>
<p className="text-muted-foreground mt-1"></p>
</div>
{/* Progress Overview */}
<Card>
<CardContent className="pt-6">
<div className="flex items-center justify-between mb-2">
<span className="text-sm font-medium"></span>
<span className="text-sm text-muted-foreground">{watchedCount}/{totalTutorials} </span>
</div>
<Progress value={progressPercent} className="h-2" />
<p className="text-xs text-muted-foreground mt-1">{progressPercent}% </p>
</CardContent>
</Card>
{/* Filters */}
<div className="flex flex-wrap gap-3">
<div className="flex items-center gap-2">
<Filter className="w-4 h-4 text-muted-foreground" />
<span className="text-sm font-medium">:</span>
</div>
<div className="flex flex-wrap gap-1.5">
<Button
variant={selectedCategory === "all" ? "default" : "outline"}
size="sm"
onClick={() => setSelectedCategory("all")}
>
</Button>
{Object.entries(CATEGORY_LABELS).map(([key, { label, icon }]) => (
<Button
key={key}
variant={selectedCategory === key ? "default" : "outline"}
size="sm"
onClick={() => setSelectedCategory(key)}
className="gap-1"
>
{icon} {label}
</Button>
))}
</div>
</div>
<div className="flex flex-wrap gap-3">
<div className="flex items-center gap-2">
<Star className="w-4 h-4 text-muted-foreground" />
<span className="text-sm font-medium">:</span>
</div>
<div className="flex gap-1.5">
<Button
variant={selectedSkill === "all" ? "default" : "outline"}
size="sm"
onClick={() => setSelectedSkill("all")}
>
</Button>
{Object.entries(SKILL_LABELS).map(([key, { label }]) => (
<Button
key={key}
variant={selectedSkill === key ? "default" : "outline"}
size="sm"
onClick={() => setSelectedSkill(key)}
>
{label}
</Button>
))}
</div>
</div>
{/* Tutorial Grid */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{tutorials?.map((tutorial: any) => {
const cat = CATEGORY_LABELS[tutorial.category] || { label: tutorial.category, color: "bg-gray-100 text-gray-700" };
const skill = SKILL_LABELS[tutorial.skillLevel] || { label: tutorial.skillLevel, color: "bg-gray-100 text-gray-700" };
const progress = progressMap[tutorial.id];
const isWatched = progress?.watched === 1;
const keyPoints = typeof tutorial.keyPoints === "string" ? JSON.parse(tutorial.keyPoints) : tutorial.keyPoints || [];
const mistakes = typeof tutorial.commonMistakes === "string" ? JSON.parse(tutorial.commonMistakes) : tutorial.commonMistakes || [];
return (
<Dialog key={tutorial.id}>
<DialogTrigger asChild>
<Card className={`cursor-pointer hover:shadow-md transition-all ${isWatched ? "border-green-300 bg-green-50/30" : ""}`}>
<CardHeader className="pb-3">
<div className="flex items-start justify-between">
<div className="flex gap-2 flex-wrap">
<Badge variant="secondary" className={cat.color}>{cat.label}</Badge>
<Badge variant="secondary" className={skill.color}>{skill.label}</Badge>
</div>
{isWatched && <CheckCircle2 className="w-5 h-5 text-green-600 shrink-0" />}
</div>
<CardTitle className="text-base mt-2">{tutorial.title}</CardTitle>
<CardDescription className="line-clamp-2">{tutorial.description}</CardDescription>
</CardHeader>
<CardContent className="pt-0">
<div className="flex items-center justify-between text-xs text-muted-foreground">
<span className="flex items-center gap-1">
<Clock className="w-3 h-3" />
{Math.round((tutorial.duration || 0) / 60)}
</span>
<span className="flex items-center gap-1">
{keyPoints.length}
<ChevronRight className="w-3 h-3" />
</span>
</div>
{progress?.selfScore && (
<div className="flex items-center gap-1 mt-2">
{[1, 2, 3, 4, 5].map(s => (
<Star key={s} className={`w-3 h-3 ${s <= progress.selfScore ? "fill-yellow-400 text-yellow-400" : "text-gray-300"}`} />
))}
<span className="text-xs text-muted-foreground ml-1"></span>
</div>
)}
</CardContent>
</Card>
</DialogTrigger>
<DialogContent className="max-w-2xl max-h-[85vh] overflow-hidden flex flex-col">
<DialogHeader>
<div className="flex gap-2 mb-2">
<Badge variant="secondary" className={cat.color}>{cat.label}</Badge>
<Badge variant="secondary" className={skill.color}>{skill.label}</Badge>
<Badge variant="outline" className="gap-1">
<Clock className="w-3 h-3" />
{Math.round((tutorial.duration || 0) / 60)}
</Badge>
</div>
<DialogTitle className="text-xl">{tutorial.title}</DialogTitle>
</DialogHeader>
<ScrollArea className="flex-1 pr-4">
<div className="space-y-5">
<p className="text-muted-foreground">{tutorial.description}</p>
{/* Key Points */}
<div>
<h3 className="font-semibold flex items-center gap-2 mb-3">
<Lightbulb className="w-4 h-4 text-yellow-500" />
</h3>
<div className="space-y-2">
{keyPoints.map((point: string, i: number) => (
<div key={i} className="flex items-start gap-2 p-2 rounded-lg bg-green-50 border border-green-100">
<CheckCircle2 className="w-4 h-4 text-green-600 mt-0.5 shrink-0" />
<span className="text-sm">{point}</span>
</div>
))}
</div>
</div>
{/* Common Mistakes */}
<div>
<h3 className="font-semibold flex items-center gap-2 mb-3">
<AlertTriangle className="w-4 h-4 text-orange-500" />
</h3>
<div className="space-y-2">
{mistakes.map((mistake: string, i: number) => (
<div key={i} className="flex items-start gap-2 p-2 rounded-lg bg-orange-50 border border-orange-100">
<AlertTriangle className="w-4 h-4 text-orange-500 mt-0.5 shrink-0" />
<span className="text-sm">{mistake}</span>
</div>
))}
</div>
</div>
{/* Self Assessment */}
{user && (
<div>
<h3 className="font-semibold mb-3"></h3>
<div className="flex items-center gap-2 mb-3">
<span className="text-sm text-muted-foreground">:</span>
{[1, 2, 3, 4, 5].map(s => (
<button
key={s}
onClick={() => handleSelfScore(tutorial.id, s)}
className="hover:scale-110 transition-transform"
>
<Star className={`w-6 h-6 ${s <= (progress?.selfScore || 0) ? "fill-yellow-400 text-yellow-400" : "text-gray-300 hover:text-yellow-300"}`} />
</button>
))}
</div>
<Textarea
placeholder="记录学习笔记和心得..."
value={notes || progress?.notes || ""}
onChange={e => setNotes(e.target.value)}
className="mb-2"
rows={3}
/>
<div className="flex gap-2">
<Button size="sm" onClick={() => handleSaveNotes(tutorial.id)}>
</Button>
{!isWatched && (
<Button size="sm" variant="outline" onClick={() => handleMarkWatched(tutorial.id)} className="gap-1">
<CheckCircle2 className="w-4 h-4" />
</Button>
)}
</div>
</div>
)}
</div>
</ScrollArea>
</DialogContent>
</Dialog>
);
})}
</div>
{tutorials?.length === 0 && (
<div className="text-center py-12 text-muted-foreground">
<BookOpen className="w-12 h-12 mx-auto mb-3 opacity-50" />
<p></p>
</div>
)}
</div>
);
}