diff --git a/.agents/notes/implemented/architecture/2026-10-24-trend-and-source-provenance.md b/.agents/notes/implemented/architecture/2026-10-24-trend-and-source-provenance.md index 421413bf..c0c1af26 100644 --- a/.agents/notes/implemented/architecture/2026-10-24-trend-and-source-provenance.md +++ b/.agents/notes/implemented/architecture/2026-10-24-trend-and-source-provenance.md @@ -12,13 +12,26 @@ Status: implemented — 基线 738ac61 核实趋势成员和证据链;实现 - [trends service](../../../../backend/app/services/trends.py) 明示 complete/sample_only/unavailable 等状态;缺失历史不从当前库反推并冒称完整。公开快照及成员读取受公共可见性限制。 - [来源证据](../../../../backend/app/services/evidence_service.py) 为平台无关线索,复用同一事件事实。多个独立来源、官方一手链接与“事实已被核验”不是等价关系;当前线索不能冒充历史冻结状态。 +展示入口已归入当日精选的辅助视图,路由与职责见[精选、材料与热词入口](../feature/2026-11-07-picks-materials-entry.md)。本篇继续维护数据与来源语义。 + +## 趋势页的比较与日期表达 + +- 前端按 `topic_id` 聚合,名称变更取末条名称,不按同名合并不同ID;这不证明不同ID之间存在跨日连续性。 +- 共享日历轴可补齐日期位置,缺行仍是未知,不补0;真实0保留。只有末两条快照日期相邻,且双方计算版本非空、相同时才显示带比较日期的变化;缺版本、单点或缺口均明确无法比较,图线也不跨这些边界。 +- 客户端原动量系数不变,但未知变化不获上涨加分。顶部显示真实末日期和有记录的日期数,不冒称所选窗口每日都有运行覆盖;窗口统计和显示数量明确区分,剩余话题可以展开。 +- 切换窗口时只渲染同一请求窗口的数据;所选真实日期、数量、图点及来源请求共用同一身份。窗口变化关闭旧来源抽屉,失败允许重试。索引预览只取最新快照 `top_items` 既有顺序首条,标为首条节选,不改用跨日期最高分材料;缺节选明确说明,不以旧日期补位。展开后所选单日成员由接口读取,与节选区分。 +- 默认以连续原题索引与单组材料支持先扫选、后核对;日期作为辅助索引,不用大日期或默认双组并置暗示材料相关。桌面在索引旁阅读一组材料,窄屏原位展开,收起恢复触发位置。 +- 话题/日期/筛选变化重置成员请求;同一范围翻页保留分页控件,页号与返回结果绑定,加载和失败不借用旧页材料。记录不完整时并列显示历史收录数量与当前可查看数量;筛选后的数量明确称当前筛选。保留成员不完整提示、过滤、分页、阅读与原文入口。 +- 不改公共富信息Sparkline,不借界面重建后端快照、聚类或评分事实。 + ## Alternatives considered - 用历史 Top 链接回填全体成员:不采用,少量样本不足以重建分母。 - 只给 X 打“可信”标记,或用转载数量直接提高真实性:不采用,平台、独立发布者和上游转载需区分。 +- 默认同时展示两组材料:本轮不采用,用户尚未发现具体线索时缺少比较对象;有明确比较任务时可再议。 - 为展示来源信息重建第二套事件归并真源:不采用,事件读取与启用合同沿用 [content-event-coverage](../feature/2026-10-24-content-event-contract.md)。 ## Consequences -冻结成员增加存储与写入成本,当前来源线索会随内容变化;历史证据版本化与私有趋势扩展须另立范围。 +冻结成员增加存储与写入成本,当前来源线索会随内容变化;历史证据版本化与私有趋势扩展须另立范围。首条节选利于跨话题扫选,也可能遮住后续线索,不能据此宣称选题收益提升;独立入口已按[入口合同](../feature/2026-11-07-picks-materials-entry.md)收敛;未来再评估独立趋势功能需先具备可靠的跨日身份与变化证据。 回归入口 [test_trend_traceability.py](../../../../backend/tests/test_trend_traceability.py) 已存在;本次只核对合同与源码,不重跑数据库、迁移或真实样本验收。 diff --git a/.agents/notes/implemented/feature/2026-11-03-user-navigation-contract.md b/.agents/notes/implemented/feature/2026-11-03-user-navigation-contract.md index c5978d66..7194c2d1 100644 --- a/.agents/notes/implemented/feature/2026-11-03-user-navigation-contract.md +++ b/.agents/notes/implemented/feature/2026-11-03-user-navigation-contract.md @@ -15,6 +15,8 @@ Status: implemented — 前台用户动作保持在可访问、语义相符的 - 回跳地址必须是站内路径,拒绝协议相对地址、反斜杠、C0/DEL 控制字符,并按固定站点基准解析验证 origin;避免浏览器删除换行、制表符后把输入转成站外地址。 - 小说模块关闭时,已有小说收藏不显示无法访问的榜单入口。缺少有效 HTTP(S) 原文 URL 的榜单条目展示文字,不用 `#` 跳到页顶或打开当前页。 +精选、话题线索与热词的前台入口已收敛,具体URL与兼容边界见[入口合同](2026-11-07-picks-materials-entry.md)。 + ## 保留边界 显式的“管理后台”“管理更新”入口仍仅管理员可见。历史管理路由 `/sources`、`/model-eval`、`/contents`、`/mother-topics/config` 和 `/stats/jobs` 的重定向是管理路由迁移,不是前台功能入口;本轮未凭路径外观删除它们。 diff --git a/.agents/notes/implemented/feature/2026-11-07-picks-materials-entry.md b/.agents/notes/implemented/feature/2026-11-07-picks-materials-entry.md new file mode 100644 index 00000000..d694ac29 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-07-picks-materials-entry.md @@ -0,0 +1,32 @@ +# Agent Note: 精选、话题线索与热词共用一个入口 + +Status: implemented — 前台当日精选承载主选池与两种辅助观察视图 + +## Problem + +当日精选已经支持话题分组与7天内容浏览;趋势追踪在同一内容库上再次提供原题索引和材料阅读,两处入口的用户任务明显重叠。已有快照尚不足以证明稳定跨日趋势,独立导航会放大其能力承诺。 + +## Decision + +- `/today-picks` 默认进入精选内容;`view=topics` 为话题线索,`view=keywords` 为高频热词。前台导航仅保留当日精选入口;日报链接直接进入相应辅助视图。 +- 精选沿用原入选门槛、评分、个性化、话题/列表、阅读及追加分页。话题线索覆盖公共收录,包含未入选文章;热词反映公共内容分析标签频率。三者不共用分母,不以标签频率冒充搜索热度。 +- URL 是视图和筛选的事实源。精选使用 `category`、`content_type`、`level`、`time_range`;辅助使用独立的 `days`(3/7/14/30,默认7)。切换保留各自参数,前进/后退同步控件与请求。 +- 隐藏精选保留已加载条目、展开状态及筛选,停止其滚动自动加载;辅助只在选中时挂载。切换时隐藏旧范围数据,投影和请求身份一致后才展示;滚动按视图及范围记忆,内容ready后恢复,拒绝旧范围恢复回调。 +- **已由[旧地址退役决定](2026-11-07-retire-trends-route.md)替代的历史决定:** `/trends` 当时保留为兼容入口,服务端归一到 `/today-picks?view=topics`;合法热词目标与窗口保留,未知或重复参数回落默认,目标固定为站内。它不再维护第二套前台页面。 +- 材料的日期、缺口、计算口径、冻结成员及降级语义继续由[趋势与来源合同](../architecture/2026-10-24-trend-and-source-provenance.md)维护。历史收录数量读取对应日 `daily_counts`,现存/筛选可查看数量读取 `total`;`summary` 的现存成员统计不代替历史分母。 + +## Alternatives considered + +- 只改页面名字、保留两个一级入口:不采用,不能消除重复任务。 +- 为保持独立趋势页而补造走势、稳定话题身份或全网热度:不采用,现有证据不支持。 +- 合并后删除快照与成员接口:不采用,材料回查与标签分布仍有独立价值。 + +界面采用“话题线索”命名,强调从收录内容发现可跟进的问题;展开后的文章仍称材料。该命名不改变数据范围、入选规则或URL。 + +## Consequences + +用户在一处入口完成选文章和补查材料,辅助视图需要一次切换。只有未来能可靠提供跨日身份、可比覆盖、变化与新增材料时,再评估独立趋势入口;本次不重建后端、不迁移数据库,也不声称真实选题收益已提升。 + +## Verification + +现行视图参数由 `picks-view.test.ts` 验证;旧地址的退役回归见后续决定;导航由 `navigation.test.ts` 验证;原精选追加合同与回归保留。浏览器验证三视图、筛选、历史导航、滚动恢复、隐藏时停止追加。原始运行证据留本地 `.vidt/`,本地隔离API不等于生产或真实用户验收。 diff --git a/.agents/notes/implemented/feature/2026-11-07-retire-trends-route.md b/.agents/notes/implemented/feature/2026-11-07-retire-trends-route.md new file mode 100644 index 00000000..50bd4d3d --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-07-retire-trends-route.md @@ -0,0 +1,26 @@ +# Agent Note: 退役趋势追踪的旧页面地址 + +Status: implemented — 仅保留当日精选的现行入口,不维护旧页面兼容层 + +## Problem + +[入口收敛](2026-11-07-picks-materials-entry.md)曾保留 `/trends` 跳转。所有者随后明确不需要兼容旧链接;站内入口已经统一,继续维护旧页面及参数转换只会增加一套无必要的路由合同。 + +## Decision + +- 删除 `/trends` 前台页面及其兼容重定向、旧参数转换函数,访问旧地址由框架返回404,不新增退役提示页。 +- 现行入口保持 `/today-picks`,话题线索和高频热词分别使用 `view=topics`、`view=keywords`。 +- 站内链接使用现行入口;后端 `/api/v1/trends/*` 数据接口与被新视图复用的组件仍服务现行功能,不属于退役页面。 +- 本决定替代入口收敛笔记中保留旧地址的单项决定,其余数据、筛选、分页与视图边界继续有效。 + +## Alternatives considered + +- 继续保留兼容跳转:所有者认为没有必要,因此退役。 + +## Consequences + +历史收藏或外部旧链接将得到404。这是本次明确接受的路由变化,不代表已部署上线。删除前已在本地`.vidt/`备份精确文件,可按路径恢复;不涉及数据库或依赖。 + +## Verification + +`retired-trends-route.test.ts` 防止重新注册旧页面或配置重定向;当前视图、导航与数据API另有回归。实际HTTP状态通过本地Next验证,不能替代生产部署后的验证。 diff --git a/.agents/notes/implemented/simplification/2026-10-24-component-semantic-boundaries.md b/.agents/notes/implemented/simplification/2026-10-24-component-semantic-boundaries.md index c85964b9..2f579994 100644 --- a/.agents/notes/implemented/simplification/2026-10-24-component-semantic-boundaries.md +++ b/.agents/notes/implemented/simplification/2026-10-24-component-semantic-boundaries.md @@ -10,7 +10,7 @@ Status: implemented — 基线 738ac61 核实现有组件和注释;#151 从旧 共享色彩、反馈分类和导航等同口径内容由共同模块维护;抽取组件前先比较输入语义、交互、空值与错误状态。 [SourceForm](../../../../frontend/src/components/SourceForm.tsx) 的分类不含“全部”,因为它写入单个信源;[design-tokens](../../../../frontend/src/lib/design-tokens.ts) 的筛选分类允许“全部”。 -[趋势页](../../../../frontend/src/app/trends/page.tsx) 的简单折线与 [公共 Sparkline](../../../../frontend/src/components/Sparkline.tsx) 的富信息趋势卡保留不同接口,当前注释明确记录不合并理由。 +[话题线索视图](../../../../frontend/src/app/trends/TrendExplorer.tsx) 以原题索引与单次快照材料为主体,不为复用 [公共 Sparkline](../../../../frontend/src/components/Sparkline.tsx) 富信息趋势卡而重新加入缺乏连续可比数据的图形。按日身份、缺口与计算版本边界由[趋势与来源合同](../architecture/2026-10-24-trend-and-source-provenance.md)维护。 ## Alternatives considered 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('