时间范围
-
+
推荐等级
@@ -277,7 +277,7 @@ export function FilterPanel({
{activeFilterCount > 0 && (
-
@@ -393,7 +393,7 @@ export function TopicBoard({
{topic.name}
- {topic.summary &&
{topic.summary}
}
+ {topic.summary &&
{topic.summary}
}
{topicItems.length} 条
@@ -482,7 +482,7 @@ export function PickCard({
const score = scoreOf(item);
const tags = tagsOf(analysis);
const recommendation = analysis?.recommendation || analysis?.recommended_reason || item.summary || '';
- const scoreClass = score >= 80 ? 'text-primary' : score >= 70 ? 'text-amber' : 'text-teal';
+ const scoreClass = score >= 80 ? 'text-primary-text' : score >= 70 ? 'text-amber-800' : 'text-teal-text';
const [showBreakdown, setShowBreakdown] = useState(false);
const breakdown = analysis?.score_breakdown;
@@ -510,7 +510,7 @@ export function PickCard({
/
-
{timeAgo(item.published_at || item.crawled_at)}
+
{timeAgo(item.published_at || item.crawled_at)}
{analysis?.summary_source === 'local_fallback' && (
)}
- {item.category && {item.category}}
- {item.content_type && {item.content_type}}
+ {item.category && {item.category}}
+ {item.content_type && {item.content_type}}
{tags.slice(0, 3).map((tag) => (
-
+
{tag}
))}
@@ -532,7 +532,7 @@ export function PickCard({
{item.title}
{recommendation && (
-
+
{recommendation}
)}
@@ -557,12 +557,12 @@ export function PickCard({
{Math.round(score)}
- 分
+ 分
{breakdown && (
{ e.stopPropagation(); setShowBreakdown((v) => !v); }}
- className="mt-2 inline-flex items-center gap-0.5 rounded-xs border border-gray-200 bg-white px-1.5 py-0.5 text-[10px] font-bold text-gray-500 transition hover:border-primary-border hover:text-primary"
+ className="mt-2 inline-flex items-center gap-0.5 rounded-xs border border-gray-200 bg-white px-1.5 py-0.5 text-[10px] font-bold text-gray-600 transition hover:border-primary-border hover:text-primary-text"
title={showBreakdown ? '收起评分解释' : '展开评分解释'}
>
@@ -599,10 +599,10 @@ export function PickActions({
}) {
const actionClass = dark
? 'border-white/15 bg-white/10 text-gray-200 hover:bg-white/15'
- : 'border-gray-200 bg-white text-gray-600 hover:border-primary-border hover:text-primary';
+ : 'border-gray-200 bg-white text-gray-600 hover:border-primary-border hover:text-primary-text';
const linkClass = dark
? 'border-white/15 bg-white/10 text-gray-200 hover:bg-white/15'
- : 'border-teal-border bg-teal-light text-teal hover:border-teal-border';
+ : 'border-teal-border bg-teal-light text-teal-text hover:border-teal-border';
return (
@@ -647,7 +647,7 @@ export function PickActions({
className={cx(
'inline-flex items-center gap-1.5 rounded-xs border px-2.5 py-1.5 text-[11px] font-bold transition',
dark ? 'border-white/15 bg-white/10 hover:bg-white/15' : 'border-gray-200 bg-white hover:border-amber-border',
- isFav ? 'text-amber' : dark ? 'text-gray-300' : 'text-gray-400',
+ isFav ? (dark ? 'text-amber-300' : 'text-amber-800') : dark ? 'text-gray-300' : 'text-gray-600',
)}
>
收藏
@@ -688,7 +688,7 @@ export function TopicToggle({
{label}
@@ -704,7 +704,7 @@ export function SectionHeading({ title, count }: { title: string; count: number
return (
{title}
- {count}
+ {count}
);
}
diff --git a/frontend/src/app/today-picks/page.tsx b/frontend/src/app/today-picks/page.tsx
index ff3cb353..50ca02c2 100644
--- a/frontend/src/app/today-picks/page.tsx
+++ b/frontend/src/app/today-picks/page.tsx
@@ -1,6 +1,6 @@
'use client';
-import React, { Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import React, { Suspense, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import {
ChevronDown,
@@ -9,13 +9,15 @@ import {
List,
} from 'lucide-react';
import { contentsApi } from '@/lib/api';
+import { PICKS_VIEWS, picksViewHref, readPicksView, readSnapshotDays, type PicksView } from '@/lib/picks-view';
+import TrendExplorer from '../trends/TrendExplorer';
import type { EvidenceMark } from '@/types';
import { useAppContext } from '@/components/ClientLayout';
import AnalysisPanel from '@/components/AnalysisPanel';
import { PendingReview } from './_pending-review';
import RadarSignature from '@/components/RadarSignature';
-import { Badge, Button, Panel, cx } from '@/components/ui';
-import { EmptyState, LoadingState } from '@/components/StateView';
+import { Button, cx } from '@/components/ui';
+import { EmptyState, ErrorState, LoadingState } from '@/components/StateView';
import { useContentFavoriteStates } from '@/hooks/useContentFavoriteStates';
import { useFetch } from '@/hooks/useFetch';
import { getRecommendLevelLabel } from '@/lib/utils';
@@ -45,7 +47,7 @@ import {
} from './_components';
export default function TodayPicksPageWrapper() {
return (
- 加载中... }>
+ 加载中... }>
);
@@ -54,51 +56,70 @@ export default function TodayPicksPageWrapper() {
function TodayPicksPage() {
const searchParams = useSearchParams();
const router = useRouter();
+ const pageView = readPicksView(searchParams.get('view'));
+ const snapshotDays = readSnapshotDays(searchParams.get('days'));
+ const scrollRef = useRef(null);
+ const viewScrolls = useRef>({});
+ const restoringScroll = useRef(null);
const { toggleFavorite, currentUser, reportTodayPicksTotal, openReader } = useAppContext();
- const [selectedCategory, setSelectedCategory] = useState(searchParams.get('category') || '');
- const [selectedContentType, setSelectedContentType] = useState(searchParams.get('content_type') || '');
- const [selectedLevel, setSelectedLevel] = useState(searchParams.get('level') || '');
- const [selectedTimeRange, setSelectedTimeRange] = useState(normalizeTimeRange(searchParams.get('time_range')));
+ const selectedCategory = searchParams.get('category') || '';
+ const selectedContentType = searchParams.get('content_type') || '';
+ const selectedLevel = searchParams.get('level') || '';
+ const selectedTimeRange = normalizeTimeRange(searchParams.get('time_range'));
+ const picksScope = JSON.stringify([selectedCategory, selectedContentType, selectedTimeRange]);
+ const scrollKey = pageView === 'picks' ? `picks:${picksScope}:${selectedLevel}` : `${pageView}:${snapshotDays}`;
+ useLayoutEffect(() => { restoringScroll.current = scrollKey; if (scrollRef.current) scrollRef.current.scrollTop = 0; }, [scrollKey]);
+ const restoreScroll = useCallback(() => {
+ if (restoringScroll.current !== scrollKey) return;
+ requestAnimationFrame(() => {
+ if (restoringScroll.current !== scrollKey || !scrollRef.current) return;
+ scrollRef.current.scrollTop = viewScrolls.current[scrollKey] ?? 0;
+ restoringScroll.current = null;
+ });
+ }, [scrollKey]);
const [selectedAnalysis, setSelectedAnalysis] = useState<(ContentAnalysis & { _content_id?: number }) | null>(null);
const [filtersOpen, setFiltersOpen] = useState(false);
const [groupByTopic, setGroupByTopic] = useState(true);
const [expandedTopics, setExpandedTopics] = useState>(new Set());
+ const [materialLimits, setMaterialLimits] = useState>({});
+ const rememberMaterialLimit = useCallback((limit: number) => setMaterialLimits(current => ({ ...current, [snapshotDays]: limit })), [snapshotDays]);
const [workflowPendingId, setWorkflowPendingId] = useState(null);
const [actionError, setActionError] = useState(null);
const updateURL = useCallback((cat: string, ct: string, level: string, tr: string) => {
- const params = new URLSearchParams();
- if (cat) params.set('category', cat);
- if (ct) params.set('content_type', ct);
- if (level) params.set('level', level);
- if (tr && tr !== DEFAULT_TIME_RANGE) params.set('time_range', tr);
+ const params = new URLSearchParams(searchParams.toString());
+ for (const [key, value] of [['category', cat], ['content_type', ct], ['level', level], ['time_range', tr === DEFAULT_TIME_RANGE ? '' : tr]]) { if (value) params.set(key, value); else params.delete(key); }
const qs = params.toString();
router.replace(`/today-picks${qs ? '?' + qs : ''}`, { scroll: false });
- }, [router]);
+ }, [router, searchParams]);
const setCategory = (cat: string) => {
- setSelectedCategory(cat);
updateURL(cat, selectedContentType, selectedLevel, selectedTimeRange);
};
const setContentType = (ct: string) => {
- setSelectedContentType(ct);
updateURL(selectedCategory, ct, selectedLevel, selectedTimeRange);
};
const setLevel = (level: string) => {
const next = selectedLevel === level ? '' : level;
- setSelectedLevel(next);
updateURL(selectedCategory, selectedContentType, next, selectedTimeRange);
};
const setTimeRange = (tr: string) => {
- setSelectedTimeRange(tr);
updateURL(selectedCategory, selectedContentType, selectedLevel, tr);
};
+ const changePageView = (next: PicksView) => {
+ if (next === pageView) return;
+ viewScrolls.current[scrollKey] = scrollRef.current?.scrollTop ?? 0;
+ setSelectedAnalysis(null);
+ router.push(picksViewHref(next, new URLSearchParams(searchParams.toString())), { scroll: false });
+ };
+ const changeSnapshotDays = (days: number) => {
+ const params = new URLSearchParams(searchParams.toString());
+ params.set('days', String(days));
+ router.replace(picksViewHref(pageView, params), { scroll: false });
+ };
+
const clearFilters = () => {
- setSelectedCategory('');
- setSelectedContentType('');
- setSelectedLevel('');
- setSelectedTimeRange(DEFAULT_TIME_RANGE);
updateURL('', '', '', DEFAULT_TIME_RANGE);
};
@@ -123,11 +144,14 @@ function TodayPicksPage() {
return params;
}, [selectedCategory, selectedContentType, selectedTimeRange]);
- const fetchPicks = useCallback(() => contentsApi.todayPicks(buildParams(0)), [buildParams]);
+ const fetchPicks = useCallback(async () => ({ ...await contentsApi.todayPicks(buildParams(0)), scope: picksScope }), [buildParams, picksScope]);
- const { data, loading } = useFetch(fetchPicks, [selectedCategory, selectedContentType, selectedTimeRange]);
+ const { data: fetchedPicks, loading, error, refetch } = useFetch(fetchPicks, [selectedCategory, selectedContentType, selectedTimeRange]);
+ const data = fetchedPicks?.scope === picksScope ? fetchedPicks : null;
+ const picksBusy = loading || (!data && !error);
// 已加载的条目(首屏 + 后续页)。筛选变化时随首屏重置。
+ const [loadedFrom, setLoadedFrom] = useState(null);
const [loadedItems, setLoadedItems] = useState([]);
// 已加载条目涉及的话题。后端每页只返回本页涉及的话题,追加页的新话题
// 必须合并进来,否则话题视图下这些条目会因为没有对应分组而丢失。
@@ -145,14 +169,18 @@ function TodayPicksPage() {
loadMorePending.current = false;
setLoadingMore(false);
setLoadMoreError(null);
+ setLoadedFrom(data);
setLoadedItems(data?.items || []);
setLoadedTopics(data?.topics || []);
setServerHasMore(data?.has_more);
}, [data]);
- const items = loadedItems;
+ const projectionReady = data !== null && loadedFrom === data;
+ const picksLoading = picksBusy || (!!data && !projectionReady);
+ useLayoutEffect(() => { if (pageView === 'picks' && !picksLoading && projectionReady) restoreScroll(); }, [pageView, picksLoading, projectionReady, restoreScroll]);
+ const items = useMemo(() => projectionReady ? loadedItems : [], [projectionReady, loadedItems]);
const total = data?.total || 0;
- const topics = loadedTopics;
+ const topics = useMemo(() => projectionReady ? loadedTopics : [], [projectionReady, loadedTopics]);
const eventMemberCount = data?.event_members_hidden || 0;
const canLoadMore = hasMorePicks(items.length, total, serverHasMore);
@@ -189,7 +217,7 @@ function TodayPicksPage() {
const loadMoreAnchorRef = useRef(null);
useEffect(() => {
const anchor = loadMoreAnchorRef.current;
- if (!anchor) return;
+ if (!anchor || pageView !== 'picks') return;
const observer = new IntersectionObserver(
(entries) => {
if (entries.some((entry) => entry.isIntersecting)) void loadMore();
@@ -199,7 +227,7 @@ function TodayPicksPage() {
);
observer.observe(anchor);
return () => observer.disconnect();
- }, [loadMore]);
+ }, [loadMore, pageView]);
// 批量获取证据标记(避免每张卡片单独 API 调用 N+1)
const [evidenceMarks, setEvidenceMarks] = useState>({});
@@ -314,7 +342,7 @@ function TodayPicksPage() {
};
return (
-
+
{ if (restoringScroll.current === null) viewScrolls.current[scrollKey] = event.currentTarget.scrollTop; }} className="workspace-scroll">
@@ -322,36 +350,43 @@ function TodayPicksPage() {
当日精选
-
- CURATION DESK
-
-
- 从算法候选中筛出可写选题,按话题、质量和来源做二次判断
+
+ {pageView === 'picks' ? '从算法候选中筛出可写选题,按话题、质量和来源做二次判断' : '补充查看公共收录的材料与标签分布,观察窗口独立于精选筛选'}
-
setGroupByTopic(!groupByTopic)}
>
{groupByTopic ? :
}
- {groupByTopic ? '话题视图' : '列表视图'}
-
+ {groupByTopic ? '精选分组' : '精选列表'}
+ }
+
+
+ {PICKS_VIEWS.map((view, index) => changePageView(view.value)} onKeyDown={event => {
+ if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return;
+ event.preventDefault();
+ const next = event.key === 'Home' ? 0 : event.key === 'End' ? PICKS_VIEWS.length - 1 : (index + (event.key === 'ArrowRight' ? 1 : -1) + PICKS_VIEWS.length) % PICKS_VIEWS.length;
+ changePageView(PICKS_VIEWS[next].value);
+ document.getElementById(`picks-${PICKS_VIEWS[next].value}-tab`)?.focus();
+ }} className={cx('min-h-11 border-b-2 px-2 text-sm font-semibold transition-colors focus-visible:outline-2 focus-visible:outline-primary sm:px-1', pageView === view.value ? 'border-primary text-primary-text' : 'border-transparent text-gray-600 hover:text-gray-900')}>{view.label})}
+
-
+ />}
{actionError && (
@@ -372,9 +407,10 @@ function TodayPicksPage() {
/>
)}
- {loading ? (
+ {error && void refetch()} />}
+ {picksLoading ? (
- ) : filteredItems.length === 0 ? (
+ ) : error && !data ? null : filteredItems.length === 0 ? (
0 ? '筛选后没有匹配内容' : '当前窗口暂无精选内容'}
@@ -417,10 +453,10 @@ function TodayPicksPage() {
))}
)}
- {!loading && data?.pending_review && !selectedLevel && }
+ {!picksLoading && data?.pending_review && !selectedLevel && }
{/* 滚动加载锚点:进入视口即自动接下一批 */}
- {!loading && canLoadMore && (
+ {!picksLoading && canLoadMore && (
{loadingMore ? '正在加载…' : `加载更多(还有 ${Math.max(0, total - items.length)} 条)`}
-
+
{loadMoreError
? loadMoreError
: '向下滚动会自动加载更多,也可以点击按钮继续展开。'}
)}
- {!loading && !canLoadMore && items.length > 0 && (
-
+ {!picksLoading && !canLoadMore && items.length > 0 && (
+
已加载全部 {items.length} 条精选内容
)}
-
- {selectedAnalysis && setSelectedAnalysis(null)} />}
+
+ {(['topics', 'keywords'] as const).map(view =>
+ {pageView === view && }
+ )}
+ {pageView === 'picks' && selectedAnalysis && setSelectedAnalysis(null)} />}
);
}
diff --git a/frontend/src/app/trends/TopicMaterials.test.tsx b/frontend/src/app/trends/TopicMaterials.test.tsx
new file mode 100644
index 00000000..16f10b0e
--- /dev/null
+++ b/frontend/src/app/trends/TopicMaterials.test.tsx
@@ -0,0 +1,55 @@
+import React from 'react';
+import { renderToStaticMarkup } from 'react-dom/server';
+import { describe, expect, it, vi } from 'vitest';
+import { MaterialPage } from './TopicMaterials';
+
+const state = vi.hoisted(() => ({ data: null as unknown, loading: false, error: null as string | null }));
+vi.mock('@/hooks/useFetch', () => ({ useFetch: () => ({ ...state, refetch: vi.fn() }) }));
+vi.mock('@/components/ClientLayout', () => ({ useAppContext: () => ({ openReader: vi.fn() }) }));
+vi.mock('@/components/SourceBadge', () => ({ default: () => null }));
+vi.mock('@/components/EvidenceTag', () => ({ default: () => null }));
+const payload = {
+ summary: { content_count: 25, source_count: 2, provenance_status: 'sample_only' },
+ calculation: { event_members_excluded: false },
+ items: [{ content_id: null, title: '前一页的材料', url: null, selected: false, score: null }],
+ total: 25,
+};
+const render = (page: number) => renderToStaticMarkup();
+
+const content = (html: string) => html.replace(/<[^>]*>/g, '');
+describe('材料分页请求边界', () => {
+ it('翻页加载保留分页控件,隐藏前一页的内容', () => {
+ state.data = { page: 1, payload }; state.loading = true; state.error = null;
+ const html = render(2);
+ expect(content(html)).not.toContain('前一页的材料');
+ expect(html).toContain('正在读取这次快照的材料');
+ expect(html).toContain('aria-label="下一页材料"');
+ expect(html).toContain('aria-label="上一页材料"');
+ expect(html).toContain('2 / 2 页 · 读取中');
+ });
+ it('翻页失败仍保留分页与重试入口,不把旧页当新页', () => {
+ state.data = { page: 1, payload }; state.loading = false; state.error = '材料读取失败';
+ const html = render(2);
+ expect(content(html)).not.toContain('前一页的材料');
+ expect(html).toContain('role="alert"');
+ expect(html).toContain('重试');
+ expect(html).toContain('aria-label="上一页材料"');
+ });
+ it('不完整历史并列说明历史收录与实际可查看数量', () => {
+ state.data = { page: 1, payload: { ...payload, total: 3, summary: { ...payload.summary, content_count: 0 }, daily_counts: [{ date: '2026-11-03', count: 25 }] } }; state.loading = false; state.error = null;
+ const html = render(1);
+ expect(html).toContain('当前可查看 3 条');
+ expect(html).toContain('历史收录 25 条');
+ });
+ it('新页成功后只显示新页,并保留不完整记录提示', () => {
+ state.data = { page: 2, payload: { ...payload, items: [{ ...payload.items[0], title: '第二页的材料' }] } }; state.loading = false; state.error = null;
+ const html = render(2);
+ expect(content(html)).toContain('第二页的材料');
+ expect(content(html)).not.toContain('前一页的材料');
+ expect(html).toContain('历史成员记录不完整');
+ expect(html).toContain('当前可查看');
+ expect(html).toContain('历史收录');
+ expect(html).toContain('不能还原当时全部内容');
+ expect(html).toContain('aria-disabled="true"');
+ });
+});
diff --git a/frontend/src/app/trends/TopicMaterials.tsx b/frontend/src/app/trends/TopicMaterials.tsx
new file mode 100644
index 00000000..d04b0676
--- /dev/null
+++ b/frontend/src/app/trends/TopicMaterials.tsx
@@ -0,0 +1,76 @@
+'use client';
+
+import React, { useState } from 'react';
+import { ArrowUpRight, ChevronLeft, ChevronRight, X } from 'lucide-react';
+import { useAppContext } from '@/components/ClientLayout';
+import EvidenceTag from '@/components/EvidenceTag';
+import SourceBadge from '@/components/SourceBadge';
+import SourceLink from '@/components/SourceLink';
+import { ErrorState, LoadingState } from '@/components/StateView';
+import { useFetch } from '@/hooks/useFetch';
+import { trendsApi } from '@/lib/api';
+import type { TrendEvidenceFilter } from '@/types/trends';
+import type { TopicSeries } from './_trend-model';
+import styles from './page.module.css';
+import TitleText from './_title-text';
+
+const FILTERS = [['all', '全部'], ['selected', '已入选'], ['evidenced', '有来源证据']] as const;
+
+// Remount on topic/date/filter. Within that identity, keep pagination controls mounted.
+// Page-tagged results hide old rows while the next page loads.
+export function MaterialPage({ topicId, date, filter, page, setPage }: { topicId: number; date: string; filter: TrendEvidenceFilter; page: number; setPage: (page: number) => void }) {
+ const { openReader } = useAppContext();
+ const { data: result, loading, error, refetch } = useFetch(async () => ({ page, payload: await trendsApi.topicEvidence(topicId, date, { filter, page, page_size: 20 }) }), [page]);
+ const data = result?.page === page ? result.payload : null;
+ const busy = loading || (!data && !error);
+ const complete = data?.summary.provenance_status === 'complete';
+ const total = result?.payload.total ?? 0;
+ const pages = Math.max(1, Math.ceil(total / 20));
+ const retry = () => {
+ const region = document.getElementById(`topic-materials-${topicId}`);
+ const restoreFocus = !!document.activeElement?.closest('[role="alert"]');
+ void refetch().then(() => requestAnimationFrame(() => {
+ // Retrying removes the error button. Restore only if focus was lost there;
+ // do not steal focus after the reader moves to another control or topic.
+ if (restoreFocus && region?.isConnected && document.activeElement === document.body) {
+ const retryButton = region.querySelector('[role="alert"] button');
+ (retryButton ?? region).focus({ preventScroll: true });
+ }
+ }));
+ };
+ return <>
+ {busy ? : error ? : data && <>
+
+
{complete ? '已保留完整成员记录' : '历史成员记录不完整'} · {data.summary.source_count} 个信源
+
{filter === 'all' ? '当前可查看' : '当前筛选可查看'} {data.total} 条{!complete && <> · 历史收录 {data.daily_counts?.find(point => point.date === date)?.count ?? data.summary.content_count} 条>}
+ {(!complete || data.calculation.event_members_excluded) &&
查看记录说明
{!complete && {data.message || '以下仅为现存材料,不能还原当时全部内容。'}
}{data.calculation.event_members_excluded && 已排除已合并事件成员。
}}
+
+ {data.items.length ? {data.items.map((item, index) => {
+ const time = item.time_basis === 'published_at' ? item.published_at : item.crawled_at;
+ return -
+ {String((page - 1) * 20 + index + 1).padStart(2, '0')}
+
+ {item.content_id ?
openReader(item.content_id!)} title="站内阅读"> :
}
+
{time && {item.time_basis === 'published_at' ? '发布' : '抓取'} {time.replace('T', ' ').slice(0, 16)}}
+
{item.selected &&
已入选}
{typeof item.score === 'number' &&
评分 {Math.round(item.score)}}{item.url &&
原文 }
+
+ ;
+ })}
: 这次快照中没有符合筛选条件的材料。
}
+ >}
+ {total > 0 && }
+ >;
+}
+
+export default function TopicMaterials({ topic, onClose }: { topic: TopicSeries; onClose: () => void }) {
+ const [date, setDate] = useState(topic.latestDate);
+ const [filter, setFilter] = useState('all');
+ const [page, setPage] = useState(1);
+ const selected = topic.pts.find(point => point.date === date) ?? topic.pts.at(-1)!;
+ return { if (event.key === 'Escape') { event.stopPropagation(); onClose(); } }}>
+
+ {selected.content_count} 条收录
+ 同一话题的收录,可能涉及不同事件。
+ {FILTERS.map(([value, label]) => { setFilter(value); setPage(1); }}>{label})}
+
+ ;
+}
diff --git a/frontend/src/app/trends/TrendExplorer.tsx b/frontend/src/app/trends/TrendExplorer.tsx
new file mode 100644
index 00000000..d43b659f
--- /dev/null
+++ b/frontend/src/app/trends/TrendExplorer.tsx
@@ -0,0 +1,86 @@
+'use client';
+
+import React, { useEffect, useRef, useState } from 'react';
+import { ArrowDownRight, ArrowUpRight, ArrowRight, RefreshCw } from 'lucide-react';
+import { Button, Panel, cx } from '@/components/ui';
+import { EmptyState, ErrorState, LoadingState } from '@/components/StateView';
+import { useFetch } from '@/hooks/useFetch';
+import { trendsApi } from '@/lib/api';
+import type { TrendKeywordItem, TrendEvidenceRequest } from '@/types/trends';
+import TrendEvidenceDrawer from './TrendEvidenceDrawer';
+import { buildTrendModel } from './_trend-model';
+import TopicMaterials from './TopicMaterials';
+import TitleText from './_title-text';
+import styles from './page.module.css';
+
+type View = 'topics' | 'keywords';
+const WINDOWS = [3, 7, 14, 30];
+const dateLabel = (date: string) => date.replaceAll('-', '/');
+
+export default function TrendExplorer({ view, days, onDaysChange, onReady, initialLimit = 15, onLimitChange }: { view: View; days: number; onDaysChange: (days: number) => void; onReady?: () => void; initialLimit?: number; onLimitChange?: (limit: number) => void }) {
+ const [limit, setLimit] = useState(initialLimit);
+ const [entered, setEntered] = useState(false);
+ const [selectedTopic, setSelectedTopic] = useState(null);
+ const triggerRefs = useRef(new Map());
+ const [evidence, setEvidence] = useState(null);
+ const { data, loading, error, refetch } = useFetch(async () => {
+ const scope = days;
+ if (view === 'topics') return { days: scope, view, trends: (await trendsApi.topics(scope)).trends, keywords: [] };
+ return { days: scope, view, trends: [], keywords: (await trendsApi.keywords({ days: scope, limit: 60 })).keywords };
+ }, [days, view]);
+ // A newly selected window must never borrow the previous window's numbers.
+ const current = data?.days === days && data.view === view ? data : null;
+ const busy = loading || (!current && !error);
+ useEffect(() => { if (!busy && current) onReady?.(); }, [busy, current, onReady]);
+ const model = buildTrendModel(current?.trends ?? []);
+ const words: TrendKeywordItem[] = current?.keywords ?? [];
+ const changeDays = (value: number) => { if (value === days) return; setSelectedTopic(null); setEvidence(null); setLimit(15); onDaysChange(value); };
+ const shown = model.topics.slice(0, limit);
+ const comparable = model.topics.filter(topic => topic.delta !== null).length;
+ const openKeyword = (keyword: string) => setEvidence({ kind: 'keyword', keyword, days });
+ const closeMaterials = (id: number) => {
+ setSelectedTopic(null);
+ requestAnimationFrame(() => { const trigger = triggerRefs.current.get(id); trigger?.focus({ preventScroll: true }); trigger?.scrollIntoView({ block: 'nearest', behavior: 'instant' }); });
+ };
+ return
+
+
+
+ {WINDOWS.map(value => changeDays(value)} className={cx(styles.press, 'relative min-h-9 rounded-xs px-3 text-sm font-semibold focus-visible:outline-2 focus-visible:outline-primary', days === value ? 'text-primary-text' : 'text-gray-600')}>{value}天)}
+
+
{ setSelectedTopic(null); void refetch(); }} className="min-h-9 text-xs">刷新{view === 'topics' ? '材料' : '热词'}
+
+
+
{busy ? `正在读取近 ${days} 天的${view === 'topics' ? '话题线索' : '高频热词'}…` : view === 'keywords' ? (current ? `近 ${days} 天 · 公共内容标签频率` : '尚未取得当前窗口数据') : model.latestDate ? `数据截至 ${dateLabel(model.latestDate)} · 近 ${days} 天有 ${model.recordedDays} 个记录日` : error ? '尚未取得当前窗口数据' : `近 ${days} 天暂无快照`}
+ {current && !busy && (view === 'topics' ?
{model.topics.length} 个话题 / {model.totalContent} 条收录 / {model.totalPicks} 条入选
:
显示 {words.length} 个关键词
)}
+
+ {error &&
void refetch()} panel={false} />{current && 以下保留当前窗口上次成功读取的快照。
} }
+ {busy ?
: current &&
setEntered(true)}>
+
+ 显示 {shown.length} / {model.topics.length} 个话题
{comparable ? '按动量排序' : '按收录与入选数排序'}
+ {!shown.length ? :
+ {shown.map((topic, index) => {
+ const latest = topic.pts.at(-1)!;
+ const preview = latest.top_items?.[0];
+ const active = selectedTopic === topic.topicId;
+ return -
+ { if (node) triggerRefs.current.set(topic.topicId, node); else triggerRefs.current.delete(topic.topicId); }} id={`topic-trigger-${topic.topicId}`} type="button" className={cx(styles.topicTrigger, active && styles.active)} aria-expanded={active} aria-controls={active ? `topic-materials-${topic.topicId}` : undefined} onClick={() => active ? closeMaterials(topic.topicId) : setSelectedTopic(topic.topicId)}>
+ {String(index + 1).padStart(2, '0')}
+ {topic.name}{dateLabel(topic.latestDate)}{topic.latestCount} 条收录 · {latest.pick_count} 条入选
+ {preview ? '最新快照 · 首条节选' : '展开查看现存材料'}{topic.delta === null ? (topic.pts.length === 1 ? '仅一次快照,暂无法比较' : '记录间断或口径不同,暂无法比较') : <>{topic.delta > 0 ? : topic.delta < 0 ? : null}{dateLabel(topic.latestDate)} 较 {dateLabel(topic.previousDate!)} {topic.delta === 0 ? '持平' : `${topic.delta > 0 ? '+' : ''}${topic.delta}条`}>}
+
+
+ {active &&
`${point.date}:${point.snapshot_id ?? ''}:${point.content_count}`).join(',')}`} topic={topic} onClose={() => closeMaterials(topic.topicId)} />
}
+ ;
+ })}
+
}
+ {shown.length < model.topics.length && { setLimit(model.topics.length); onLimitChange?.(model.topics.length); }} className="mt-3 w-full">查看其余 {model.topics.length - shown.length} 个话题}
+
+
+ 高频热词
来自公共收录内容的分析标签;数值为带有该标签的内容数,同一内容可贡献多个标签。点击查看来源。
+ {!words.length ? : {words.map(word =>
openKeyword(word.keyword)} className={cx(styles.press, 'block min-h-20 w-full rounded-sm p-4 text-left focus-visible:outline-2 focus-visible:outline-primary')} aria-label={`查看关键词「${word.keyword}」的来源明细`}>{word.keyword}{word.count} item.count), 1) * 100))}%` }} />)}
}
+
+
}
+
setEvidence(null)} />
+ ;
+}
diff --git a/frontend/src/app/trends/_title-text.test.tsx b/frontend/src/app/trends/_title-text.test.tsx
new file mode 100644
index 00000000..a3f4f32b
--- /dev/null
+++ b/frontend/src/app/trends/_title-text.test.tsx
@@ -0,0 +1,20 @@
+import React from 'react';
+import { renderToStaticMarkup } from 'react-dom/server';
+import { describe, expect, it } from 'vitest';
+import TitleText from './_title-text';
+
+describe('原题中文断行', () => {
+ it('最高与美元不被拆成单字,原题文本保持完整', () => {
+ const title = 'Meta MSL 漏洞赏金计划:单个报告最高 30 万美元,提示词注入最高 13 万美元';
+ const html = renderToStaticMarkup();
+ expect(html).toMatch(/]*>最高<\/span>/);
+ expect(html).toMatch(/]*>美元<\/span>/);
+ expect(html.replace(/<[^>]*>/g, '')).toBe(title);
+ });
+ it('中英混排的空格和标点保持原样,内容按文本转义', () => {
+ const html = renderToStaticMarkup( & 原题(2026)'} />);
+ expect(html).not.toContain('