- 不再依赖 zhparser 分词:关键词按空格拆分,全部需在描述或语音转写中以子串出现;-词 表示排除 - 英文/数字关键词要求词首对齐,避免 ai 命中 said - 按描述/转写命中次数打分,同分按发布时间倒序;总数随查询一并返回 - 返回结构化高亮片段(descParts / snippet),前端高亮描述与转写命中位置 - 前端显示描述/语音命中标记、真实结果总数,并支持加载更多 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
464 lines
17 KiB
TypeScript
464 lines
17 KiB
TypeScript
"use client";
|
|
|
|
import { ArrowLeft, FileText, Mic, Search, X } from "lucide-react";
|
|
import Image from "next/image";
|
|
import Link from "next/link";
|
|
import { useRouter, useSearchParams } from "next/navigation";
|
|
import {
|
|
type FormEvent,
|
|
useCallback,
|
|
useEffect,
|
|
useRef,
|
|
useState,
|
|
} from "react";
|
|
import type { SnippetPart } from "@/lib/search";
|
|
import { isVideoContentTag, VIDEO_CONTENT_TAGS } from "@/lib/video-tags";
|
|
|
|
// 匹配搜索结果类型(适配后端API)
|
|
type SearchResultItem = {
|
|
id: string;
|
|
awemeId: string;
|
|
type: "video" | "image";
|
|
score: number;
|
|
matchedIn: ("desc" | "transcript")[];
|
|
descParts: SnippetPart[]; // 完整描述,标出命中位置
|
|
snippet: SnippetPart[] | null; // 语音转写的命中片段
|
|
contentTags: string[];
|
|
video?: {
|
|
aweme_id: string;
|
|
desc: string;
|
|
cover_url: string | null;
|
|
video_url: string | null;
|
|
duration_ms: number;
|
|
author: {
|
|
sec_uid: string;
|
|
nickname: string;
|
|
avatar_url: string | null;
|
|
};
|
|
};
|
|
imagePost?: {
|
|
aweme_id: string;
|
|
desc: string;
|
|
cover_url: string | null;
|
|
author: {
|
|
sec_uid: string;
|
|
nickname: string;
|
|
avatar_url: string | null;
|
|
};
|
|
};
|
|
};
|
|
|
|
const PAGE_SIZE = 30;
|
|
|
|
function renderParts(parts: SnippetPart[]) {
|
|
let offset = 0;
|
|
return parts.map((part) => {
|
|
const key = `${offset}-${part.text}`;
|
|
offset += part.text.length;
|
|
return part.hit ? (
|
|
<mark
|
|
key={key}
|
|
className="rounded-sm bg-yellow-400/80 px-0.5 text-zinc-950"
|
|
>
|
|
{part.text}
|
|
</mark>
|
|
) : (
|
|
<span key={key}>{part.text}</span>
|
|
);
|
|
});
|
|
}
|
|
|
|
export default function SearchClient({
|
|
initialQuery,
|
|
}: {
|
|
initialQuery: string;
|
|
}) {
|
|
const searchParams = useSearchParams();
|
|
const router = useRouter();
|
|
|
|
const [query, setQuery] = useState(initialQuery);
|
|
const [results, setResults] = useState<SearchResultItem[]>([]);
|
|
const [total, setTotal] = useState(0);
|
|
const [page, setPage] = useState(1);
|
|
const [loading, setLoading] = useState(false);
|
|
const [loadingMore, setLoadingMore] = useState(false);
|
|
// 只采用最近一次请求的结果,避免快速切换关键词时旧结果覆盖新结果
|
|
const requestIdRef = useRef(0);
|
|
const [searched, setSearched] = useState(false);
|
|
const [selectedTag, setSelectedTag] = useState<string | null>(null);
|
|
|
|
const buildSearchHref = useCallback((q: string, tag: string | null) => {
|
|
const params = new URLSearchParams();
|
|
const trimmed = q.trim();
|
|
if (trimmed) params.set("q", trimmed);
|
|
if (tag) params.set("tag", tag);
|
|
const queryString = params.toString();
|
|
return queryString ? `/search?${queryString}` : "/search";
|
|
}, []);
|
|
|
|
const fetchPage = useCallback(
|
|
async (q: string, tag: string | null, pageNum: number) => {
|
|
const params = new URLSearchParams({
|
|
limit: String(PAGE_SIZE),
|
|
page: String(pageNum),
|
|
});
|
|
if (q) params.set("q", q);
|
|
if (tag) params.set("tag", tag);
|
|
const res = await fetch(`/api/search?${params.toString()}`);
|
|
if (!res.ok) throw new Error("Search failed");
|
|
return (await res.json()) as {
|
|
results?: SearchResultItem[];
|
|
total?: number;
|
|
};
|
|
},
|
|
[],
|
|
);
|
|
|
|
const performSearch = useCallback(
|
|
async (q: string, tag: string | null) => {
|
|
const trimmed = q.trim();
|
|
const requestId = ++requestIdRef.current;
|
|
if (!trimmed && !tag) {
|
|
setResults([]);
|
|
setTotal(0);
|
|
setSearched(false);
|
|
return;
|
|
}
|
|
setLoading(true);
|
|
setSearched(true);
|
|
setPage(1);
|
|
try {
|
|
const data = await fetchPage(trimmed, tag, 1);
|
|
if (requestId !== requestIdRef.current) return;
|
|
setResults(data.results || []);
|
|
setTotal(data.total ?? 0);
|
|
} catch (err) {
|
|
if (requestId !== requestIdRef.current) return;
|
|
console.error("Search error:", err);
|
|
setResults([]);
|
|
setTotal(0);
|
|
} finally {
|
|
if (requestId === requestIdRef.current) setLoading(false);
|
|
}
|
|
},
|
|
[fetchPage],
|
|
);
|
|
|
|
const loadMore = async () => {
|
|
const q = (searchParams.get("q") || "").trim();
|
|
const tagParam = searchParams.get("tag") || "";
|
|
const tag = tagParam && isVideoContentTag(tagParam) ? tagParam : null;
|
|
const requestId = requestIdRef.current;
|
|
const nextPage = page + 1;
|
|
setLoadingMore(true);
|
|
try {
|
|
const data = await fetchPage(q, tag, nextPage);
|
|
if (requestId !== requestIdRef.current) return;
|
|
setResults((prev) => {
|
|
const seen = new Set(prev.map((r) => r.id));
|
|
return [
|
|
...prev,
|
|
...(data.results || []).filter((r) => !seen.has(r.id)),
|
|
];
|
|
});
|
|
setTotal(data.total ?? 0);
|
|
setPage(nextPage);
|
|
} catch (err) {
|
|
console.error("Search error:", err);
|
|
} finally {
|
|
if (requestId === requestIdRef.current) setLoadingMore(false);
|
|
}
|
|
};
|
|
|
|
// 初始 & URL 变化时同步(用 searchParams 订阅 URL 更稳妥)
|
|
useEffect(() => {
|
|
const q = searchParams.get("q") || "";
|
|
const tagParam = searchParams.get("tag") || "";
|
|
const tag = tagParam && isVideoContentTag(tagParam) ? tagParam : null;
|
|
setQuery(q);
|
|
setSelectedTag(tag);
|
|
if (q || tag) {
|
|
performSearch(q, tag);
|
|
} else {
|
|
requestIdRef.current++;
|
|
setResults([]);
|
|
setTotal(0);
|
|
setSearched(false);
|
|
}
|
|
}, [searchParams, performSearch]);
|
|
|
|
const handleSearch = (e: FormEvent) => {
|
|
e.preventDefault();
|
|
const trimmed = query.trim();
|
|
if (!trimmed && !selectedTag) return;
|
|
router.push(buildSearchHref(trimmed, selectedTag));
|
|
};
|
|
|
|
const handleTagSelect = (tag: string) => {
|
|
const nextTag = selectedTag === tag ? null : tag;
|
|
setSelectedTag(nextTag);
|
|
router.push(buildSearchHref(query, nextTag));
|
|
};
|
|
|
|
const handleClear = () => {
|
|
setQuery("");
|
|
setSelectedTag(null);
|
|
setResults([]);
|
|
setTotal(0);
|
|
setSearched(false);
|
|
router.push("/search");
|
|
};
|
|
|
|
return (
|
|
<div className="min-h-screen bg-zinc-950 text-white">
|
|
{/* 顶部搜索栏 */}
|
|
<header className="sticky top-0 z-50 bg-zinc-900/80 backdrop-blur-xl border-b border-white/10">
|
|
<div className="max-w-7xl mx-auto px-4 py-4 flex items-center gap-4">
|
|
<button
|
|
type="button"
|
|
onClick={() => router.push("/")}
|
|
className="p-2 rounded-full hover:bg-white/10 transition-colors"
|
|
aria-label="返回首页"
|
|
>
|
|
<ArrowLeft size={24} />
|
|
</button>
|
|
|
|
<form
|
|
onSubmit={handleSearch}
|
|
className="flex-1 flex items-center gap-3"
|
|
>
|
|
<div className="relative flex-1">
|
|
<input
|
|
type="text"
|
|
value={query}
|
|
onChange={(e) => setQuery(e.target.value)}
|
|
placeholder="搜索视频、图文描述或语音内容..."
|
|
className="w-full bg-white/5 border border-white/10 rounded-full px-5 py-3 pl-12 pr-12 text-white placeholder-white/40 focus:outline-none focus:ring-2 focus:ring-blue-500/50 focus:border-blue-500/50 transition-all"
|
|
/>
|
|
<Search
|
|
size={20}
|
|
className="absolute left-4 top-1/2 -translate-y-1/2 text-white/40"
|
|
/>
|
|
{(query || selectedTag) && (
|
|
<button
|
|
type="button"
|
|
onClick={handleClear}
|
|
className="absolute right-4 top-1/2 -translate-y-1/2 p-1 rounded-full hover:bg-white/10 transition-colors"
|
|
aria-label="清空"
|
|
>
|
|
<X size={18} className="text-white/60" />
|
|
</button>
|
|
)}
|
|
</div>
|
|
<button
|
|
type="submit"
|
|
className="px-6 py-3 bg-blue-600 hover:bg-blue-700 rounded-full font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
|
disabled={loading || (!query.trim() && !selectedTag)}
|
|
>
|
|
{loading ? "搜索中..." : "搜索"}
|
|
</button>
|
|
</form>
|
|
</div>
|
|
<div className="max-w-7xl mx-auto px-4 pb-4">
|
|
<div className="flex gap-2 overflow-x-auto">
|
|
{VIDEO_CONTENT_TAGS.map((tag) => (
|
|
<button
|
|
key={tag}
|
|
type="button"
|
|
onClick={() => handleTagSelect(tag)}
|
|
className={`flex-shrink-0 rounded-full border px-3 py-1.5 text-xs font-medium transition-colors ${
|
|
selectedTag === tag
|
|
? "border-blue-400 bg-blue-500/20 text-blue-200"
|
|
: "border-white/10 bg-white/5 text-white/60 hover:border-white/20 hover:text-white"
|
|
}`}
|
|
>
|
|
{tag}
|
|
</button>
|
|
))}
|
|
</div>
|
|
</div>
|
|
</header>
|
|
|
|
{/* 结果区域 */}
|
|
<main className="max-w-7xl mx-auto px-4 py-8">
|
|
{loading && (
|
|
<div className="flex items-center justify-center py-20">
|
|
<div className="flex flex-col items-center gap-4">
|
|
<div className="w-12 h-12 border-4 border-blue-500/30 border-t-blue-500 rounded-full animate-spin" />
|
|
<p className="text-white/60">正在搜索...</p>
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
{!loading && searched && results.length === 0 && (
|
|
<div className="flex flex-col items-center justify-center py-20 text-white/60">
|
|
<Search size={64} className="mb-4 opacity-20" />
|
|
<p className="text-xl">未找到相关内容</p>
|
|
<p className="text-sm mt-2">试试其他关键词</p>
|
|
</div>
|
|
)}
|
|
|
|
{!loading && !searched && !query && !selectedTag && (
|
|
<div className="flex flex-col items-center justify-center py-20 text-white/40">
|
|
<Search size={64} className="mb-4 opacity-20" />
|
|
<p className="text-xl">输入关键词开始搜索</p>
|
|
<p className="text-sm mt-2">
|
|
按原文匹配描述和语音转写,多个关键词用空格分隔,以 - 开头表示排除
|
|
</p>
|
|
</div>
|
|
)}
|
|
|
|
{!loading && results.length > 0 && (
|
|
<div>
|
|
<div className="mb-6 flex items-center justify-between">
|
|
<h2 className="text-lg text-white/80">
|
|
找到 <span className="text-white font-semibold">{total}</span>{" "}
|
|
个结果
|
|
</h2>
|
|
</div>
|
|
|
|
{/* 单列列表布局 */}
|
|
<div className="space-y-4">
|
|
{results.map((item) => {
|
|
const content =
|
|
item.type === "video" ? item.video : item.imagePost;
|
|
if (!content) return null;
|
|
|
|
return (
|
|
<div
|
|
key={item.id}
|
|
className="bg-white/5 backdrop-blur-sm border border-white/10 rounded-2xl overflow-hidden hover:border-white/20 transition-all hover:-translate-y-1"
|
|
>
|
|
{/* 主内容区 */}
|
|
<div className="flex gap-4 p-4">
|
|
{/* 左侧:封面预览 */}
|
|
<Link
|
|
href={`/aweme/${content.aweme_id}`}
|
|
target="_blank"
|
|
className="flex-shrink-0 w-64 h-80 sm:w-70 sm:h-96 rounded-xl overflow-hidden bg-zinc-900 group"
|
|
>
|
|
{content.cover_url ? (
|
|
<Image
|
|
src={content.cover_url}
|
|
alt={content.desc}
|
|
width={280}
|
|
height={384}
|
|
unoptimized
|
|
className="w-full h-full object-cover transition-transform duration-300 group-hover:scale-105"
|
|
/>
|
|
) : (
|
|
<div className="h-full w-full bg-zinc-800" />
|
|
)}
|
|
</Link>
|
|
|
|
{/* 右侧:信息区 */}
|
|
<div className="flex-1 min-w-0 flex flex-col">
|
|
{/* 类型标签 */}
|
|
<div className="flex items-center gap-2 mb-2">
|
|
<span
|
|
className={`px-2 py-0.5 text-xs rounded ${
|
|
item.type === "video"
|
|
? "bg-blue-600/20 text-blue-300"
|
|
: "bg-purple-600/20 text-purple-300"
|
|
}`}
|
|
>
|
|
{item.type === "video" ? "视频" : "图文"}
|
|
</span>
|
|
{item.matchedIn.includes("desc") && (
|
|
<span className="flex items-center gap-1 px-2 py-0.5 bg-green-600/20 text-green-300 text-xs rounded">
|
|
<FileText size={12} />
|
|
描述命中
|
|
</span>
|
|
)}
|
|
{item.matchedIn.includes("transcript") && (
|
|
<span className="flex items-center gap-1 px-2 py-0.5 bg-green-600/20 text-green-300 text-xs rounded">
|
|
<Mic size={12} />
|
|
语音命中
|
|
</span>
|
|
)}
|
|
{item.contentTags.map((tag) => (
|
|
<span
|
|
key={tag}
|
|
className="px-2 py-0.5 text-xs rounded bg-blue-500/15 text-blue-200"
|
|
>
|
|
{tag}
|
|
</span>
|
|
))}
|
|
</div>
|
|
|
|
{/* 描述 */}
|
|
<Link
|
|
href={`/aweme/${content.aweme_id}`}
|
|
target="_blank"
|
|
>
|
|
<p className="text-white/90 text-sm sm:text-base line-clamp-3 mb-3 hover:text-white transition-colors">
|
|
{item.descParts.length > 0
|
|
? renderParts(item.descParts)
|
|
: "无描述"}
|
|
</p>
|
|
</Link>
|
|
|
|
{/* 作者信息 */}
|
|
<div className="flex items-center gap-2 mb-4">
|
|
{content.author.avatar_url ? (
|
|
<Image
|
|
src={content.author.avatar_url}
|
|
alt={content.author.nickname}
|
|
width={24}
|
|
height={24}
|
|
unoptimized
|
|
className="w-6 h-6 rounded-full ring-1 ring-white/20"
|
|
/>
|
|
) : (
|
|
<div className="h-6 w-6 rounded-full bg-white/10 ring-1 ring-white/20" />
|
|
)}
|
|
<span className="text-xs text-white/60">
|
|
{content.author.nickname}
|
|
</span>
|
|
</div>
|
|
|
|
{/* 语音转写片段:命中时展示命中位置附近的文字 */}
|
|
{item.snippet && item.snippet.length > 0 && (
|
|
<div>
|
|
<h4 className="flex items-center gap-2 text-xs font-medium text-green-300 mb-1.5">
|
|
<Mic size={14} />
|
|
{item.matchedIn.includes("transcript")
|
|
? "语音内容"
|
|
: "语音转写"}
|
|
</h4>
|
|
<div
|
|
className="text-xs text-white/70 bg-white/5 rounded-lg p-2 leading-relaxed"
|
|
style={{ wordBreak: "break-word" }}
|
|
>
|
|
{renderParts(item.snippet)}
|
|
</div>
|
|
</div>
|
|
)}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
})}
|
|
</div>
|
|
|
|
{results.length < total && (
|
|
<div className="mt-8 flex justify-center">
|
|
<button
|
|
type="button"
|
|
onClick={loadMore}
|
|
disabled={loadingMore}
|
|
className="rounded-full border border-white/10 bg-white/5 px-6 py-2.5 text-sm text-white/80 transition-colors hover:border-white/20 hover:text-white disabled:opacity-50"
|
|
>
|
|
{loadingMore
|
|
? "加载中..."
|
|
: `加载更多(还有 ${total - results.length} 个)`}
|
|
</button>
|
|
</div>
|
|
)}
|
|
</div>
|
|
)}
|
|
</main>
|
|
</div>
|
|
);
|
|
}
|