feat: monorepo 重构 + 新增 5 个平台适配器
项目从单体结构重构为 pnpm monorepo (shared/backend/frontend), 新增 YouTube、Instagram、Twitter/X、哔哩哔哩、微博 5 个平台适配器, 包含完整的单元测试和 E2E 测试覆盖。 - 完成 T-031~T-044: 5 个适配器实现、注册、配置和测试 - 重构前后端分离: Hono 后端 + Next.js 前端 - 151 个单元测试 + 21 个 Mock E2E + 25 个真实 E2E - 适配器基于真实 TikHub API 响应结构实现 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
"use client";
|
||||
|
||||
import { use } from "react";
|
||||
import { useDetailQuery } from "@/hooks/useDetailQuery";
|
||||
import { DetailPanel } from "@/components/detail/DetailPanel";
|
||||
import { DetailSkeleton } from "@/components/detail/DetailSkeleton";
|
||||
import { ArrowLeft, RefreshCw } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
|
||||
interface DetailPageProps {
|
||||
params: Promise<{ platform: string; id: string }>;
|
||||
}
|
||||
|
||||
export default function DetailPage({ params }: DetailPageProps) {
|
||||
const { platform, id } = use(params);
|
||||
const decodedId = decodeURIComponent(id);
|
||||
const { data, isLoading, isError, error, refetch } = useDetailQuery(
|
||||
platform,
|
||||
decodedId
|
||||
);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="px-4 py-6">
|
||||
<DetailSkeleton />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (isError || !data) {
|
||||
return (
|
||||
<div className="px-4 py-6">
|
||||
<div className="max-w-3xl mx-auto text-center py-20">
|
||||
<p className="text-4xl mb-4">😵</p>
|
||||
<h2 className="text-lg font-medium text-slate-700 mb-2">
|
||||
加载失败
|
||||
</h2>
|
||||
<p className="text-sm text-slate-500 mb-6">
|
||||
{error?.message || "无法获取内容详情"}
|
||||
</p>
|
||||
<div className="flex items-center justify-center gap-3">
|
||||
<button
|
||||
onClick={() => refetch()}
|
||||
className="inline-flex items-center gap-1.5 px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 transition-colors"
|
||||
>
|
||||
<RefreshCw className="w-4 h-4" />
|
||||
重试
|
||||
</button>
|
||||
<Link
|
||||
href="/"
|
||||
className="inline-flex items-center gap-1.5 px-4 py-2 text-sm font-medium text-slate-600 border border-slate-200 rounded-lg hover:bg-slate-50 transition-colors"
|
||||
>
|
||||
<ArrowLeft className="w-4 h-4" />
|
||||
返回首页
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="px-4 py-6">
|
||||
<DetailPanel item={data} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
@@ -0,0 +1,50 @@
|
||||
"use client";
|
||||
|
||||
import { useFavoritesStore } from "@/stores/favorites";
|
||||
import { ContentGrid } from "@/components/card/ContentGrid";
|
||||
import Link from "next/link";
|
||||
import { ArrowLeft } from "lucide-react";
|
||||
|
||||
export default function FavoritesPage() {
|
||||
const favorites = useFavoritesStore((s) => s.items);
|
||||
|
||||
return (
|
||||
<div className="px-4 py-4">
|
||||
<div className="flex items-center gap-3 mb-4">
|
||||
<Link
|
||||
href="/"
|
||||
className="inline-flex items-center gap-1 text-sm text-slate-500 hover:text-slate-700 transition-colors"
|
||||
>
|
||||
<ArrowLeft className="w-4 h-4" />
|
||||
返回
|
||||
</Link>
|
||||
<h1 className="text-lg font-semibold text-slate-800">
|
||||
我的收藏
|
||||
</h1>
|
||||
<span data-testid="favorites-count" className="text-sm text-slate-400">
|
||||
{favorites.length} 个内容
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{favorites.length === 0 ? (
|
||||
<div className="text-center py-20">
|
||||
<p className="text-4xl mb-4">💝</p>
|
||||
<h2 className="text-lg font-medium text-slate-700 mb-2">
|
||||
还没有收藏
|
||||
</h2>
|
||||
<p className="text-sm text-slate-500 mb-4">
|
||||
浏览热门内容,点击心形按钮收藏
|
||||
</p>
|
||||
<Link
|
||||
href="/"
|
||||
className="inline-flex items-center gap-1.5 px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 transition-colors"
|
||||
>
|
||||
去发现
|
||||
</Link>
|
||||
</div>
|
||||
) : (
|
||||
<ContentGrid items={favorites} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
@import "tailwindcss";
|
||||
@import "tw-animate-css";
|
||||
@import "shadcn/tailwind.css";
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--font-sans: var(--font-geist-sans);
|
||||
--font-mono: var(--font-geist-mono);
|
||||
--color-sidebar-ring: var(--sidebar-ring);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
--color-sidebar-accent: var(--sidebar-accent);
|
||||
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||
--color-sidebar-primary: var(--sidebar-primary);
|
||||
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||
--color-sidebar: var(--sidebar);
|
||||
--color-chart-5: var(--chart-5);
|
||||
--color-chart-4: var(--chart-4);
|
||||
--color-chart-3: var(--chart-3);
|
||||
--color-chart-2: var(--chart-2);
|
||||
--color-chart-1: var(--chart-1);
|
||||
--color-ring: var(--ring);
|
||||
--color-input: var(--input);
|
||||
--color-border: var(--border);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-card: var(--card);
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) + 4px);
|
||||
--radius-2xl: calc(var(--radius) + 8px);
|
||||
--radius-3xl: calc(var(--radius) + 12px);
|
||||
--radius-4xl: calc(var(--radius) + 16px);
|
||||
}
|
||||
|
||||
:root {
|
||||
--radius: 0.625rem;
|
||||
--background: oklch(1 0 0);
|
||||
--foreground: oklch(0.145 0 0);
|
||||
--card: oklch(1 0 0);
|
||||
--card-foreground: oklch(0.145 0 0);
|
||||
--popover: oklch(1 0 0);
|
||||
--popover-foreground: oklch(0.145 0 0);
|
||||
--primary: oklch(0.205 0 0);
|
||||
--primary-foreground: oklch(0.985 0 0);
|
||||
--secondary: oklch(0.97 0 0);
|
||||
--secondary-foreground: oklch(0.205 0 0);
|
||||
--muted: oklch(0.97 0 0);
|
||||
--muted-foreground: oklch(0.556 0 0);
|
||||
--accent: oklch(0.97 0 0);
|
||||
--accent-foreground: oklch(0.205 0 0);
|
||||
--destructive: oklch(0.577 0.245 27.325);
|
||||
--border: oklch(0.922 0 0);
|
||||
--input: oklch(0.922 0 0);
|
||||
--ring: oklch(0.708 0 0);
|
||||
--chart-1: oklch(0.646 0.222 41.116);
|
||||
--chart-2: oklch(0.6 0.118 184.704);
|
||||
--chart-3: oklch(0.398 0.07 227.392);
|
||||
--chart-4: oklch(0.828 0.189 84.429);
|
||||
--chart-5: oklch(0.769 0.188 70.08);
|
||||
--sidebar: oklch(0.985 0 0);
|
||||
--sidebar-foreground: oklch(0.145 0 0);
|
||||
--sidebar-primary: oklch(0.205 0 0);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.97 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.205 0 0);
|
||||
--sidebar-border: oklch(0.922 0 0);
|
||||
--sidebar-ring: oklch(0.708 0 0);
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: oklch(0.145 0 0);
|
||||
--foreground: oklch(0.985 0 0);
|
||||
--card: oklch(0.205 0 0);
|
||||
--card-foreground: oklch(0.985 0 0);
|
||||
--popover: oklch(0.205 0 0);
|
||||
--popover-foreground: oklch(0.985 0 0);
|
||||
--primary: oklch(0.922 0 0);
|
||||
--primary-foreground: oklch(0.205 0 0);
|
||||
--secondary: oklch(0.269 0 0);
|
||||
--secondary-foreground: oklch(0.985 0 0);
|
||||
--muted: oklch(0.269 0 0);
|
||||
--muted-foreground: oklch(0.708 0 0);
|
||||
--accent: oklch(0.269 0 0);
|
||||
--accent-foreground: oklch(0.985 0 0);
|
||||
--destructive: oklch(0.704 0.191 22.216);
|
||||
--border: oklch(1 0 0 / 10%);
|
||||
--input: oklch(1 0 0 / 15%);
|
||||
--ring: oklch(0.556 0 0);
|
||||
--chart-1: oklch(0.488 0.243 264.376);
|
||||
--chart-2: oklch(0.696 0.17 162.48);
|
||||
--chart-3: oklch(0.769 0.188 70.08);
|
||||
--chart-4: oklch(0.627 0.265 303.9);
|
||||
--chart-5: oklch(0.645 0.246 16.439);
|
||||
--sidebar: oklch(0.205 0 0);
|
||||
--sidebar-foreground: oklch(0.985 0 0);
|
||||
--sidebar-primary: oklch(0.488 0.243 264.376);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.269 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.985 0 0);
|
||||
--sidebar-border: oklch(1 0 0 / 10%);
|
||||
--sidebar-ring: oklch(0.556 0 0);
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border outline-ring/50;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import type { Metadata } from "next";
|
||||
import { Geist, Geist_Mono } from "next/font/google";
|
||||
import { Toaster } from "sonner";
|
||||
import { QueryProvider } from "@/components/providers/QueryProvider";
|
||||
import "./globals.css";
|
||||
|
||||
const geistSans = Geist({
|
||||
variable: "--font-geist-sans",
|
||||
subsets: ["latin"],
|
||||
});
|
||||
|
||||
const geistMono = Geist_Mono({
|
||||
variable: "--font-geist-mono",
|
||||
subsets: ["latin"],
|
||||
});
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Muse Creative Hotspots",
|
||||
description: "全平台热点内容聚合浏览器",
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
}>) {
|
||||
return (
|
||||
<html lang="zh-CN">
|
||||
<body
|
||||
className={`${geistSans.variable} ${geistMono.variable} antialiased bg-white`}
|
||||
>
|
||||
<QueryProvider>
|
||||
{children}
|
||||
<Toaster position="top-right" richColors closeButton />
|
||||
</QueryProvider>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useMemo, useCallback } from "react";
|
||||
import { useContentQuery, useRefreshContent } from "@/hooks/useContentQuery";
|
||||
import { PlatformTabs } from "@/components/layout/PlatformTabs";
|
||||
import { SortToolbar, type SortField, type SortOrder } from "@/components/layout/SortToolbar";
|
||||
import { ContentGrid } from "@/components/card/ContentGrid";
|
||||
import type { ContentItem } from "@muse/shared";
|
||||
|
||||
function sortItems(
|
||||
items: ContentItem[],
|
||||
sortBy: SortField,
|
||||
sortOrder: SortOrder
|
||||
): ContentItem[] {
|
||||
return [...items].sort((a, b) => {
|
||||
let valA: number;
|
||||
let valB: number;
|
||||
|
||||
if (sortBy === "publish_time") {
|
||||
valA = new Date(a.publish_time).getTime() || 0;
|
||||
valB = new Date(b.publish_time).getTime() || 0;
|
||||
} else {
|
||||
valA = (a[sortBy] as number) ?? 0;
|
||||
valB = (b[sortBy] as number) ?? 0;
|
||||
}
|
||||
|
||||
return sortOrder === "desc" ? valB - valA : valA - valB;
|
||||
});
|
||||
}
|
||||
|
||||
export default function Home() {
|
||||
const [platform, setPlatform] = useState("all");
|
||||
const [sortBy, setSortBy] = useState<SortField>("play_count");
|
||||
const [sortOrder, setSortOrder] = useState<SortOrder>("desc");
|
||||
const [lastRefreshTime, setLastRefreshTime] = useState<string | null>(null);
|
||||
|
||||
const { data, isLoading, isFetching, isError, error, refetch } = useContentQuery(platform);
|
||||
const { refresh } = useRefreshContent();
|
||||
|
||||
const sortedItems = useMemo(() => {
|
||||
if (!data) return [];
|
||||
return sortItems(data, sortBy, sortOrder);
|
||||
}, [data, sortBy, sortOrder]);
|
||||
|
||||
const handleRefresh = useCallback(() => {
|
||||
refresh(platform);
|
||||
setLastRefreshTime(
|
||||
new Date().toLocaleTimeString("zh-CN", {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
})
|
||||
);
|
||||
}, [refresh, platform]);
|
||||
|
||||
const handleSortOrderChange = useCallback(() => {
|
||||
setSortOrder((prev) => (prev === "desc" ? "asc" : "desc"));
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="px-4 py-4">
|
||||
<PlatformTabs active={platform} onChange={setPlatform} />
|
||||
<SortToolbar
|
||||
sortBy={sortBy}
|
||||
sortOrder={sortOrder}
|
||||
onSortByChange={setSortBy}
|
||||
onSortOrderChange={handleSortOrderChange}
|
||||
onRefresh={handleRefresh}
|
||||
isRefreshing={isFetching}
|
||||
lastRefreshTime={lastRefreshTime}
|
||||
/>
|
||||
|
||||
{isError ? (
|
||||
<div className="text-center py-20">
|
||||
<p className="text-4xl mb-4">😵</p>
|
||||
<h2 className="text-lg font-medium text-slate-700 mb-2">
|
||||
加载失败
|
||||
</h2>
|
||||
<p className="text-sm text-slate-500 mb-4">
|
||||
{error?.message || "请求出错,请稍后重试"}
|
||||
</p>
|
||||
<button
|
||||
data-testid="error-retry"
|
||||
onClick={() => refetch()}
|
||||
className="inline-flex items-center gap-1.5 px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 transition-colors"
|
||||
>
|
||||
重试
|
||||
</button>
|
||||
</div>
|
||||
) : !isLoading && sortedItems.length === 0 ? (
|
||||
<div data-testid="empty-state" className="text-center py-20">
|
||||
<p className="text-4xl mb-4">📭</p>
|
||||
<h2 className="text-lg font-medium text-slate-700 mb-2">
|
||||
暂无内容
|
||||
</h2>
|
||||
<p className="text-sm text-slate-500">
|
||||
请先在设置页配置 API Key,或稍后重试
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<ContentGrid items={sortedItems} loading={isLoading} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { ArrowLeft, Eye, EyeOff, Check } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useSettingsStore } from "@/stores/settings";
|
||||
import { API_BASE_URL } from "@/lib/api";
|
||||
import { toast } from "sonner";
|
||||
|
||||
const REFRESH_OPTIONS: { value: 5 | 10 | 15 | 30 | 60; label: string }[] = [
|
||||
{ value: 5, label: "5 分钟" },
|
||||
{ value: 10, label: "10 分钟" },
|
||||
{ value: 15, label: "15 分钟" },
|
||||
{ value: 30, label: "30 分钟" },
|
||||
{ value: 60, label: "60 分钟" },
|
||||
];
|
||||
|
||||
export default function SettingsPage() {
|
||||
const { apiKey, setApiKey, refreshInterval, setRefreshInterval } =
|
||||
useSettingsStore();
|
||||
|
||||
const [inputKey, setInputKey] = useState(apiKey);
|
||||
const [showKey, setShowKey] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
const handleSaveApiKey = async () => {
|
||||
const trimmed = inputKey.trim();
|
||||
if (!trimmed) {
|
||||
toast.error("请输入 API Key");
|
||||
return;
|
||||
}
|
||||
|
||||
setSaving(true);
|
||||
try {
|
||||
const res = await fetch(`${API_BASE_URL}/api/settings`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ apiKey: trimmed }),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error("保存失败");
|
||||
}
|
||||
|
||||
setApiKey(trimmed);
|
||||
toast.success("API Key 已保存");
|
||||
} catch {
|
||||
toast.error("保存失败,请重试");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="px-4 py-4 max-w-2xl mx-auto">
|
||||
<div className="flex items-center gap-3 mb-6">
|
||||
<Link
|
||||
href="/"
|
||||
className="inline-flex items-center gap-1 text-sm text-slate-500 hover:text-slate-700 transition-colors"
|
||||
>
|
||||
<ArrowLeft className="w-4 h-4" />
|
||||
返回
|
||||
</Link>
|
||||
<h1 className="text-lg font-semibold text-slate-800">设置</h1>
|
||||
</div>
|
||||
|
||||
{/* API Key Section */}
|
||||
<section className="mb-8">
|
||||
<h2 className="text-sm font-medium text-slate-700 mb-1">
|
||||
TikHub API Key
|
||||
</h2>
|
||||
<p className="text-xs text-slate-400 mb-3">
|
||||
请前往{" "}
|
||||
<a
|
||||
href="https://tikhub.io"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-blue-500 hover:underline"
|
||||
>
|
||||
tikhub.io
|
||||
</a>{" "}
|
||||
获取 API Key
|
||||
</p>
|
||||
<div className="flex gap-2">
|
||||
<div className="relative flex-1">
|
||||
<input
|
||||
data-testid="apikey-input"
|
||||
type={showKey ? "text" : "password"}
|
||||
value={inputKey}
|
||||
onChange={(e) => setInputKey(e.target.value)}
|
||||
placeholder="输入你的 API Key"
|
||||
className="w-full text-sm border border-slate-200 rounded-lg px-3 py-2 pr-10 bg-white text-slate-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowKey(!showKey)}
|
||||
className="absolute right-2 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600"
|
||||
>
|
||||
{showKey ? (
|
||||
<EyeOff className="w-4 h-4" />
|
||||
) : (
|
||||
<Eye className="w-4 h-4" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
data-testid="apikey-save"
|
||||
onClick={handleSaveApiKey}
|
||||
disabled={saving}
|
||||
className="inline-flex items-center gap-1.5 px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 disabled:opacity-50 transition-colors"
|
||||
>
|
||||
{saving ? "保存中..." : "保存"}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Refresh Interval Section */}
|
||||
<section className="mb-8">
|
||||
<h2 className="text-sm font-medium text-slate-700 mb-1">
|
||||
自动刷新间隔
|
||||
</h2>
|
||||
<p className="text-xs text-slate-400 mb-3">
|
||||
设置热门内容的自动刷新频率
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{REFRESH_OPTIONS.map((opt) => (
|
||||
<button
|
||||
key={opt.value}
|
||||
onClick={() => setRefreshInterval(opt.value)}
|
||||
className={`inline-flex items-center gap-1 px-3 py-1.5 text-sm rounded-lg border transition-colors ${
|
||||
refreshInterval === opt.value
|
||||
? "border-blue-500 bg-blue-50 text-blue-700"
|
||||
: "border-slate-200 bg-white text-slate-600 hover:bg-slate-50"
|
||||
}`}
|
||||
>
|
||||
{refreshInterval === opt.value && (
|
||||
<Check className="w-3.5 h-3.5" />
|
||||
)}
|
||||
{opt.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
export function CardSkeleton() {
|
||||
return (
|
||||
<div className="rounded-lg border border-slate-200 bg-white overflow-hidden animate-pulse">
|
||||
{/* Cover placeholder */}
|
||||
<div className="aspect-[4/3] bg-slate-200" />
|
||||
|
||||
<div className="p-3 space-y-2">
|
||||
{/* Platform tag */}
|
||||
<div className="h-4 w-16 bg-slate-200 rounded" />
|
||||
{/* Title */}
|
||||
<div className="h-4 w-full bg-slate-200 rounded" />
|
||||
<div className="h-4 w-2/3 bg-slate-200 rounded" />
|
||||
{/* Author */}
|
||||
<div className="flex items-center gap-1.5">
|
||||
<div className="w-5 h-5 rounded-full bg-slate-200" />
|
||||
<div className="h-3 w-20 bg-slate-200 rounded" />
|
||||
</div>
|
||||
{/* Stats */}
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="h-3 w-10 bg-slate-200 rounded" />
|
||||
<div className="h-3 w-10 bg-slate-200 rounded" />
|
||||
<div className="h-3 w-10 bg-slate-200 rounded" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
"use client";
|
||||
|
||||
import Image from "next/image";
|
||||
import Link from "next/link";
|
||||
import { Play, Heart, Bookmark, Clock } from "lucide-react";
|
||||
import { getPlatformConfig } from "@muse/shared";
|
||||
import { formatCount, formatTime } from "@/lib/format";
|
||||
import { FavoriteButton } from "@/components/common/FavoriteButton";
|
||||
import type { ContentItem } from "@muse/shared";
|
||||
import { useState } from "react";
|
||||
|
||||
interface ContentCardProps {
|
||||
item: ContentItem;
|
||||
}
|
||||
|
||||
export function ContentCard({ item }: ContentCardProps) {
|
||||
const platform = getPlatformConfig(item.platform);
|
||||
const [imgError, setImgError] = useState(false);
|
||||
|
||||
const playCount = formatCount(item.play_count);
|
||||
const likeCount = formatCount(item.like_count);
|
||||
const collectCount = formatCount(item.collect_count);
|
||||
|
||||
return (
|
||||
<Link
|
||||
href={`/detail/${item.platform}/${encodeURIComponent(item.id)}`}
|
||||
data-testid="content-card"
|
||||
className="group block rounded-lg border border-slate-200 bg-white shadow-sm overflow-hidden transition-all hover:-translate-y-0.5 hover:shadow-md"
|
||||
>
|
||||
{/* Cover image */}
|
||||
<div className="relative aspect-[4/3] bg-slate-100 overflow-hidden">
|
||||
{item.cover_url && !imgError ? (
|
||||
<Image
|
||||
src={item.cover_url}
|
||||
alt={item.title}
|
||||
fill
|
||||
unoptimized
|
||||
className="object-cover"
|
||||
loading="lazy"
|
||||
sizes="(max-width: 640px) 100vw, (max-width: 960px) 50vw, (max-width: 1240px) 33vw, 25vw"
|
||||
onError={() => setImgError(true)}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex items-center justify-center h-full text-3xl text-slate-300">
|
||||
{platform?.icon || "📄"}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="p-3">
|
||||
{/* Platform tag + publish time */}
|
||||
<div className="flex items-center justify-between mb-1.5">
|
||||
{platform && (
|
||||
<span
|
||||
className="inline-block text-xs px-1.5 py-0.5 rounded"
|
||||
style={{
|
||||
backgroundColor: `${platform.color}15`,
|
||||
color: platform.color,
|
||||
}}
|
||||
>
|
||||
{platform.icon} {platform.name}
|
||||
</span>
|
||||
)}
|
||||
{item.publish_time && (
|
||||
<span className="flex items-center gap-0.5 text-[11px] text-slate-400">
|
||||
<Clock className="w-3 h-3" />
|
||||
{formatTime(item.publish_time)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Title */}
|
||||
<h3 className="text-sm font-medium text-slate-800 line-clamp-2 mb-2 leading-snug">
|
||||
{item.title}
|
||||
</h3>
|
||||
|
||||
{/* Author */}
|
||||
<div className="flex items-center gap-1.5 mb-2">
|
||||
{item.author_avatar ? (
|
||||
<Image
|
||||
src={item.author_avatar}
|
||||
alt={item.author_name}
|
||||
width={20}
|
||||
height={20}
|
||||
unoptimized
|
||||
className="rounded-full object-cover"
|
||||
onError={(e) => {
|
||||
(e.target as HTMLImageElement).style.display = "none";
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<div className="w-5 h-5 rounded-full bg-slate-200 flex items-center justify-center text-[10px] text-slate-500">
|
||||
👤
|
||||
</div>
|
||||
)}
|
||||
<span className="text-xs text-slate-500 truncate">
|
||||
{item.author_name}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Stats + Favorite */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3 text-xs text-slate-400">
|
||||
{playCount && (
|
||||
<span className="flex items-center gap-0.5">
|
||||
<Play className="w-3 h-3" />
|
||||
{playCount}
|
||||
</span>
|
||||
)}
|
||||
{likeCount && (
|
||||
<span className="flex items-center gap-0.5">
|
||||
<Heart className="w-3 h-3" />
|
||||
{likeCount}
|
||||
</span>
|
||||
)}
|
||||
{collectCount && (
|
||||
<span className="flex items-center gap-0.5">
|
||||
<Bookmark className="w-3 h-3" />
|
||||
{collectCount}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<FavoriteButton item={item} />
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
"use client";
|
||||
|
||||
import { ContentCard } from "./ContentCard";
|
||||
import { CardSkeleton } from "./CardSkeleton";
|
||||
import type { ContentItem } from "@muse/shared";
|
||||
|
||||
interface ContentGridProps {
|
||||
items: ContentItem[];
|
||||
loading?: boolean;
|
||||
skeletonCount?: number;
|
||||
}
|
||||
|
||||
export function ContentGrid({
|
||||
items,
|
||||
loading,
|
||||
skeletonCount = 12,
|
||||
}: ContentGridProps) {
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="grid grid-cols-[repeat(auto-fill,minmax(280px,1fr))] gap-4">
|
||||
{Array.from({ length: skeletonCount }).map((_, i) => (
|
||||
<CardSkeleton key={i} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div data-testid="content-grid" className="grid grid-cols-[repeat(auto-fill,minmax(280px,1fr))] gap-4">
|
||||
{items.map((item) => (
|
||||
<ContentCard key={`${item.platform}-${item.id}`} item={item} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import Link from "next/link";
|
||||
|
||||
interface EmptyStateProps {
|
||||
icon?: string;
|
||||
title: string;
|
||||
description?: string;
|
||||
actionLabel?: string;
|
||||
actionHref?: string;
|
||||
}
|
||||
|
||||
export function EmptyState({
|
||||
icon = "📭",
|
||||
title,
|
||||
description,
|
||||
actionLabel,
|
||||
actionHref,
|
||||
}: EmptyStateProps) {
|
||||
return (
|
||||
<div className="text-center py-20">
|
||||
<p className="text-4xl mb-4">{icon}</p>
|
||||
<h2 className="text-lg font-medium text-slate-700 mb-2">{title}</h2>
|
||||
{description && (
|
||||
<p className="text-sm text-slate-500 mb-4">{description}</p>
|
||||
)}
|
||||
{actionLabel && actionHref && (
|
||||
<Link
|
||||
href={actionHref}
|
||||
className="inline-flex items-center gap-1.5 px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 transition-colors"
|
||||
>
|
||||
{actionLabel}
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { RefreshCw } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
|
||||
interface ErrorStateProps {
|
||||
message?: string;
|
||||
onRetry?: () => void;
|
||||
showHomeLink?: boolean;
|
||||
}
|
||||
|
||||
export function ErrorState({
|
||||
message = "加载失败,请稍后重试",
|
||||
onRetry,
|
||||
showHomeLink = true,
|
||||
}: ErrorStateProps) {
|
||||
return (
|
||||
<div className="text-center py-20">
|
||||
<p className="text-4xl mb-4">😵</p>
|
||||
<h2 className="text-lg font-medium text-slate-700 mb-2">出错了</h2>
|
||||
<p className="text-sm text-slate-500 mb-6">{message}</p>
|
||||
<div className="flex items-center justify-center gap-3">
|
||||
{onRetry && (
|
||||
<button
|
||||
onClick={onRetry}
|
||||
className="inline-flex items-center gap-1.5 px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 transition-colors"
|
||||
>
|
||||
<RefreshCw className="w-4 h-4" />
|
||||
重试
|
||||
</button>
|
||||
)}
|
||||
{showHomeLink && (
|
||||
<Link
|
||||
href="/"
|
||||
className="inline-flex items-center gap-1.5 px-4 py-2 text-sm font-medium text-slate-600 border border-slate-200 rounded-lg hover:bg-slate-50 transition-colors"
|
||||
>
|
||||
返回首页
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
"use client";
|
||||
|
||||
import { Heart } from "lucide-react";
|
||||
import { useFavoritesStore } from "@/stores/favorites";
|
||||
import type { ContentItem } from "@muse/shared";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useState } from "react";
|
||||
|
||||
interface FavoriteButtonProps {
|
||||
item: ContentItem;
|
||||
size?: "sm" | "md";
|
||||
}
|
||||
|
||||
export function FavoriteButton({ item, size = "sm" }: FavoriteButtonProps) {
|
||||
const { isFavorited, addFavorite, removeFavorite } = useFavoritesStore();
|
||||
const favorited = isFavorited(item.id, item.platform);
|
||||
const [animating, setAnimating] = useState(false);
|
||||
|
||||
const handleClick = (e: React.MouseEvent) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
setAnimating(true);
|
||||
setTimeout(() => setAnimating(false), 300);
|
||||
|
||||
if (favorited) {
|
||||
removeFavorite(item.id, item.platform);
|
||||
} else {
|
||||
addFavorite(item);
|
||||
}
|
||||
};
|
||||
|
||||
const iconSize = size === "sm" ? "w-4 h-4" : "w-5 h-5";
|
||||
|
||||
return (
|
||||
<button
|
||||
data-testid="favorite-btn"
|
||||
onClick={handleClick}
|
||||
className={cn(
|
||||
"inline-flex items-center justify-center rounded-md transition-colors",
|
||||
size === "sm" ? "w-8 h-8" : "w-11 h-11",
|
||||
favorited
|
||||
? "text-red-500 hover:text-red-600"
|
||||
: "text-slate-400 hover:text-red-400",
|
||||
animating && "scale-110"
|
||||
)}
|
||||
style={{ transition: "transform 0.2s ease" }}
|
||||
aria-label={favorited ? "取消收藏" : "收藏"}
|
||||
>
|
||||
<Heart
|
||||
className={cn(iconSize, favorited && "fill-current")}
|
||||
/>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
"use client";
|
||||
|
||||
import Image from "next/image";
|
||||
import { ArrowLeft, Play, Heart, Bookmark, MessageCircle, Share2, ExternalLink } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { getPlatformConfig } from "@muse/shared";
|
||||
import { formatCount, formatTime } from "@/lib/format";
|
||||
import { FavoriteButton } from "@/components/common/FavoriteButton";
|
||||
import type { ContentItem } from "@muse/shared";
|
||||
import { useState } from "react";
|
||||
|
||||
interface DetailPanelProps {
|
||||
item: ContentItem;
|
||||
}
|
||||
|
||||
const STAT_ITEMS = [
|
||||
{ key: "play_count" as const, label: "播放", icon: Play },
|
||||
{ key: "like_count" as const, label: "点赞", icon: Heart },
|
||||
{ key: "collect_count" as const, label: "收藏", icon: Bookmark },
|
||||
{ key: "comment_count" as const, label: "评论", icon: MessageCircle },
|
||||
{ key: "share_count" as const, label: "分享", icon: Share2 },
|
||||
];
|
||||
|
||||
export function DetailPanel({ item }: DetailPanelProps) {
|
||||
const router = useRouter();
|
||||
const platform = getPlatformConfig(item.platform);
|
||||
const [imgError, setImgError] = useState(false);
|
||||
|
||||
return (
|
||||
<div className="max-w-3xl mx-auto">
|
||||
{/* Back button */}
|
||||
<button
|
||||
data-testid="detail-back"
|
||||
onClick={() => router.back()}
|
||||
className="inline-flex items-center gap-1.5 text-sm text-slate-500 hover:text-slate-700 mb-4 transition-colors"
|
||||
>
|
||||
<ArrowLeft className="w-4 h-4" />
|
||||
返回
|
||||
</button>
|
||||
|
||||
{/* Cover image */}
|
||||
<div className="relative aspect-video bg-slate-100 rounded-lg overflow-hidden">
|
||||
{item.cover_url && !imgError ? (
|
||||
<Image
|
||||
src={item.cover_url}
|
||||
alt={item.title}
|
||||
fill
|
||||
unoptimized
|
||||
className="object-cover"
|
||||
priority
|
||||
sizes="(max-width: 768px) 100vw, 768px"
|
||||
onError={() => setImgError(true)}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex items-center justify-center h-full text-5xl text-slate-300">
|
||||
{platform?.icon || "📄"}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="mt-6 space-y-5">
|
||||
{/* Platform tag */}
|
||||
{platform && (
|
||||
<span
|
||||
className="inline-block text-xs px-2 py-0.5 rounded"
|
||||
style={{
|
||||
backgroundColor: `${platform.color}15`,
|
||||
color: platform.color,
|
||||
}}
|
||||
>
|
||||
{platform.icon} {platform.name}
|
||||
</span>
|
||||
)}
|
||||
|
||||
{/* Title */}
|
||||
<h1 className="text-xl font-semibold text-slate-900 leading-relaxed">
|
||||
{item.title}
|
||||
</h1>
|
||||
|
||||
{/* Author */}
|
||||
<div className="flex items-center gap-3">
|
||||
{item.author_avatar ? (
|
||||
<Image
|
||||
src={item.author_avatar}
|
||||
alt={item.author_name}
|
||||
width={40}
|
||||
height={40}
|
||||
unoptimized
|
||||
className="rounded-full object-cover"
|
||||
onError={(e) => {
|
||||
(e.target as HTMLImageElement).style.display = "none";
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<div className="w-10 h-10 rounded-full bg-slate-200 flex items-center justify-center text-lg text-slate-500">
|
||||
👤
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<p className="text-sm font-medium text-slate-700">
|
||||
{item.author_name}
|
||||
</p>
|
||||
{item.publish_time && (
|
||||
<p className="text-xs text-slate-400">
|
||||
{formatTime(item.publish_time)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Stats panel */}
|
||||
<div className="grid grid-cols-5 gap-3">
|
||||
{STAT_ITEMS.map(({ key, label, icon: Icon }) => {
|
||||
const value = item[key];
|
||||
return (
|
||||
<div
|
||||
key={key}
|
||||
className="flex flex-col items-center gap-1 py-3 bg-slate-50 rounded-lg"
|
||||
>
|
||||
<Icon className="w-4 h-4 text-slate-400" />
|
||||
<span className="text-lg font-semibold text-slate-800">
|
||||
{formatCount(value) || "0"}
|
||||
</span>
|
||||
<span className="text-xs text-slate-400">{label}</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Tags */}
|
||||
{item.tags && item.tags.length > 0 && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{item.tags.map((tag) => (
|
||||
<span
|
||||
key={tag}
|
||||
className="text-xs px-2.5 py-1 bg-slate-100 text-slate-600 rounded-full"
|
||||
>
|
||||
#{tag}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex items-center gap-3 pt-2">
|
||||
<button
|
||||
data-testid="view-original"
|
||||
onClick={() => window.open(item.original_url, "_blank")}
|
||||
className="inline-flex items-center gap-1.5 px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 transition-colors"
|
||||
>
|
||||
<ExternalLink className="w-4 h-4" />
|
||||
查看原文
|
||||
</button>
|
||||
<FavoriteButton item={item} size="md" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
export function DetailSkeleton() {
|
||||
return (
|
||||
<div className="max-w-3xl mx-auto animate-pulse">
|
||||
{/* Cover */}
|
||||
<div className="aspect-video bg-slate-200 rounded-lg" />
|
||||
|
||||
<div className="mt-6 space-y-4">
|
||||
{/* Title */}
|
||||
<div className="h-7 w-3/4 bg-slate-200 rounded" />
|
||||
<div className="h-7 w-1/2 bg-slate-200 rounded" />
|
||||
|
||||
{/* Author */}
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-10 h-10 rounded-full bg-slate-200" />
|
||||
<div className="h-4 w-24 bg-slate-200 rounded" />
|
||||
</div>
|
||||
|
||||
{/* Stats */}
|
||||
<div className="flex gap-6">
|
||||
{Array.from({ length: 4 }).map((_, i) => (
|
||||
<div key={i} className="h-16 w-24 bg-slate-200 rounded-lg" />
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Tags */}
|
||||
<div className="flex gap-2">
|
||||
{Array.from({ length: 3 }).map((_, i) => (
|
||||
<div key={i} className="h-6 w-16 bg-slate-200 rounded-full" />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { Heart, Settings } from "lucide-react";
|
||||
import { PlatformTabs } from "./PlatformTabs";
|
||||
|
||||
interface HeaderProps {
|
||||
activePlatform?: string;
|
||||
onPlatformChange?: (platform: string) => void;
|
||||
}
|
||||
|
||||
export function Header({ activePlatform, onPlatformChange }: HeaderProps) {
|
||||
const pathname = usePathname();
|
||||
const isHome = pathname === "/";
|
||||
|
||||
return (
|
||||
<header className="sticky top-0 z-50 w-full bg-white border-b border-slate-200">
|
||||
<div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
|
||||
<div className="flex h-14 items-center justify-between">
|
||||
{/* Logo */}
|
||||
<Link href="/" className="text-xl font-bold text-slate-800 shrink-0">
|
||||
Muse
|
||||
</Link>
|
||||
|
||||
{/* Platform Tabs - only on home page */}
|
||||
{isHome && onPlatformChange && (
|
||||
<div className="flex-1 flex justify-center mx-4 overflow-x-auto">
|
||||
<PlatformTabs
|
||||
active={activePlatform || "all"}
|
||||
onChange={onPlatformChange}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Right actions */}
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
<Link
|
||||
href="/favorites"
|
||||
className="inline-flex items-center justify-center w-9 h-9 rounded-md text-slate-500 hover:text-slate-800 hover:bg-slate-100 transition-colors"
|
||||
>
|
||||
<Heart className="w-5 h-5" />
|
||||
</Link>
|
||||
<Link
|
||||
href="/settings"
|
||||
className="inline-flex items-center justify-center w-9 h-9 rounded-md text-slate-500 hover:text-slate-800 hover:bg-slate-100 transition-colors"
|
||||
>
|
||||
<Settings className="w-5 h-5" />
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
"use client";
|
||||
|
||||
import { MVP_PLATFORMS } from "@muse/shared";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface PlatformTabsProps {
|
||||
active: string;
|
||||
onChange: (platform: string) => void;
|
||||
}
|
||||
|
||||
const ALL_TAB = { id: "all", name: "全部", icon: "🌐", color: "#2563EB" };
|
||||
|
||||
export function PlatformTabs({ active, onChange }: PlatformTabsProps) {
|
||||
const tabs = [ALL_TAB, ...MVP_PLATFORMS.map((p) => ({ id: p.id, name: p.name, icon: p.icon, color: p.color }))];
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-1">
|
||||
{tabs.map((tab) => (
|
||||
<button
|
||||
key={tab.id}
|
||||
data-testid={`platform-tab-${tab.id}`}
|
||||
onClick={() => onChange(tab.id)}
|
||||
className={cn(
|
||||
"relative px-3 py-1.5 text-sm font-medium rounded-md transition-colors whitespace-nowrap",
|
||||
active === tab.id
|
||||
? "text-slate-800"
|
||||
: "text-slate-500 hover:text-slate-700 hover:bg-slate-50"
|
||||
)}
|
||||
>
|
||||
<span className="mr-1">{tab.icon}</span>
|
||||
{tab.name}
|
||||
{active === tab.id && (
|
||||
<span
|
||||
className="absolute bottom-0 left-1/2 -translate-x-1/2 w-6 h-0.5 rounded-full"
|
||||
style={{ backgroundColor: tab.color }}
|
||||
/>
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
"use client";
|
||||
|
||||
import { RefreshCw } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export type SortField = "play_count" | "like_count" | "collect_count" | "comment_count" | "publish_time";
|
||||
export type SortOrder = "asc" | "desc";
|
||||
|
||||
const SORT_OPTIONS: { value: SortField; label: string }[] = [
|
||||
{ value: "play_count", label: "播放量" },
|
||||
{ value: "like_count", label: "点赞数" },
|
||||
{ value: "collect_count", label: "收藏量" },
|
||||
{ value: "comment_count", label: "评论数" },
|
||||
{ value: "publish_time", label: "发布时间" },
|
||||
];
|
||||
|
||||
interface SortToolbarProps {
|
||||
sortBy: SortField;
|
||||
sortOrder: SortOrder;
|
||||
onSortByChange: (field: SortField) => void;
|
||||
onSortOrderChange: () => void;
|
||||
onRefresh: () => void;
|
||||
isRefreshing: boolean;
|
||||
lastRefreshTime: string | null;
|
||||
}
|
||||
|
||||
export function SortToolbar({
|
||||
sortBy,
|
||||
sortOrder,
|
||||
onSortByChange,
|
||||
onSortOrderChange,
|
||||
onRefresh,
|
||||
isRefreshing,
|
||||
lastRefreshTime,
|
||||
}: SortToolbarProps) {
|
||||
return (
|
||||
<div className="flex items-center justify-between py-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-sm text-slate-500">排序:</span>
|
||||
<select
|
||||
data-testid="sort-select"
|
||||
value={sortBy}
|
||||
onChange={(e) => onSortByChange(e.target.value as SortField)}
|
||||
className="text-sm border border-slate-200 rounded-md px-2 py-1 bg-white text-slate-700 focus:outline-none focus:ring-1 focus:ring-blue-500"
|
||||
>
|
||||
{SORT_OPTIONS.map((opt) => (
|
||||
<option key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button
|
||||
data-testid="sort-order"
|
||||
onClick={onSortOrderChange}
|
||||
className="text-sm border border-slate-200 rounded-md px-2 py-1 bg-white text-slate-700 hover:bg-slate-50 transition-colors"
|
||||
>
|
||||
{sortOrder === "desc" ? "↓ 降序" : "↑ 升序"}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
data-testid="refresh-btn"
|
||||
onClick={onRefresh}
|
||||
disabled={isRefreshing}
|
||||
className="inline-flex items-center gap-1 text-sm text-slate-500 hover:text-slate-700 disabled:opacity-50 transition-colors"
|
||||
>
|
||||
<RefreshCw
|
||||
className={cn("w-4 h-4", isRefreshing && "animate-spin")}
|
||||
/>
|
||||
刷新
|
||||
</button>
|
||||
{lastRefreshTime && (
|
||||
<span className="text-xs text-slate-400">
|
||||
上次: {lastRefreshTime}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
"use client";
|
||||
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { useState } from "react";
|
||||
|
||||
export function QueryProvider({ children }: { children: React.ReactNode }) {
|
||||
const [queryClient] = useState(
|
||||
() =>
|
||||
new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
staleTime: 1000 * 60 * 5, // 5 minutes
|
||||
retry: 1,
|
||||
},
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import * as React from "react"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { Slot } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const buttonVariants = cva(
|
||||
"inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-all outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-primary text-primary-foreground hover:bg-primary/90",
|
||||
destructive:
|
||||
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40",
|
||||
outline:
|
||||
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||
ghost:
|
||||
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
default: "h-9 px-4 py-2 has-[>svg]:px-3",
|
||||
xs: "h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",
|
||||
sm: "h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5",
|
||||
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
|
||||
icon: "size-9",
|
||||
"icon-xs": "size-6 rounded-md [&_svg:not([class*='size-'])]:size-3",
|
||||
"icon-sm": "size-8",
|
||||
"icon-lg": "size-10",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Button({
|
||||
className,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> &
|
||||
VariantProps<typeof buttonVariants> & {
|
||||
asChild?: boolean
|
||||
}) {
|
||||
const Comp = asChild ? Slot.Root : "button"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="button"
|
||||
data-variant={variant}
|
||||
data-size={size}
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Button, buttonVariants }
|
||||
@@ -0,0 +1,21 @@
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
data-slot="input"
|
||||
className={cn(
|
||||
"h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30",
|
||||
"focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50",
|
||||
"aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Input }
|
||||
@@ -0,0 +1,190 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react"
|
||||
import { Select as SelectPrimitive } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Select({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
|
||||
return <SelectPrimitive.Root data-slot="select" {...props} />
|
||||
}
|
||||
|
||||
function SelectGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
|
||||
return <SelectPrimitive.Group data-slot="select-group" {...props} />
|
||||
}
|
||||
|
||||
function SelectValue({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
|
||||
return <SelectPrimitive.Value data-slot="select-value" {...props} />
|
||||
}
|
||||
|
||||
function SelectTrigger({
|
||||
className,
|
||||
size = "default",
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
|
||||
size?: "sm" | "default"
|
||||
}) {
|
||||
return (
|
||||
<SelectPrimitive.Trigger
|
||||
data-slot="select-trigger"
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"flex w-fit items-center justify-between gap-2 rounded-md border border-input bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[placeholder]:text-muted-foreground data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SelectPrimitive.Icon asChild>
|
||||
<ChevronDownIcon className="size-4 opacity-50" />
|
||||
</SelectPrimitive.Icon>
|
||||
</SelectPrimitive.Trigger>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectContent({
|
||||
className,
|
||||
children,
|
||||
position = "item-aligned",
|
||||
align = "center",
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
|
||||
return (
|
||||
<SelectPrimitive.Portal>
|
||||
<SelectPrimitive.Content
|
||||
data-slot="select-content"
|
||||
className={cn(
|
||||
"relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
|
||||
position === "popper" &&
|
||||
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
|
||||
className
|
||||
)}
|
||||
position={position}
|
||||
align={align}
|
||||
{...props}
|
||||
>
|
||||
<SelectScrollUpButton />
|
||||
<SelectPrimitive.Viewport
|
||||
className={cn(
|
||||
"p-1",
|
||||
position === "popper" &&
|
||||
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</SelectPrimitive.Viewport>
|
||||
<SelectScrollDownButton />
|
||||
</SelectPrimitive.Content>
|
||||
</SelectPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectLabel({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
|
||||
return (
|
||||
<SelectPrimitive.Label
|
||||
data-slot="select-label"
|
||||
className={cn("px-2 py-1.5 text-xs text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
|
||||
return (
|
||||
<SelectPrimitive.Item
|
||||
data-slot="select-item"
|
||||
className={cn(
|
||||
"relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span
|
||||
data-slot="select-item-indicator"
|
||||
className="absolute right-2 flex size-3.5 items-center justify-center"
|
||||
>
|
||||
<SelectPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</SelectPrimitive.ItemIndicator>
|
||||
</span>
|
||||
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
||||
</SelectPrimitive.Item>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
|
||||
return (
|
||||
<SelectPrimitive.Separator
|
||||
data-slot="select-separator"
|
||||
className={cn("pointer-events-none -mx-1 my-1 h-px bg-border", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectScrollUpButton({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
|
||||
return (
|
||||
<SelectPrimitive.ScrollUpButton
|
||||
data-slot="select-scroll-up-button"
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronUpIcon className="size-4" />
|
||||
</SelectPrimitive.ScrollUpButton>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectScrollDownButton({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
|
||||
return (
|
||||
<SelectPrimitive.ScrollDownButton
|
||||
data-slot="select-scroll-down-button"
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronDownIcon className="size-4" />
|
||||
</SelectPrimitive.ScrollDownButton>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectGroup,
|
||||
SelectItem,
|
||||
SelectLabel,
|
||||
SelectScrollDownButton,
|
||||
SelectScrollUpButton,
|
||||
SelectSeparator,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
"use client"
|
||||
|
||||
import {
|
||||
CircleCheckIcon,
|
||||
InfoIcon,
|
||||
Loader2Icon,
|
||||
OctagonXIcon,
|
||||
TriangleAlertIcon,
|
||||
} from "lucide-react"
|
||||
import { useTheme } from "next-themes"
|
||||
import { Toaster as Sonner, type ToasterProps } from "sonner"
|
||||
|
||||
const Toaster = ({ ...props }: ToasterProps) => {
|
||||
const { theme = "system" } = useTheme()
|
||||
|
||||
return (
|
||||
<Sonner
|
||||
theme={theme as ToasterProps["theme"]}
|
||||
className="toaster group"
|
||||
icons={{
|
||||
success: <CircleCheckIcon className="size-4" />,
|
||||
info: <InfoIcon className="size-4" />,
|
||||
warning: <TriangleAlertIcon className="size-4" />,
|
||||
error: <OctagonXIcon className="size-4" />,
|
||||
loading: <Loader2Icon className="size-4 animate-spin" />,
|
||||
}}
|
||||
style={
|
||||
{
|
||||
"--normal-bg": "var(--popover)",
|
||||
"--normal-text": "var(--popover-foreground)",
|
||||
"--normal-border": "var(--border)",
|
||||
"--border-radius": "var(--radius)",
|
||||
} as React.CSSProperties
|
||||
}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Toaster }
|
||||
@@ -0,0 +1,60 @@
|
||||
"use client";
|
||||
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useSettingsStore } from "@/stores/settings";
|
||||
import type { ContentItem } from "@muse/shared";
|
||||
import { MVP_PLATFORMS } from "@muse/shared";
|
||||
import { API_BASE_URL } from "@/lib/api";
|
||||
|
||||
async function fetchPlatformContent(platform: string): Promise<ContentItem[]> {
|
||||
const res = await fetch(`${API_BASE_URL}/api/tikhub/${platform}?count=20`);
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
throw new Error(data.error || `请求失败: ${res.status}`);
|
||||
}
|
||||
const data = await res.json();
|
||||
return data.data || [];
|
||||
}
|
||||
|
||||
async function fetchAllPlatforms(): Promise<ContentItem[]> {
|
||||
const results = await Promise.allSettled(
|
||||
MVP_PLATFORMS.filter((p) => p.enabled).map((p) => fetchPlatformContent(p.id))
|
||||
);
|
||||
|
||||
const fulfilled = results.filter(
|
||||
(r): r is PromiseFulfilledResult<ContentItem[]> => r.status === "fulfilled"
|
||||
);
|
||||
|
||||
// If ALL requests failed, throw the first error so the UI can show it
|
||||
if (fulfilled.length === 0 && results.length > 0) {
|
||||
const firstError = results.find(
|
||||
(r): r is PromiseRejectedResult => r.status === "rejected"
|
||||
);
|
||||
throw firstError?.reason || new Error("所有平台请求失败");
|
||||
}
|
||||
|
||||
return fulfilled.flatMap((r) => r.value);
|
||||
}
|
||||
|
||||
export function useContentQuery(platform: string) {
|
||||
const refreshInterval = useSettingsStore((s) => s.refreshInterval);
|
||||
|
||||
return useQuery<ContentItem[]>({
|
||||
queryKey: ["content", platform],
|
||||
queryFn: () =>
|
||||
platform === "all"
|
||||
? fetchAllPlatforms()
|
||||
: fetchPlatformContent(platform),
|
||||
refetchInterval: refreshInterval * 60 * 1000,
|
||||
refetchIntervalInBackground: false,
|
||||
});
|
||||
}
|
||||
|
||||
export function useRefreshContent() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return {
|
||||
refresh: (platform: string) =>
|
||||
queryClient.invalidateQueries({ queryKey: ["content", platform] }),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
"use client";
|
||||
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import type { ContentItem } from "@muse/shared";
|
||||
import { API_BASE_URL } from "@/lib/api";
|
||||
|
||||
async function fetchDetail(
|
||||
platform: string,
|
||||
id: string
|
||||
): Promise<ContentItem> {
|
||||
const res = await fetch(
|
||||
`${API_BASE_URL}/api/tikhub/${platform}/detail?id=${encodeURIComponent(id)}`
|
||||
);
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
throw new Error(data.error || `请求失败: ${res.status}`);
|
||||
}
|
||||
const data = await res.json();
|
||||
return data.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Look up an item from TanStack Query's trending list cache.
|
||||
* Checks both platform-specific and "all" caches.
|
||||
*/
|
||||
function findCachedItem(
|
||||
queryClient: ReturnType<typeof useQueryClient>,
|
||||
platform: string,
|
||||
id: string
|
||||
): ContentItem | undefined {
|
||||
const keys = [["content", platform], ["content", "all"]];
|
||||
for (const key of keys) {
|
||||
const items = queryClient.getQueryData<ContentItem[]>(key);
|
||||
if (items) {
|
||||
const found = items.find(
|
||||
(item) => item.id === id && item.platform === platform
|
||||
);
|
||||
if (found) return found;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function useDetailQuery(platform: string, id: string) {
|
||||
const queryClient = useQueryClient();
|
||||
const cached = findCachedItem(queryClient, platform, id);
|
||||
|
||||
return useQuery<ContentItem>({
|
||||
queryKey: ["detail", platform, id],
|
||||
queryFn: () => fetchDetail(platform, id),
|
||||
// Skip API call if item already in trending cache
|
||||
enabled: !!platform && !!id && !cached,
|
||||
initialData: cached,
|
||||
staleTime: 5 * 60 * 1000,
|
||||
retry: 1,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export const API_BASE_URL =
|
||||
process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001";
|
||||
@@ -0,0 +1,73 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import { formatCount, formatTime } from "./format";
|
||||
|
||||
describe("formatCount", () => {
|
||||
it("returns null for undefined", () => {
|
||||
expect(formatCount(undefined)).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null for null (cast)", () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
expect(formatCount(null as any)).toBeNull();
|
||||
});
|
||||
|
||||
it("returns raw number for values < 1000", () => {
|
||||
expect(formatCount(0)).toBe("0");
|
||||
expect(formatCount(1)).toBe("1");
|
||||
expect(formatCount(999)).toBe("999");
|
||||
});
|
||||
|
||||
it("formats thousands with K suffix", () => {
|
||||
expect(formatCount(1000)).toBe("1.0K");
|
||||
expect(formatCount(1500)).toBe("1.5K");
|
||||
expect(formatCount(5300)).toBe("5.3K");
|
||||
expect(formatCount(999_999)).toBe("1000.0K");
|
||||
});
|
||||
|
||||
it("formats millions with M suffix", () => {
|
||||
expect(formatCount(1_000_000)).toBe("1.0M");
|
||||
expect(formatCount(1_200_000)).toBe("1.2M");
|
||||
expect(formatCount(53_000_000)).toBe("53.0M");
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatTime", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date("2026-03-03T12:00:00Z"));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('returns "刚刚" for times less than 1 minute ago', () => {
|
||||
expect(formatTime("2026-03-03T12:00:00Z")).toBe("刚刚");
|
||||
expect(formatTime("2026-03-03T11:59:30Z")).toBe("刚刚");
|
||||
});
|
||||
|
||||
it("returns minutes ago for times < 60 minutes", () => {
|
||||
expect(formatTime("2026-03-03T11:55:00Z")).toBe("5分钟前");
|
||||
expect(formatTime("2026-03-03T11:01:00Z")).toBe("59分钟前");
|
||||
});
|
||||
|
||||
it("returns hours ago for times < 24 hours", () => {
|
||||
expect(formatTime("2026-03-03T10:00:00Z")).toBe("2小时前");
|
||||
expect(formatTime("2026-03-02T13:00:00Z")).toBe("23小时前");
|
||||
});
|
||||
|
||||
it("returns days ago for times < 30 days", () => {
|
||||
expect(formatTime("2026-03-02T12:00:00Z")).toBe("1天前");
|
||||
expect(formatTime("2026-02-10T12:00:00Z")).toBe("21天前");
|
||||
});
|
||||
|
||||
it("returns formatted date for times >= 30 days ago", () => {
|
||||
const result = formatTime("2026-01-01T12:00:00Z");
|
||||
expect(result).toBeTruthy();
|
||||
expect(result).not.toBe("");
|
||||
});
|
||||
|
||||
it("returns 'Invalid Date' for invalid date string", () => {
|
||||
expect(formatTime("invalid-date")).toBe("Invalid Date");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
export function formatCount(count: number | undefined): string | null {
|
||||
if (count === undefined || count === null) return null;
|
||||
if (count >= 1_000_000) return `${(count / 1_000_000).toFixed(1)}M`;
|
||||
if (count >= 1_000) return `${(count / 1_000).toFixed(1)}K`;
|
||||
return String(count);
|
||||
}
|
||||
|
||||
export function formatTime(isoString: string): string {
|
||||
try {
|
||||
const date = new Date(isoString);
|
||||
const now = new Date();
|
||||
const diffMs = now.getTime() - date.getTime();
|
||||
const diffMin = Math.floor(diffMs / 60_000);
|
||||
const diffHour = Math.floor(diffMs / 3_600_000);
|
||||
const diffDay = Math.floor(diffMs / 86_400_000);
|
||||
|
||||
if (diffMin < 1) return "刚刚";
|
||||
if (diffMin < 60) return `${diffMin}分钟前`;
|
||||
if (diffHour < 24) return `${diffHour}小时前`;
|
||||
if (diffDay < 30) return `${diffDay}天前`;
|
||||
|
||||
return date.toLocaleDateString("zh-CN", {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
});
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { clsx, type ClassValue } from "clsx"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import { describe, it, expect, beforeEach } from "vitest";
|
||||
import { useFavoritesStore } from "./favorites";
|
||||
import type { ContentItem } from "@muse/shared";
|
||||
|
||||
const mockItem: ContentItem = {
|
||||
id: "123",
|
||||
title: "Test Item",
|
||||
author_name: "Test Author",
|
||||
publish_time: "2026-03-03T12:00:00Z",
|
||||
platform: "douyin",
|
||||
original_url: "https://douyin.com/video/123",
|
||||
};
|
||||
|
||||
const mockItem2: ContentItem = {
|
||||
id: "456",
|
||||
title: "Second Item",
|
||||
author_name: "Author 2",
|
||||
publish_time: "2026-03-03T12:00:00Z",
|
||||
platform: "tiktok",
|
||||
original_url: "https://tiktok.com/@user/video/456",
|
||||
};
|
||||
|
||||
const mockItemSameIdDiffPlatform: ContentItem = {
|
||||
...mockItem,
|
||||
platform: "tiktok",
|
||||
original_url: "https://tiktok.com/@user/video/123",
|
||||
};
|
||||
|
||||
describe("useFavoritesStore", () => {
|
||||
beforeEach(() => {
|
||||
// Reset store state before each test
|
||||
useFavoritesStore.setState({ items: [] });
|
||||
});
|
||||
|
||||
describe("addFavorite", () => {
|
||||
it("adds an item to favorites", () => {
|
||||
useFavoritesStore.getState().addFavorite(mockItem);
|
||||
expect(useFavoritesStore.getState().items).toHaveLength(1);
|
||||
expect(useFavoritesStore.getState().items[0]).toEqual(mockItem);
|
||||
});
|
||||
|
||||
it("does not add duplicate item (same id + platform)", () => {
|
||||
useFavoritesStore.getState().addFavorite(mockItem);
|
||||
useFavoritesStore.getState().addFavorite(mockItem);
|
||||
expect(useFavoritesStore.getState().items).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("adds item with same id but different platform", () => {
|
||||
useFavoritesStore.getState().addFavorite(mockItem);
|
||||
useFavoritesStore.getState().addFavorite(mockItemSameIdDiffPlatform);
|
||||
expect(useFavoritesStore.getState().items).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("adds multiple different items", () => {
|
||||
useFavoritesStore.getState().addFavorite(mockItem);
|
||||
useFavoritesStore.getState().addFavorite(mockItem2);
|
||||
expect(useFavoritesStore.getState().items).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("removeFavorite", () => {
|
||||
it("removes item by id and platform", () => {
|
||||
useFavoritesStore.getState().addFavorite(mockItem);
|
||||
useFavoritesStore.getState().addFavorite(mockItem2);
|
||||
|
||||
useFavoritesStore.getState().removeFavorite("123", "douyin");
|
||||
|
||||
const items = useFavoritesStore.getState().items;
|
||||
expect(items).toHaveLength(1);
|
||||
expect(items[0].id).toBe("456");
|
||||
});
|
||||
|
||||
it("does nothing when removing non-existent item", () => {
|
||||
useFavoritesStore.getState().addFavorite(mockItem);
|
||||
useFavoritesStore.getState().removeFavorite("999", "douyin");
|
||||
expect(useFavoritesStore.getState().items).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("only removes matching platform (not same id different platform)", () => {
|
||||
useFavoritesStore.getState().addFavorite(mockItem);
|
||||
useFavoritesStore.getState().addFavorite(mockItemSameIdDiffPlatform);
|
||||
|
||||
useFavoritesStore.getState().removeFavorite("123", "douyin");
|
||||
|
||||
const items = useFavoritesStore.getState().items;
|
||||
expect(items).toHaveLength(1);
|
||||
expect(items[0].platform).toBe("tiktok");
|
||||
});
|
||||
});
|
||||
|
||||
describe("isFavorited", () => {
|
||||
it("returns false when item is not favorited", () => {
|
||||
expect(
|
||||
useFavoritesStore.getState().isFavorited("123", "douyin")
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("returns true when item is favorited", () => {
|
||||
useFavoritesStore.getState().addFavorite(mockItem);
|
||||
expect(
|
||||
useFavoritesStore.getState().isFavorited("123", "douyin")
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("returns false for same id but different platform", () => {
|
||||
useFavoritesStore.getState().addFavorite(mockItem);
|
||||
expect(
|
||||
useFavoritesStore.getState().isFavorited("123", "tiktok")
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("returns false after item is removed", () => {
|
||||
useFavoritesStore.getState().addFavorite(mockItem);
|
||||
useFavoritesStore.getState().removeFavorite("123", "douyin");
|
||||
expect(
|
||||
useFavoritesStore.getState().isFavorited("123", "douyin")
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
"use client";
|
||||
|
||||
import { create } from "zustand";
|
||||
import { persist } from "zustand/middleware";
|
||||
import type { ContentItem, Platform } from "@muse/shared";
|
||||
|
||||
interface FavoritesStore {
|
||||
items: ContentItem[];
|
||||
addFavorite: (item: ContentItem) => void;
|
||||
removeFavorite: (id: string, platform: Platform) => void;
|
||||
isFavorited: (id: string, platform: Platform) => boolean;
|
||||
}
|
||||
|
||||
export const useFavoritesStore = create<FavoritesStore>()(
|
||||
persist(
|
||||
(set, get) => ({
|
||||
items: [],
|
||||
addFavorite: (item) =>
|
||||
set((state) => {
|
||||
// Dedup by id + platform
|
||||
const exists = state.items.some(
|
||||
(i) => i.id === item.id && i.platform === item.platform
|
||||
);
|
||||
if (exists) return state;
|
||||
return { items: [...state.items, item] };
|
||||
}),
|
||||
removeFavorite: (id, platform) =>
|
||||
set((state) => ({
|
||||
items: state.items.filter(
|
||||
(i) => !(i.id === id && i.platform === platform)
|
||||
),
|
||||
})),
|
||||
isFavorited: (id, platform) =>
|
||||
get().items.some((i) => i.id === id && i.platform === platform),
|
||||
}),
|
||||
{
|
||||
name: "muse-favorites",
|
||||
// Handle data corruption
|
||||
onRehydrateStorage: () => (state) => {
|
||||
if (state && !Array.isArray(state.items)) {
|
||||
state.items = [];
|
||||
}
|
||||
},
|
||||
}
|
||||
)
|
||||
);
|
||||
@@ -0,0 +1,89 @@
|
||||
import { describe, it, expect, beforeEach } from "vitest";
|
||||
import { useSettingsStore } from "./settings";
|
||||
|
||||
describe("useSettingsStore", () => {
|
||||
beforeEach(() => {
|
||||
// Reset store to default state
|
||||
useSettingsStore.setState({
|
||||
apiKey: "",
|
||||
refreshInterval: 30,
|
||||
enabledPlatforms: {
|
||||
douyin: true,
|
||||
tiktok: true,
|
||||
xiaohongshu: true,
|
||||
},
|
||||
displayCount: 20,
|
||||
});
|
||||
});
|
||||
|
||||
describe("default values", () => {
|
||||
it("has empty apiKey by default", () => {
|
||||
expect(useSettingsStore.getState().apiKey).toBe("");
|
||||
});
|
||||
|
||||
it("has 30 minute refresh interval by default", () => {
|
||||
expect(useSettingsStore.getState().refreshInterval).toBe(30);
|
||||
});
|
||||
|
||||
it("has all 3 platforms enabled by default", () => {
|
||||
const platforms = useSettingsStore.getState().enabledPlatforms;
|
||||
expect(platforms.douyin).toBe(true);
|
||||
expect(platforms.tiktok).toBe(true);
|
||||
expect(platforms.xiaohongshu).toBe(true);
|
||||
});
|
||||
|
||||
it("has display count of 20 by default", () => {
|
||||
expect(useSettingsStore.getState().displayCount).toBe(20);
|
||||
});
|
||||
});
|
||||
|
||||
describe("setApiKey", () => {
|
||||
it("sets the API key", () => {
|
||||
useSettingsStore.getState().setApiKey("test-key-123");
|
||||
expect(useSettingsStore.getState().apiKey).toBe("test-key-123");
|
||||
});
|
||||
|
||||
it("can clear the API key", () => {
|
||||
useSettingsStore.getState().setApiKey("test-key");
|
||||
useSettingsStore.getState().setApiKey("");
|
||||
expect(useSettingsStore.getState().apiKey).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("setRefreshInterval", () => {
|
||||
it("sets refresh interval to valid values", () => {
|
||||
const validValues: (5 | 10 | 15 | 30 | 60)[] = [5, 10, 15, 30, 60];
|
||||
validValues.forEach((val) => {
|
||||
useSettingsStore.getState().setRefreshInterval(val);
|
||||
expect(useSettingsStore.getState().refreshInterval).toBe(val);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("togglePlatform", () => {
|
||||
it("disables an enabled platform", () => {
|
||||
useSettingsStore.getState().togglePlatform("douyin");
|
||||
expect(useSettingsStore.getState().enabledPlatforms.douyin).toBe(false);
|
||||
});
|
||||
|
||||
it("enables a disabled platform", () => {
|
||||
useSettingsStore.getState().togglePlatform("douyin");
|
||||
useSettingsStore.getState().togglePlatform("douyin");
|
||||
expect(useSettingsStore.getState().enabledPlatforms.douyin).toBe(true);
|
||||
});
|
||||
|
||||
it("does not affect other platforms", () => {
|
||||
useSettingsStore.getState().togglePlatform("tiktok");
|
||||
expect(useSettingsStore.getState().enabledPlatforms.douyin).toBe(true);
|
||||
expect(useSettingsStore.getState().enabledPlatforms.tiktok).toBe(false);
|
||||
expect(useSettingsStore.getState().enabledPlatforms.xiaohongshu).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("setDisplayCount", () => {
|
||||
it("sets display count", () => {
|
||||
useSettingsStore.getState().setDisplayCount(50);
|
||||
expect(useSettingsStore.getState().displayCount).toBe(50);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
"use client";
|
||||
|
||||
import { create } from "zustand";
|
||||
import { persist } from "zustand/middleware";
|
||||
import type { Platform } from "@muse/shared";
|
||||
|
||||
interface SettingsStore {
|
||||
apiKey: string;
|
||||
refreshInterval: 5 | 10 | 15 | 30 | 60;
|
||||
enabledPlatforms: Record<string, boolean>;
|
||||
displayCount: number;
|
||||
setApiKey: (key: string) => void;
|
||||
setRefreshInterval: (minutes: 5 | 10 | 15 | 30 | 60) => void;
|
||||
togglePlatform: (platform: Platform) => void;
|
||||
setDisplayCount: (count: number) => void;
|
||||
}
|
||||
|
||||
export const useSettingsStore = create<SettingsStore>()(
|
||||
persist(
|
||||
(set) => ({
|
||||
apiKey: "",
|
||||
refreshInterval: 30,
|
||||
enabledPlatforms: {
|
||||
douyin: true,
|
||||
tiktok: true,
|
||||
xiaohongshu: true,
|
||||
},
|
||||
displayCount: 20,
|
||||
setApiKey: (key) => set({ apiKey: key }),
|
||||
setRefreshInterval: (minutes) => set({ refreshInterval: minutes }),
|
||||
togglePlatform: (platform) =>
|
||||
set((state) => ({
|
||||
enabledPlatforms: {
|
||||
...state.enabledPlatforms,
|
||||
[platform]: !state.enabledPlatforms[platform],
|
||||
},
|
||||
})),
|
||||
setDisplayCount: (count) => set({ displayCount: count }),
|
||||
}),
|
||||
{
|
||||
name: "muse-settings",
|
||||
}
|
||||
)
|
||||
);
|
||||
Reference in New Issue
Block a user