Add optimized tutorial cover images

这个提交包含在:
cryptocommuniums-afk
2026-03-15 12:01:21 +08:00
父节点 bee24d547d
当前提交 143c60a054
修改 7 个文件,包含 673 行新增242 行删除

查看文件

@@ -16,6 +16,9 @@ FROM node:22-bookworm-slim AS runtime
WORKDIR /app
ENV NODE_ENV=production
RUN corepack enable
RUN apt-get update \
&& apt-get install -y --no-install-recommends ca-certificates ffmpeg \
&& rm -rf /var/lib/apt/lists/*
COPY package.json pnpm-lock.yaml ./
COPY patches ./patches
RUN pnpm install --prod --frozen-lockfile

查看文件

@@ -1,306 +1,441 @@
import { useMemo, useState } from "react";
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 { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
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 { Textarea } from "@/components/ui/textarea";
import { trpc } from "@/lib/trpc";
import { cn } from "@/lib/utils";
import { toast } from "sonner";
import { useState, useMemo } from "react";
import {
BookOpen, Play, CheckCircle2, Star, Target,
ChevronRight, Filter, AlertTriangle, Lightbulb,
ArrowUpDown, Clock, Dumbbell
BookOpen,
CheckCircle2,
ChevronRight,
Clock3,
ExternalLink,
Flame,
Star,
Target,
Trophy,
type LucideIcon,
} 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" },
type TutorialRecord = Record<string, any>;
const CATEGORY_META: Record<string, { label: string; icon: LucideIcon; tone: string }> = {
forehand: { label: "正手", icon: Target, tone: "bg-green-500/10 text-green-700" },
backhand: { label: "反手", icon: Target, tone: "bg-blue-500/10 text-blue-700" },
serve: { label: "发球", icon: Target, tone: "bg-violet-500/10 text-violet-700" },
volley: { label: "截击", icon: Target, tone: "bg-orange-500/10 text-orange-700" },
footwork: { label: "脚步", icon: Flame, tone: "bg-yellow-500/10 text-yellow-700" },
shadow: { label: "影子挥拍", icon: BookOpen, tone: "bg-indigo-500/10 text-indigo-700" },
wall: { label: "墙壁练习", icon: Target, tone: "bg-pink-500/10 text-pink-700" },
fitness: { label: "体能", icon: Flame, tone: "bg-rose-500/10 text-rose-700" },
strategy: { label: "战术", icon: Trophy, tone: "bg-teal-500/10 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" },
const SKILL_META: Record<string, { label: string; tone: string }> = {
beginner: { label: "初级", tone: "bg-emerald-500/10 text-emerald-700" },
intermediate: { label: "中级", tone: "bg-amber-500/10 text-amber-700" },
advanced: { label: "高级", tone: "bg-rose-500/10 text-rose-700" },
};
function parseStringArray(value: unknown) {
if (Array.isArray(value)) {
return value.filter((item): item is string => typeof item === "string");
}
if (typeof value === "string") {
try {
const parsed = JSON.parse(value);
return Array.isArray(parsed) ? parsed.filter((item): item is string => typeof item === "string") : [];
} catch {
return [];
}
}
return [];
}
function isTutorialCompleted(progress: TutorialRecord | undefined) {
return progress?.completed === 1 || progress?.watched === 1;
}
function formatEffortMinutes(tutorial: TutorialRecord) {
const effort = tutorial.estimatedEffortMinutes || (tutorial.duration ? Math.round(tutorial.duration / 60) : 0);
return effort > 0 ? `${effort} 分钟` : "按需学习";
}
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 utils = trpc.useUtils();
const [selectedCategory, setSelectedCategory] = useState("all");
const [selectedSkill, setSelectedSkill] = useState("all");
const [draftNotes, setDraftNotes] = useState<Record<number, string>>({});
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 tutorialsQuery = trpc.tutorial.list.useQuery({ topicArea: "tennis_skill" });
const progressQuery = trpc.tutorial.progress.useQuery(undefined, { enabled: !!user });
const updateProgress = trpc.tutorial.updateProgress.useMutation({
onSuccess: () => toast.success("进度已更新"),
onSuccess: async () => {
await utils.tutorial.progress.invalidate();
toast.success("教程进度已更新");
},
});
const tutorials = tutorialsQuery.data ?? [];
const progressMap = useMemo(() => {
const map: Record<number, any> = {};
progressData?.forEach((p: any) => { map[p.tutorialId] = p; });
const map: Record<number, TutorialRecord> = {};
(progressQuery.data ?? []).forEach((item: TutorialRecord) => {
map[item.tutorialId] = item;
});
return map;
}, [progressData]);
}, [progressQuery.data]);
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 filteredTutorials = useMemo(
() => tutorials.filter((tutorial) => {
if (selectedCategory !== "all" && tutorial.category !== selectedCategory) return false;
if (selectedSkill !== "all" && tutorial.skillLevel !== selectedSkill) return false;
return true;
}),
[selectedCategory, selectedSkill, tutorials],
);
const categories = useMemo(() => {
const cats = new Set<string>();
tutorials?.forEach((t: any) => cats.add(t.category));
return Array.from(cats);
}, [tutorials]);
const categories = useMemo(
() => Array.from(new Set(tutorials.map((tutorial) => tutorial.category).filter(Boolean))),
[tutorials],
);
const handleMarkWatched = (tutorialId: number) => {
updateProgress.mutate({ tutorialId, watched: 1 });
};
const completedTutorials = useMemo(
() => tutorials.filter((tutorial) => isTutorialCompleted(progressMap[tutorial.id])),
[progressMap, tutorials],
);
const handleSaveNotes = (tutorialId: number) => {
const notes = draftNotes[tutorialId] ?? progressMap[tutorialId]?.notes ?? "";
updateProgress.mutate({ tutorialId, notes });
setNotes("");
toast.success("笔记已保存");
};
const handleComplete = (tutorialId: number) => {
updateProgress.mutate({ tutorialId, completed: 1, watched: 1 });
};
const handleSelfScore = (tutorialId: number, score: number) => {
updateProgress.mutate({ tutorialId, selfScore: score });
};
if (isLoading) {
if (tutorialsQuery.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 className="flex min-h-[60vh] items-center justify-center">
<div className="h-8 w-8 animate-spin rounded-full border-b-2 border-primary" />
</div>
);
}
return (
<div className="space-y-6">
{/* Header */}
<section className="overflow-hidden rounded-[30px] border border-border/60 bg-[radial-gradient(circle_at_top_left,_rgba(34,197,94,0.18),_transparent_24%),radial-gradient(circle_at_82%_18%,_rgba(59,130,246,0.14),_transparent_24%),linear-gradient(135deg,rgba(255,255,255,0.98),rgba(248,250,252,0.96))] p-5 shadow-sm md:p-7">
<div className="grid gap-4 xl:grid-cols-[minmax(0,1.2fr)_360px]">
<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 className="flex flex-wrap items-center gap-2">
<Badge className="bg-emerald-500/10 text-emerald-700">
<BookOpen className="mr-1 h-3 w-3" />
</Badge>
<Badge variant="outline"></Badge>
</div>
<h1 className="mt-4 text-3xl font-semibold tracking-tight"></h1>
<p className="mt-3 max-w-3xl text-sm leading-7 text-muted-foreground">
</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>
<div className="grid gap-3 sm:grid-cols-3 xl:grid-cols-1">
<Card className="border-0 bg-background/90 shadow-sm">
<CardHeader className="pb-2">
<CardDescription></CardDescription>
<CardTitle className="text-3xl">{tutorials.length}</CardTitle>
</CardHeader>
</Card>
<Card className="border-0 bg-background/90 shadow-sm">
<CardHeader className="pb-2">
<CardDescription></CardDescription>
<CardTitle className="text-3xl">{completedTutorials.length}</CardTitle>
</CardHeader>
</Card>
<Card className="border-0 bg-background/90 shadow-sm">
<CardHeader className="pb-2">
<CardDescription></CardDescription>
<CardTitle className="text-base">
{selectedCategory === "all" ? "全部分类" : (CATEGORY_META[selectedCategory] || { label: selectedCategory }).label}
{" · "}
{selectedSkill === "all" ? "全部级别" : (SKILL_META[selectedSkill] || { label: selectedSkill }).label}
</CardTitle>
</CardHeader>
</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">
</div>
</section>
<section className="space-y-5">
<div className="flex flex-col gap-3 lg:flex-row lg:items-end lg:justify-between">
<div>
<h2 className="text-xl font-semibold tracking-tight"></h2>
<p className="mt-1 text-sm text-muted-foreground"></p>
</div>
<div className="rounded-2xl border border-border/60 bg-background/85 px-4 py-3 text-sm text-muted-foreground">
{completedTutorials.length}/{tutorials.length}
</div>
</div>
<div className="flex flex-wrap gap-3">
<div className="flex flex-wrap gap-2">
<Button
variant={selectedCategory === "all" ? "default" : "outline"}
size="sm"
onClick={() => setSelectedCategory("all")}
>
</Button>
{Object.entries(CATEGORY_LABELS).map(([key, { label, icon }]) => (
{categories.map((category) => (
<Button
key={key}
variant={selectedCategory === key ? "default" : "outline"}
key={category}
variant={selectedCategory === category ? "default" : "outline"}
size="sm"
onClick={() => setSelectedCategory(key)}
className="gap-1"
onClick={() => setSelectedCategory(category)}
>
{icon} {label}
{(CATEGORY_META[category] || { label: category }).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">
<div className="flex flex-wrap gap-2">
<Button
variant={selectedSkill === "all" ? "default" : "outline"}
size="sm"
onClick={() => setSelectedSkill("all")}
>
</Button>
{Object.entries(SKILL_LABELS).map(([key, { label }]) => (
{Object.entries(SKILL_META).map(([key, meta]) => (
<Button
key={key}
variant={selectedSkill === key ? "default" : "outline"}
size="sm"
onClick={() => setSelectedSkill(key)}
>
{label}
{meta.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" };
<div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
{filteredTutorials.map((tutorial) => {
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 || [];
const completed = isTutorialCompleted(progress);
const category = CATEGORY_META[tutorial.category || "forehand"] || CATEGORY_META.forehand;
const skill = SKILL_META[tutorial.skillLevel || "beginner"] || SKILL_META.beginner;
const keyPoints = parseStringArray(tutorial.keyPoints);
const commonMistakes = parseStringArray(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>
<Card className={cn(
"overflow-hidden border-0 shadow-sm transition-shadow hover:shadow-md",
completed && "ring-1 ring-emerald-200",
)}>
<div className="relative h-48 overflow-hidden bg-[radial-gradient(circle_at_top_left,_rgba(34,197,94,0.28),_transparent_30%),radial-gradient(circle_at_bottom_right,_rgba(59,130,246,0.18),_transparent_28%),linear-gradient(135deg,rgba(255,255,255,1),rgba(248,250,252,0.92))] px-5 py-4">
{tutorial.thumbnailUrl ? (
<>
<img
src={tutorial.thumbnailUrl}
alt={`${tutorial.title} 标准配图`}
loading="lazy"
className="absolute inset-0 h-full w-full object-cover"
/>
<div className="absolute inset-0 bg-[linear-gradient(180deg,rgba(15,23,42,0.18),rgba(15,23,42,0.58))]" />
</>
) : null}
<div className="relative flex items-start justify-between gap-3">
<div className="flex flex-wrap gap-2">
<Badge className={category.tone}>{category.label}</Badge>
<Badge className={skill.tone}>{skill.label}</Badge>
</div>
{isWatched && <CheckCircle2 className="w-5 h-5 text-green-600 shrink-0" />}
{completed ? <CheckCircle2 className="h-5 w-5 text-emerald-600" /> : null}
</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="relative mt-6">
<div className={cn("text-xl font-semibold", tutorial.thumbnailUrl && "text-white drop-shadow-sm")}>{tutorial.title}</div>
<div className={cn(
"mt-2 line-clamp-2 text-sm leading-6",
tutorial.thumbnailUrl ? "text-white/88 drop-shadow-sm" : "text-muted-foreground",
)}>
{tutorial.description}
</div>
</div>
</div>
<CardContent className="p-5">
<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 className="inline-flex items-center gap-1">
<Clock3 className="h-3.5 w-3.5" />
{formatEffortMinutes(tutorial)}
</span>
<span>{keyPoints.length} </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>
{progress?.selfScore ? (
<div className="mt-3 flex items-center gap-1">
{[1, 2, 3, 4, 5].map((score) => (
<Star
key={score}
className={cn(
"h-4 w-4",
score <= progress.selfScore ? "fill-yellow-400 text-yellow-400" : "text-slate-300",
)}
/>
))}
</div>
) : null}
<DialogTrigger asChild>
<Button variant="outline" className="mt-4 w-full"></Button>
</DialogTrigger>
</CardContent>
</Card>
</DialogTrigger>
<DialogContent className="max-w-2xl max-h-[85vh] overflow-hidden flex flex-col">
<DialogContent className="max-h-[85vh] max-w-2xl overflow-hidden">
<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 className="flex flex-wrap gap-2">
<Badge className={category.tone}>{category.label}</Badge>
<Badge className={skill.tone}>{skill.label}</Badge>
</div>
<DialogTitle className="text-xl">{tutorial.title}</DialogTitle>
</DialogHeader>
<ScrollArea className="flex-1 pr-4">
<ScrollArea className="max-h-[68vh] pr-4">
<div className="space-y-5">
<p className="text-muted-foreground">{tutorial.description}</p>
{tutorial.thumbnailUrl ? (
<div className="overflow-hidden rounded-[24px] border border-border/60 bg-muted/20">
<img
src={tutorial.thumbnailUrl}
alt={`${tutorial.title} 标准配图`}
loading="lazy"
className="h-64 w-full object-cover sm:h-80"
/>
</div>
) : null}
{/* 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>
<p className="text-sm leading-7 text-muted-foreground">{tutorial.description}</p>
{/* 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"
{tutorial.externalUrl ? (
<div className="flex flex-wrap items-center gap-2 rounded-2xl border border-border/60 bg-muted/20 px-4 py-3 text-sm text-muted-foreground">
<span></span>
<a
href={tutorial.externalUrl}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 font-medium text-primary underline-offset-4 hover:underline"
>
<Star className={`w-6 h-6 ${s <= (progress?.selfScore || 0) ? "fill-yellow-400 text-yellow-400" : "text-gray-300 hover:text-yellow-300"}`} />
Wikimedia Commons
<ExternalLink className="h-3.5 w-3.5" />
</a>
</div>
) : null}
<div>
<h4 className="text-sm font-semibold uppercase tracking-[0.24em] text-muted-foreground"></h4>
<div className="mt-3 space-y-2">
{keyPoints.map((item) => (
<div key={item} className="rounded-2xl border border-emerald-200 bg-emerald-50/70 px-4 py-3 text-sm">
{item}
</div>
))}
</div>
</div>
<div>
<h4 className="text-sm font-semibold uppercase tracking-[0.24em] text-muted-foreground"></h4>
<div className="mt-3 space-y-2">
{commonMistakes.map((item) => (
<div key={item} className="rounded-2xl border border-amber-200 bg-amber-50/70 px-4 py-3 text-sm">
{item}
</div>
))}
</div>
</div>
{user ? (
<div className="rounded-[24px] border border-border/60 bg-muted/20 p-5">
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<div className="text-base font-semibold"></div>
<div className="mt-1 text-sm text-muted-foreground"></div>
</div>
{!completed ? (
<Button size="sm" onClick={() => handleComplete(tutorial.id)}>
<CheckCircle2 className="h-4 w-4" />
</Button>
) : (
<Badge className="bg-emerald-500/10 text-emerald-700">
<CheckCircle2 className="mr-1 h-3 w-3" />
</Badge>
)}
</div>
<div className="mt-5">
<div className="mb-2 text-sm font-medium"></div>
<div className="flex items-center gap-2">
{[1, 2, 3, 4, 5].map((score) => (
<button
key={score}
onClick={() => handleSelfScore(tutorial.id, score)}
className="transition-transform hover:scale-110"
>
<Star className={cn(
"h-6 w-6",
score <= (progress?.selfScore || 0) ? "fill-yellow-400 text-yellow-400" : "text-slate-300",
)} />
</button>
))}
</div>
</div>
<div className="mt-5">
<div className="mb-2 text-sm font-medium"></div>
<Textarea
placeholder="记录学习笔记和心得..."
value={notes || progress?.notes || ""}
onChange={e => setNotes(e.target.value)}
className="mb-2"
rows={3}
rows={4}
placeholder="记录今天的挥拍体感、移动节奏、失误原因和下次训练目标。"
value={draftNotes[tutorial.id] ?? progress?.notes ?? ""}
onChange={(event) => setDraftNotes((current) => ({
...current,
[tutorial.id]: event.target.value,
}))}
/>
<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 className="mt-3 flex gap-2">
<Button size="sm" onClick={() => handleSaveNotes(tutorial.id)}></Button>
</div>
</div>
)}
</div>
) : null}
{keyPoints.length > 0 ? (
<div>
<h4 className="text-sm font-semibold uppercase tracking-[0.24em] text-muted-foreground"></h4>
<div className="mt-3 space-y-2">
{keyPoints.slice(0, 3).map((item) => (
<div key={item} className="flex items-start gap-2 rounded-2xl bg-muted/20 px-4 py-3 text-sm">
<ChevronRight className="mt-0.5 h-4 w-4 shrink-0 text-primary" />
<span>{item}</span>
</div>
))}
</div>
</div>
) : null}
</div>
</ScrollArea>
</DialogContent>
@@ -309,12 +444,12 @@ export default function Tutorials() {
})}
</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>
{filteredTutorials.length === 0 ? (
<div className="rounded-[26px] border border-dashed border-border/60 px-6 py-14 text-center text-muted-foreground">
</div>
)}
) : null}
</section>
</div>
);
}

查看文件

@@ -1,6 +1,6 @@
# Verified Features
本文档记录当前已经通过自动化验证或构建验证的项目。更新时间2026-03-15 11:28 CST。
本文档记录当前已经通过自动化验证或构建验证的项目。更新时间2026-03-15 11:58 CST。
## 最新完整验证记录
@@ -16,6 +16,7 @@
| `https://te.hao.work/` HTTPS 访问 | `curl -I https://te.hao.work/` | 通过 |
| `https://te.hao.work/checkin` 成就系统路由 | Playwright 登录后检查“成就系统” | 通过 |
| `https://te.hao.work/tutorials` 教程库清洗 | Playwright smoke + `tutorial.list` 线上接口校验,仅返回 `topicArea=tennis_skill` 的 11 条网球教程 | 通过 |
| `https://te.hao.work/tutorials` 教程标准配图 | 登录后 Playwright 检查 11 张压缩配图渲染、首图为 `/uploads/tutorials/forehand-fundamentals.webp`,并验证图片资源 `200 OK` | 通过 |
| `https://te.hao.work/logs` 日志页访问 | `curl -I https://te.hao.work/logs` | 通过 |
| `https://te.hao.work/vision-lab` 视觉测试页访问 | `curl -I https://te.hao.work/vision-lab` | 通过 |
| `http://te.hao.work:8302/` 4 位端口访问 | `curl -I http://te.hao.work:8302/` | 通过 |

查看文件

@@ -11,6 +11,7 @@ import { registerMediaProxy } from "./mediaProxy";
import { serveStatic } from "./static";
import { createBackgroundTask, getAdminUserId, hasRecentBackgroundTaskOfType, seedAchievementDefinitions, seedAppSettings, seedTutorials, seedVisionReferenceImages } from "../db";
import { nanoid } from "nanoid";
import { syncTutorialImages } from "../tutorialImages";
async function scheduleDailyNtrpRefresh() {
const now = new Date();
@@ -64,6 +65,7 @@ async function findAvailablePort(startPort: number = 3000): Promise<number> {
async function startServer() {
await seedTutorials();
await syncTutorialImages();
await seedVisionReferenceImages();
await seedAchievementDefinitions();
await seedAppSettings();

查看文件

@@ -0,0 +1,69 @@
export type TutorialImageSpec = {
imageUrl: string;
sourcePageUrl: string;
sourceLabel: string;
};
export const TUTORIAL_IMAGE_LIBRARY = {
forehand: {
imageUrl: "https://upload.wikimedia.org/wikipedia/commons/0/00/Ray_Dunlop_forehand.jpg",
sourcePageUrl: "https://commons.wikimedia.org/wiki/File:Ray_Dunlop_forehand.jpg",
sourceLabel: "Wikimedia Commons",
},
backhand: {
imageUrl: "https://upload.wikimedia.org/wikipedia/commons/8/8c/Backhand_Federer.jpg",
sourcePageUrl: "https://commons.wikimedia.org/wiki/File:Backhand_Federer.jpg",
sourceLabel: "Wikimedia Commons",
},
serve: {
imageUrl: "https://upload.wikimedia.org/wikipedia/commons/8/85/Serena_Williams_Serves.JPG",
sourcePageUrl: "https://commons.wikimedia.org/wiki/File:Serena_Williams_Serves.JPG",
sourceLabel: "Wikimedia Commons",
},
volley: {
imageUrl: "https://upload.wikimedia.org/wikipedia/commons/a/af/Ernest_w._lewis%2C_volleying.jpg",
sourcePageUrl: "https://commons.wikimedia.org/wiki/File:Ernest_w._lewis,_volleying.jpg",
sourceLabel: "Wikimedia Commons",
},
action: {
imageUrl: "https://upload.wikimedia.org/wikipedia/commons/3/34/Frances_Tiafoe_Backhand.jpg",
sourcePageUrl: "https://commons.wikimedia.org/wiki/File:Frances_Tiafoe_Backhand.jpg",
sourceLabel: "Wikimedia Commons",
},
wall: {
imageUrl: "https://upload.wikimedia.org/wikipedia/commons/2/2c/Tennis_wall.jpg",
sourcePageUrl: "https://commons.wikimedia.org/wiki/File:Tennis_wall.jpg",
sourceLabel: "Wikimedia Commons",
},
strategy: {
imageUrl: "https://upload.wikimedia.org/wikipedia/commons/f/f3/Court_plan.png",
sourcePageUrl: "https://commons.wikimedia.org/wiki/File:Court_plan.png",
sourceLabel: "Wikimedia Commons",
},
} satisfies Record<string, TutorialImageSpec>;
const CATEGORY_TO_IMAGE: Record<string, keyof typeof TUTORIAL_IMAGE_LIBRARY> = {
forehand: "forehand",
backhand: "backhand",
serve: "serve",
volley: "volley",
footwork: "action",
shadow: "forehand",
wall: "wall",
fitness: "action",
strategy: "strategy",
};
export function buildTutorialImageKey(slug: string) {
return `tutorials/${slug}.webp`;
}
export function buildTutorialImageUrl(slug: string) {
return `/uploads/${buildTutorialImageKey(slug)}`;
}
export function getTutorialImageSpec(category: string): TutorialImageSpec | null {
const imageKey = CATEGORY_TO_IMAGE[category];
if (!imageKey) return null;
return TUTORIAL_IMAGE_LIBRARY[imageKey];
}

查看文件

@@ -0,0 +1,43 @@
import { describe, expect, it } from "vitest";
import {
buildTutorialImageFfmpegArgs,
buildTutorialImageKey,
buildTutorialImageUrl,
getTutorialImageSpec,
} from "./tutorialImages";
describe("tutorialImages", () => {
it("maps tennis categories to image specs", () => {
expect(getTutorialImageSpec("forehand")?.sourcePageUrl).toContain("Ray_Dunlop_forehand");
expect(getTutorialImageSpec("backhand")?.sourcePageUrl).toContain("Backhand_Federer");
expect(getTutorialImageSpec("serve")?.sourcePageUrl).toContain("Serena_Williams_Serves");
expect(getTutorialImageSpec("wall")?.sourcePageUrl).toContain("Tennis_wall");
expect(getTutorialImageSpec("unknown")).toBeNull();
});
it("builds stable storage keys and public URLs", () => {
expect(buildTutorialImageKey("forehand-fundamentals")).toBe("tutorials/forehand-fundamentals.webp");
expect(buildTutorialImageUrl("forehand-fundamentals")).toBe("/uploads/tutorials/forehand-fundamentals.webp");
});
it("uses a fixed compression pipeline for tutorial images", () => {
const args = buildTutorialImageFfmpegArgs("/tmp/input.jpg", "/tmp/output.webp");
expect(args).toEqual([
"-y",
"-i",
"/tmp/input.jpg",
"-vf",
"scale=1200:675:force_original_aspect_ratio=increase,crop=1200:675",
"-frames:v",
"1",
"-c:v",
"libwebp",
"-quality",
"78",
"-compression_level",
"6",
"/tmp/output.webp",
]);
});
});

178
server/tutorialImages.ts 普通文件
查看文件

@@ -0,0 +1,178 @@
import { execFile } from "node:child_process";
import { access, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { promisify } from "node:util";
import { and, asc, eq } from "drizzle-orm";
import { tutorialVideos } from "../drizzle/schema";
import { getDb } from "./db";
import { ENV } from "./_core/env";
import { storagePut } from "./storage";
import {
buildTutorialImageKey,
buildTutorialImageUrl,
getTutorialImageSpec,
type TutorialImageSpec,
} from "./tutorialImageCatalog";
export { buildTutorialImageKey, buildTutorialImageUrl, getTutorialImageSpec } from "./tutorialImageCatalog";
const execFileAsync = promisify(execFile);
const OUTPUT_WIDTH = 1200;
const OUTPUT_HEIGHT = 675;
const OUTPUT_QUALITY = 78;
const OUTPUT_COMPRESSION_LEVEL = 6;
type TutorialRow = {
id: number;
slug: string | null;
category: string;
title: string;
thumbnailUrl: string | null;
externalUrl: string | null;
sourcePlatform: string | null;
};
function normalizeSlug(slug: string | null, tutorialId: number) {
return slug?.trim() ? slug.trim() : `tutorial-${tutorialId}`;
}
export function buildTutorialImageFfmpegArgs(inputPath: string, outputPath: string) {
return [
"-y",
"-i",
inputPath,
"-vf",
`scale=${OUTPUT_WIDTH}:${OUTPUT_HEIGHT}:force_original_aspect_ratio=increase,crop=${OUTPUT_WIDTH}:${OUTPUT_HEIGHT}`,
"-frames:v",
"1",
"-c:v",
"libwebp",
"-quality",
`${OUTPUT_QUALITY}`,
"-compression_level",
`${OUTPUT_COMPRESSION_LEVEL}`,
outputPath,
];
}
function isTutorialImageCurrent(tutorial: TutorialRow, spec: TutorialImageSpec, expectedUrl: string) {
return tutorial.thumbnailUrl === expectedUrl
&& tutorial.externalUrl === spec.sourcePageUrl
&& tutorial.sourcePlatform === "wikimedia";
}
function canUseRemoteStorage() {
return Boolean(ENV.forgeApiUrl && ENV.forgeApiKey);
}
async function localAssetExists(slug: string) {
const filePath = path.join(ENV.localStorageDir, buildTutorialImageKey(slug));
try {
await access(filePath);
return true;
} catch {
return false;
}
}
async function downloadSourceImage(url: string) {
const response = await fetch(url, {
headers: {
"accept": "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8",
"user-agent": "tennis-training-hub/1.0 (+https://te.hao.work/)",
},
});
if (!response.ok) {
throw new Error(`Image download failed (${response.status}): ${url}`);
}
const contentType = response.headers.get("content-type") || "";
if (!contentType.startsWith("image/")) {
throw new Error(`Unexpected image content-type: ${contentType || "unknown"}`);
}
return Buffer.from(await response.arrayBuffer());
}
async function normalizeTutorialImage(buffer: Buffer) {
const tempDir = await mkdtemp(path.join(os.tmpdir(), "tutorial-image-"));
const inputPath = path.join(tempDir, "source.input");
const outputPath = path.join(tempDir, "tutorial.webp");
try {
await writeFile(inputPath, buffer);
await execFileAsync("ffmpeg", buildTutorialImageFfmpegArgs(inputPath, outputPath), {
timeout: 30_000,
maxBuffer: 8 * 1024 * 1024,
});
return await readFile(outputPath);
} finally {
await rm(tempDir, { recursive: true, force: true });
}
}
export async function syncTutorialImages() {
const db = await getDb();
if (!db) return { updated: 0, skipped: 0, failed: 0 };
const tutorials = await db.select({
id: tutorialVideos.id,
slug: tutorialVideos.slug,
category: tutorialVideos.category,
title: tutorialVideos.title,
thumbnailUrl: tutorialVideos.thumbnailUrl,
externalUrl: tutorialVideos.externalUrl,
sourcePlatform: tutorialVideos.sourcePlatform,
}).from(tutorialVideos)
.where(and(eq(tutorialVideos.topicArea, "tennis_skill"), eq(tutorialVideos.isPublished, 1)))
.orderBy(asc(tutorialVideos.sortOrder), asc(tutorialVideos.id));
let updated = 0;
let skipped = 0;
let failed = 0;
for (const tutorial of tutorials) {
const spec = getTutorialImageSpec(tutorial.category);
if (!spec) {
skipped += 1;
continue;
}
const slug = normalizeSlug(tutorial.slug, tutorial.id);
const expectedUrl = buildTutorialImageUrl(slug);
const assetExists = await localAssetExists(slug);
if (canUseRemoteStorage() && tutorial.thumbnailUrl && tutorial.externalUrl === spec.sourcePageUrl && tutorial.sourcePlatform === "wikimedia") {
skipped += 1;
continue;
}
if (assetExists && isTutorialImageCurrent(tutorial, spec, expectedUrl)) {
skipped += 1;
continue;
}
try {
const sourceBuffer = await downloadSourceImage(spec.imageUrl);
const webpBuffer = await normalizeTutorialImage(sourceBuffer);
const stored = await storagePut(buildTutorialImageKey(slug), webpBuffer, "image/webp");
await db.update(tutorialVideos).set({
thumbnailUrl: stored.url,
externalUrl: spec.sourcePageUrl,
sourcePlatform: "wikimedia",
}).where(eq(tutorialVideos.id, tutorial.id));
updated += 1;
} catch (error) {
failed += 1;
console.error(`[TutorialImages] Failed to sync ${tutorial.title}:`, error);
}
}
console.log(`[TutorialImages] sync complete: updated=${updated} skipped=${skipped} failed=${failed}`);
return { updated, skipped, failed };
}