From 3b7a51e6283727c0236bc7244f798fd1f6af3d75 Mon Sep 17 00:00:00 2001 From: fxbin Date: Sat, 7 Nov 2026 09:05:29 +0800 Subject: [PATCH 1/2] =?UTF-8?q?feat(today-picks):=20=E5=90=88=E5=B9=B6?= =?UTF-8?q?=E8=AF=9D=E9=A2=98=E7=BA=BF=E7=B4=A2=E4=B8=8E=E7=83=AD=E8=AF=8D?= =?UTF-8?q?=E5=85=A5=E5=8F=A3=E5=B9=B6=E7=A7=BB=E9=99=A4=E6=97=A7=E8=B6=8B?= =?UTF-8?q?=E5=8A=BF=E9=A1=B5=20(#237)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 当日精选同页提供精选内容、话题线索和高频热词,保留分页、筛选与历史滚动位置;原题索引支持按日回查材料,旧 /trends 返回404。 验证:72个前端测试文件523项及覆盖率、类型、导航检查通过;独立代码复核通过,浏览器与本地HTTP证据另存本地。 --- frontend/scripts/check-navigation-access.js | 2 +- frontend/src/app/daily/_frontpage.tsx | 6 +- frontend/src/app/daily/page.tsx | 2 +- frontend/src/app/today-picks/_components.tsx | 52 +- frontend/src/app/today-picks/page.tsx | 138 ++-- .../src/app/trends/TopicMaterials.test.tsx | 55 ++ frontend/src/app/trends/TopicMaterials.tsx | 76 +++ frontend/src/app/trends/TrendExplorer.tsx | 86 +++ frontend/src/app/trends/_title-text.test.tsx | 20 + frontend/src/app/trends/_title-text.tsx | 16 + frontend/src/app/trends/_trend-chart.test.tsx | 14 + frontend/src/app/trends/_trend-chart.tsx | 24 + frontend/src/app/trends/_trend-model.test.ts | 114 ++++ frontend/src/app/trends/_trend-model.ts | 84 +++ frontend/src/app/trends/page.module.css | 63 ++ frontend/src/app/trends/page.test.tsx | 18 + frontend/src/app/trends/page.tsx | 596 ------------------ .../components/workspace-contract.test.tsx | 2 +- frontend/src/lib/__tests__/navigation.test.ts | 10 + frontend/src/lib/__tests__/picks-view.test.ts | 30 + .../__tests__/retired-trends-route.test.ts | 19 + frontend/src/lib/navigation.ts | 2 - frontend/src/lib/picks-view.ts | 24 + 23 files changed, 774 insertions(+), 679 deletions(-) create mode 100644 frontend/src/app/trends/TopicMaterials.test.tsx create mode 100644 frontend/src/app/trends/TopicMaterials.tsx create mode 100644 frontend/src/app/trends/TrendExplorer.tsx create mode 100644 frontend/src/app/trends/_title-text.test.tsx create mode 100644 frontend/src/app/trends/_title-text.tsx create mode 100644 frontend/src/app/trends/_trend-chart.test.tsx create mode 100644 frontend/src/app/trends/_trend-chart.tsx create mode 100644 frontend/src/app/trends/_trend-model.test.ts create mode 100644 frontend/src/app/trends/_trend-model.ts create mode 100644 frontend/src/app/trends/page.module.css create mode 100644 frontend/src/app/trends/page.test.tsx delete mode 100644 frontend/src/app/trends/page.tsx create mode 100644 frontend/src/lib/__tests__/picks-view.test.ts create mode 100644 frontend/src/lib/__tests__/retired-trends-route.test.ts create mode 100644 frontend/src/lib/picks-view.ts diff --git a/frontend/scripts/check-navigation-access.js b/frontend/scripts/check-navigation-access.js index 6f8f777a..5af71666 100644 --- a/frontend/scripts/check-navigation-access.js +++ b/frontend/scripts/check-navigation-access.js @@ -93,7 +93,7 @@ for (const pathName of ['/admin', '/admin/sources', '/admin/model-eval', '/admin assert.strictEqual(canAccessPath(pathName, admin), true, `${pathName} should allow admin`); } -for (const pathName of ['/', '/trending', '/trends', '/today-picks', '/plans']) { +for (const pathName of ['/', '/trending', '/today-picks', '/plans']) { assert.strictEqual(requiredAccessForPath(pathName), 'public'); assert.strictEqual(canAccessPath(pathName, null), true, `${pathName} should stay public`); } diff --git a/frontend/src/app/daily/_frontpage.tsx b/frontend/src/app/daily/_frontpage.tsx index a9e3028e..77559a50 100644 --- a/frontend/src/app/daily/_frontpage.tsx +++ b/frontend/src/app/daily/_frontpage.tsx @@ -456,13 +456,13 @@ export function ColophonStrip({ 昨日对账:首期或数据不足 )} | - 趋势实验室 → + 话题线索 → 今日精选 → ); } -// ── 趋势一行(增刊归还:缩为一行跳 /trends)───────────────────────── +// ── 趋势一行(辅助信号归入当日精选)───────────────────────── export function TrendsOneLiner({ trends, @@ -482,7 +482,7 @@ export function TrendsOneLiner({ {t.title} ))} - 趋势实验室 → + 高频热词 → ); } diff --git a/frontend/src/app/daily/page.tsx b/frontend/src/app/daily/page.tsx index 2382f642..69f78aa6 100644 --- a/frontend/src/app/daily/page.tsx +++ b/frontend/src/app/daily/page.tsx @@ -618,7 +618,7 @@ function DailyReportContent() { )} - {/* 趋势一行(增刊归还:缩为一行跳 /trends) */} + {/* 趋势一行(辅助信号进入当日精选) */} {/* 平台建议(折叠态) */} diff --git a/frontend/src/app/today-picks/_components.tsx b/frontend/src/app/today-picks/_components.tsx index a216c695..cd018558 100644 --- a/frontend/src/app/today-picks/_components.tsx +++ b/frontend/src/app/today-picks/_components.tsx @@ -76,15 +76,15 @@ export function OverviewStrip({ eventMemberCount: number; }) { const stats = [ - { label: '精选内容', value: total, hint: loadedCount < total ? `已加载 ${loadedCount}` : '事件归并后', icon: Target, color: 'text-primary' }, - { label: '平均分', value: avgScore || '-', hint: '算法校准', icon: BarChart3, color: 'text-teal' }, + { label: '精选内容', value: total, hint: loadedCount < total ? `已加载 ${loadedCount}` : '事件归并后', icon: Target, color: 'text-primary-text' }, + { label: '平均分', value: avgScore || '-', hint: '算法校准', icon: BarChart3, color: 'text-teal-text' }, { label: '话题组', value: topicCount, hint: '聚类结果', icon: Layers3, color: 'text-purple' }, { label: '来源', value: sourceCount, hint: eventMemberCount ? `归并附属 ${eventMemberCount}` : '有效信源', icon: Search, - color: 'text-amber', + color: 'text-amber-800', }, ]; @@ -96,12 +96,12 @@ export function OverviewStrip({
- {stat.label} + {stat.label}
{stat.value}
-
{stat.hint}
+
{stat.hint}
); })} @@ -156,7 +156,7 @@ export function LeadPick({ 今日主推 - {item.source_name} + {item.source_name} {tags.slice(0, 3).map((tag) => ( {tag} @@ -185,8 +185,8 @@ export function LeadPick({
-
SCORE
-
{Math.round(score)}
+
SCORE
+
{Math.round(score)}
@@ -227,7 +227,7 @@ export function FilterPanel({
时间范围 - +
推荐等级 @@ -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 && (
}> + 加载中...
}> ); @@ -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' ? '从算法候选中筛出可写选题,按话题、质量和来源做二次判断' : '补充查看公共收录的材料与标签分布,观察窗口独立于精选筛选'}

- + {groupByTopic ? '精选分组' : '精选列表'} + } +
+
+ {PICKS_VIEWS.map((view, index) => )}
+
- {selectedAnalysis && setSelectedAnalysis(null)} />} + + {(['topics', 'keywords'] as const).map(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
  1. + {String((page - 1) * 20 + index + 1).padStart(2, '0')} +
    + {item.content_id ? :

    } +
    {time && {item.time_basis === 'published_at' ? '发布' : '抓取'} {time.replace('T', ' ').slice(0, 16)}}
    +
    {item.selected && 已入选}{typeof item.score === 'number' && 评分 {Math.round(item.score)}}{item.url && 原文 }
    +
    +
  2. ; + })}
:

这次快照中没有符合筛选条件的材料。

} + } + {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(); } }}> +

{topic.name}

+
{selected.content_count} 条收录
+

同一话题的收录,可能涉及不同事件。

+
{FILTERS.map(([value, 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 => )} +
+ +
+
+

{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)}> + + +
} + 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('