更新Company页面的UI为FUI风格

This commit is contained in:
2025-12-21 23:40:02 +08:00
parent d9b804c46c
commit 54b7d9fc89
5 changed files with 1042 additions and 157 deletions

238
app.py
View File

@@ -10992,6 +10992,244 @@ def get_hot_events():
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/events/mainline', methods=['GET'])
def get_events_by_mainline():
"""
获取按主线lv2概念分组的事件列表
逻辑:
1. 根据筛选条件获取事件列表
2. 通过 related_concepts 表关联概念
3. 调用 concept-api/hierarchy 获取概念的 lv2 归属
4. 按 lv2 分组返回
参数:
- recent_days: 近N天默认7天
- importance: 重要性筛选S,A,B,C 或 all
- limit: 每个主线最多返回多少事件默认20
返回:
{
"success": true,
"data": {
"mainlines": [
{
"lv2_id": "L2_AI_INFRA",
"lv2_name": "AI基础设施 (算力/CPO/PCB)",
"lv1_name": "TMT (科技/媒体/通信)",
"event_count": 15,
"events": [...]
},
...
],
"total_events": 100,
"ungrouped_count": 5
}
}
"""
try:
import requests
from datetime import datetime, timedelta
from sqlalchemy.orm import joinedload
from sqlalchemy import exists
# 获取请求参数
recent_days = request.args.get('recent_days', 7, type=int)
importance = request.args.get('importance', 'all')
limit_per_mainline = request.args.get('limit', 20, type=int)
# 计算日期范围
since_date = datetime.now() - timedelta(days=recent_days)
# ==================== 1. 获取概念层级映射 ====================
# 调用 concept-api 获取层级结构
concept_hierarchy_map = {} # { concept_name: { lv1, lv2, lv1_id, lv2_id } }
try:
# 内部调用 concept-api
hierarchy_resp = requests.get(
'http://127.0.0.1:6801/hierarchy',
timeout=5
)
if hierarchy_resp.status_code == 200:
hierarchy_data = hierarchy_resp.json()
hierarchy_list = hierarchy_data.get('hierarchy', [])
# 构建概念名称 -> lv2 映射
for lv1 in hierarchy_list:
lv1_name = lv1.get('name', '')
lv1_id = lv1.get('id', '')
for lv2 in lv1.get('children', []):
lv2_name = lv2.get('name', '')
lv2_id = lv2.get('id', '')
# lv2 直接包含 concepts
for concept in lv2.get('concepts', []):
concept_name = concept if isinstance(concept, str) else concept.get('name', '')
if concept_name:
concept_hierarchy_map[concept_name] = {
'lv1': lv1_name,
'lv1_id': lv1_id,
'lv2': lv2_name,
'lv2_id': lv2_id
}
# lv3 children
for lv3 in lv2.get('children', []):
for concept in lv3.get('concepts', []):
concept_name = concept if isinstance(concept, str) else concept.get('name', '')
if concept_name:
concept_hierarchy_map[concept_name] = {
'lv1': lv1_name,
'lv1_id': lv1_id,
'lv2': lv2_name,
'lv2_id': lv2_id
}
app.logger.info(f'[mainline] 加载概念层级映射: {len(concept_hierarchy_map)} 个概念')
except Exception as e:
app.logger.warning(f'[mainline] 获取概念层级失败: {e}')
# ==================== 2. 查询事件及其关联概念 ====================
query = Event.query.options(joinedload(Event.creator))
# 只返回有关联股票的事件
query = query.filter(
exists().where(RelatedStock.event_id == Event.id)
)
# 状态筛选
query = query.filter(Event.status == 'active')
# 日期筛选
query = query.filter(Event.created_at >= since_date)
# 重要性筛选
if importance != 'all':
if ',' in importance:
importance_list = [imp.strip() for imp in importance.split(',') if imp.strip()]
query = query.filter(Event.importance.in_(importance_list))
else:
query = query.filter(Event.importance == importance)
# 按时间倒序
query = query.order_by(Event.created_at.desc())
# 获取事件(限制总数防止性能问题)
events = query.limit(500).all()
app.logger.info(f'[mainline] 查询到 {len(events)} 个事件')
# ==================== 3. 获取事件的关联概念 ====================
event_ids = [e.id for e in events]
# 批量查询 related_concepts
related_concepts_query = db.session.query(
RelatedConcept.event_id,
RelatedConcept.concept
).filter(RelatedConcept.event_id.in_(event_ids)).all()
# 构建 event_id -> concepts 映射
event_concepts_map = {} # { event_id: [concept1, concept2, ...] }
for event_id, concept in related_concepts_query:
if event_id not in event_concepts_map:
event_concepts_map[event_id] = []
event_concepts_map[event_id].append(concept)
app.logger.info(f'[mainline] 查询到 {len(related_concepts_query)} 条概念关联')
# ==================== 4. 按 lv2 分组事件 ====================
mainline_groups = {} # { lv2_id: { info: {...}, events: [...] } }
ungrouped_events = []
def find_concept_hierarchy(concept_name):
"""查找概念的层级信息(支持模糊匹配)"""
# 精确匹配
if concept_name in concept_hierarchy_map:
return concept_hierarchy_map[concept_name]
# 模糊匹配
for key in concept_hierarchy_map:
if concept_name in key or key in concept_name:
return concept_hierarchy_map[key]
return None
for event in events:
concepts = event_concepts_map.get(event.id, [])
# 找出该事件所属的所有 lv2
event_lv2s = set()
for concept in concepts:
hierarchy = find_concept_hierarchy(concept)
if hierarchy:
event_lv2s.add((hierarchy['lv2_id'], hierarchy['lv2'], hierarchy['lv1']))
# 事件数据
event_data = {
'id': event.id,
'title': event.title,
'description': event.description,
'importance': event.importance,
'created_at': event.created_at.isoformat() if event.created_at else None,
'related_avg_chg': event.related_avg_chg,
'related_max_chg': event.related_max_chg,
'expectation_surprise_score': event.expectation_surprise_score,
'hot_score': event.hot_score,
'related_concepts': [{'concept': c} for c in concepts],
'creator': {
'username': event.creator.username if event.creator else 'Anonymous'
}
}
if event_lv2s:
# 添加到每个相关的 lv2 分组
for lv2_id, lv2_name, lv1_name in event_lv2s:
if lv2_id not in mainline_groups:
mainline_groups[lv2_id] = {
'lv2_id': lv2_id,
'lv2_name': lv2_name,
'lv1_name': lv1_name,
'events': []
}
mainline_groups[lv2_id]['events'].append(event_data)
else:
ungrouped_events.append(event_data)
# ==================== 5. 整理返回数据 ====================
mainlines = []
for lv2_id, group in mainline_groups.items():
# 按时间倒序,限制每组数量
group['events'] = sorted(
group['events'],
key=lambda x: x['created_at'] or '',
reverse=True
)[:limit_per_mainline]
group['event_count'] = len(group['events'])
mainlines.append(group)
# 按事件数量排序
mainlines.sort(key=lambda x: x['event_count'], reverse=True)
return jsonify({
'success': True,
'data': {
'mainlines': mainlines,
'total_events': len(events),
'mainline_count': len(mainlines),
'ungrouped_count': len(ungrouped_events)
}
})
except Exception as e:
app.logger.error(f'[mainline] 错误: {e}', exc_info=True)
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/api/events/keywords/popular', methods=['GET'])
def get_popular_keywords():
"""获取热门关键词"""

View File

@@ -1585,4 +1585,107 @@ export const eventHandlers = [
);
}
}),
// ==================== 主线模式相关 ====================
// 获取按主线lv2概念分组的事件列表
http.get('/api/events/mainline', async ({ request }) => {
await delay(500);
const url = new URL(request.url);
const recentDays = parseInt(url.searchParams.get('recent_days') || '7', 10);
const importance = url.searchParams.get('importance') || 'all';
const limitPerMainline = parseInt(url.searchParams.get('limit') || '20', 10);
console.log('[Mock Event] 获取主线数据:', { recentDays, importance, limitPerMainline });
try {
// 生成 mock 事件数据
const allEvents = generateDynamicNewsEvents(100);
// 定义 lv2 主线分类
const mainlineDefinitions = [
{ lv2_id: 'L2_AI_INFRA', lv2_name: 'AI基础设施 (算力/CPO/PCB)', lv1_name: 'TMT (科技/媒体/通信)', keywords: ['算力', 'AI', '人工智能', 'CPO', 'PCB', '光模块', '大模型', '智能体'] },
{ lv2_id: 'L2_SEMICONDUCTOR', lv2_name: '半导体 (设计/制造/封测)', lv1_name: 'TMT (科技/媒体/通信)', keywords: ['半导体', '芯片', '光刻', 'IC', '晶圆', '封装', '测试'] },
{ lv2_id: 'L2_ROBOT', lv2_name: '机器人 (人形机器人/工业机器人)', lv1_name: 'TMT (科技/媒体/通信)', keywords: ['机器人', '人形', '自动化', '工业机器人', '具身智能'] },
{ lv2_id: 'L2_CONSUMER_ELEC', lv2_name: '消费电子 (手机/XR/可穿戴)', lv1_name: 'TMT (科技/媒体/通信)', keywords: ['手机', 'XR', 'VR', 'AR', '可穿戴', '华为', '苹果', '消费电子'] },
{ lv2_id: 'L2_NEW_ENERGY', lv2_name: '新能源 (光伏/储能/电池)', lv1_name: '新能源与环保', keywords: ['光伏', '储能', '电池', '锂电', '新能源', '风电', '清洁能源'] },
{ lv2_id: 'L2_EV', lv2_name: '新能源汽车 (整车/零部件)', lv1_name: '新能源与环保', keywords: ['新能源汽车', '电动车', '智能驾驶', '汽车', '整车', '零部件'] },
{ lv2_id: 'L2_LOW_ALTITUDE', lv2_name: '低空经济 (无人机/eVTOL)', lv1_name: '先进制造', keywords: ['低空', '无人机', 'eVTOL', '飞行', '空域'] },
{ lv2_id: 'L2_MILITARY', lv2_name: '军工 (航空航天/国防)', lv1_name: '先进制造', keywords: ['军工', '国防', '航空', '航天', '卫星', '导弹'] },
{ lv2_id: 'L2_PHARMA', lv2_name: '医药医疗 (创新药/器械)', lv1_name: '医药健康', keywords: ['医药', '医疗', '创新药', '器械', '生物', 'CXO'] },
{ lv2_id: 'L2_FINANCE', lv2_name: '金融 (银行/券商/保险)', lv1_name: '金融', keywords: ['金融', '银行', '券商', '保险', '证券'] },
];
// 按主线分组事件
const mainlineGroups = {};
allEvents.forEach(event => {
// 从事件的 keywords (related_concepts) 中查找匹配的主线
const keywords = event.keywords || event.related_concepts || [];
const conceptNames = keywords.map(k => k.concept || k.name || k).join(' ');
const titleAndDesc = `${event.title || ''} ${event.description || ''}`;
const textToMatch = `${conceptNames} ${titleAndDesc}`.toLowerCase();
// 匹配主线
mainlineDefinitions.forEach(mainline => {
const matched = mainline.keywords.some(kw => textToMatch.includes(kw.toLowerCase()));
if (matched) {
if (!mainlineGroups[mainline.lv2_id]) {
mainlineGroups[mainline.lv2_id] = {
lv2_id: mainline.lv2_id,
lv2_name: mainline.lv2_name,
lv1_name: mainline.lv1_name,
events: []
};
}
// 避免重复添加
if (!mainlineGroups[mainline.lv2_id].events.find(e => e.id === event.id)) {
mainlineGroups[mainline.lv2_id].events.push(event);
}
}
});
});
// 转换为数组,限制每组数量,按事件数量排序
const mainlines = Object.values(mainlineGroups)
.map(group => ({
...group,
events: group.events.slice(0, limitPerMainline),
event_count: Math.min(group.events.length, limitPerMainline)
}))
.filter(group => group.event_count > 0)
.sort((a, b) => b.event_count - a.event_count);
// 统计未分组的事件
const groupedEventIds = new Set();
mainlines.forEach(m => m.events.forEach(e => groupedEventIds.add(e.id)));
const ungroupedCount = allEvents.filter(e => !groupedEventIds.has(e.id)).length;
console.log('[Mock Event] 主线数据生成完成:', {
mainlineCount: mainlines.length,
totalEvents: allEvents.length,
ungroupedCount
});
return HttpResponse.json({
success: true,
data: {
mainlines,
total_events: allEvents.length,
mainline_count: mainlines.length,
ungrouped_count: ungroupedCount
}
});
} catch (error) {
console.error('[Mock Event] 主线数据获取失败:', error);
return HttpResponse.json(
{
success: false,
error: error.message || '获取主线数据失败'
},
{ status: 500 }
);
}
}),
];

View File

@@ -377,14 +377,18 @@ const [currentMode, setCurrentMode] = useState('vertical');
// 添加防抖:如果已经初始化,不再执行
if (hasInitialized.current) return;
// mainline 模式使用 four-row 的 API 模式(共用数据
const apiMode = mode === DISPLAY_MODES.MAINLINE ? DISPLAY_MODES.FOUR_ROW : mode;
// mainline 模式使用独立 API不需要通过 Redux 获取数据
if (mode === DISPLAY_MODES.MAINLINE) {
hasInitialized.current = true;
console.log('%c🚀 [初始加载] 主线模式 - 组件自己调用 /api/events/mainline', 'color: #10B981; font-weight: bold;');
return;
}
// ⚡ 始终获取最新数据,确保用户每次进入页面看到最新事件
hasInitialized.current = true;
console.log('%c🚀 [初始加载] 获取最新事件数据', 'color: #10B981; font-weight: bold;', { mode, apiMode, pageSize });
console.log('%c🚀 [初始加载] 获取最新事件数据', 'color: #10B981; font-weight: bold;', { mode, pageSize });
dispatch(fetchDynamicNews({
mode: apiMode, // 传递 API 模式mainline 映射为 four-row
mode,
per_page: pageSize,
pageSize: pageSize, // 传递 pageSize 确保索引计算一致
clearCache: true,
@@ -412,14 +416,17 @@ const [currentMode, setCurrentMode] = useState('vertical');
return;
}
// mainline 模式使用 four-row 的 API 模式(共用数据)
const apiMode = mode === DISPLAY_MODES.MAINLINE ? DISPLAY_MODES.FOUR_ROW : mode;
// mainline 模式使用独立 API筛选条件变化由 MainlineTimelineView 自己监听
if (mode === DISPLAY_MODES.MAINLINE) {
console.log('%c🔍 [筛选] 主线模式 - 筛选条件变化由组件自己处理', 'color: #8B5CF6; font-weight: bold;', { filters });
return;
}
console.log('%c🔍 [筛选] 筛选条件改变,重新请求数据', 'color: #8B5CF6; font-weight: bold;', { filters, mode, apiMode });
console.log('%c🔍 [筛选] 筛选条件改变,重新请求数据', 'color: #8B5CF6; font-weight: bold;', { filters, mode });
// 筛选条件改变时清空对应模式的缓存并从第1页开始加载
dispatch(fetchDynamicNews({
mode: apiMode, // 传递 API 模式mainline 映射为 four-row
mode,
per_page: pageSize,
pageSize: pageSize,
clearCache: true, // 清空缓存
@@ -442,6 +449,12 @@ const [currentMode, setCurrentMode] = useState('vertical');
// 监听模式切换 - 如果新模式数据为空,请求数据
useEffect(() => {
// ⚡ mainline 模式使用独立 API不需要通过 Redux 加载数据
if (mode === DISPLAY_MODES.MAINLINE) {
console.log('%c🔄 [模式切换] 主线模式 - 由 MainlineTimelineView 组件自己加载数据', 'color: #8B5CF6; font-weight: bold;');
return;
}
const isDataEmpty = currentMode === 'vertical'
? Object.keys(allCachedEventsByPage || {}).length === 0
: (allCachedEvents?.length || 0) === 0;
@@ -449,20 +462,16 @@ const [currentMode, setCurrentMode] = useState('vertical');
if (hasInitialized.current && isDataEmpty) {
console.log(`%c🔄 [模式切换] ${mode} 模式数据为空,开始加载`, 'color: #8B5CF6; font-weight: bold;');
// 🔧 根据 mode 直接计算 per_page,避免使用可能过时的 pageSize prop
// mainline 模式复用 four-row 的分页大小
const modePageSize = (mode === DISPLAY_MODES.FOUR_ROW || mode === DISPLAY_MODES.MAINLINE)
// 🔧 根据 mode 直接计算 per_page
const modePageSize = mode === DISPLAY_MODES.FOUR_ROW
? PAGINATION_CONFIG.FOUR_ROW_PAGE_SIZE // 30
: PAGINATION_CONFIG.VERTICAL_PAGE_SIZE; // 10
// mainline 模式使用 four-row 的 API 模式(共用数据)
const apiMode = mode === DISPLAY_MODES.MAINLINE ? DISPLAY_MODES.FOUR_ROW : mode;
console.log(`%c 计算的 per_page: ${modePageSize}, apiMode: ${apiMode} (mode: ${mode})`, 'color: #8B5CF6;');
console.log(`%c 计算的 per_page: ${modePageSize} (mode: ${mode})`, 'color: #8B5CF6;');
dispatch(fetchDynamicNews({
mode: apiMode, // 使用映射后的 API 模式
per_page: modePageSize, // 使用计算的值,不是 pageSize prop
mode,
per_page: modePageSize,
pageSize: modePageSize,
clearCache: true,
...filters, // 先展开筛选条件
@@ -662,6 +671,7 @@ const [currentMode, setCurrentMode] = useState('vertical');
<EventScrollList
events={currentPageEvents}
displayEvents={displayEvents} // 累积显示的事件列表(平铺模式)
filters={filters} // 筛选条件(主线模式用)
loadNextPage={loadNextPage} // 加载下一页
loadPrevPage={loadPrevPage} // 加载上一页
onFourRowEventClick={handleFourRowEventClick} // 四排模式事件点击

View File

@@ -1,19 +1,17 @@
// src/views/Community/components/DynamicNews/EventScrollList.js
// 横向滚动事件列表组件
import React, { useRef, useCallback } from 'react';
import {
Box,
useColorModeValue
} from '@chakra-ui/react';
import VirtualizedFourRowGrid from './layouts/VirtualizedFourRowGrid';
import GroupedFourRowGrid from './layouts/GroupedFourRowGrid';
import VerticalModeLayout from './layouts/VerticalModeLayout';
import React, { useRef, useCallback } from "react";
import { Box, useColorModeValue } from "@chakra-ui/react";
import VirtualizedFourRowGrid from "./layouts/VirtualizedFourRowGrid";
import MainlineTimelineView from "./layouts/MainlineTimelineView";
import VerticalModeLayout from "./layouts/VerticalModeLayout";
/**
* 事件列表组件 - 支持纵向、平铺、主线三种展示模式
* @param {Array} events - 当前页的事件列表(服务端已分页)
* @param {Array} displayEvents - 累积显示的事件列表(平铺/主线模式用)
* @param {Array} displayEvents - 累积显示的事件列表(平铺模式用)
* @param {Object} filters - 筛选条件(主线模式用)
* @param {Function} loadNextPage - 加载下一页(无限滚动)
* @param {Function} loadPrevPage - 加载上一页(双向无限滚动)
* @param {Function} onFourRowEventClick - 平铺/主线模式事件点击回调(打开弹窗)
@@ -25,148 +23,147 @@ import VerticalModeLayout from './layouts/VerticalModeLayout';
* @param {Function} onPageChange - 页码改变回调
* @param {boolean} loading - 全局加载状态
* @param {Object} error - 错误状态
* @param {string} mode - 展示模式:'vertical'(纵向分栏)| 'four-row'(平铺网格)| 'mainline'(主线分组
* @param {string} mode - 展示模式:'vertical'(纵向分栏)| 'four-row'(平铺网格)| 'mainline'(主线时间轴
* @param {boolean} hasMore - 是否还有更多数据
* @param {Object} eventFollowStatus - 事件关注状态 { [eventId]: { isFollowing, followerCount } }
* @param {Function} onToggleFollow - 关注按钮回调
* @param {React.Ref} virtualizedGridRef - VirtualizedFourRowGrid/GroupedFourRowGrid 的 ref用于获取滚动位置
* @param {React.Ref} virtualizedGridRef - VirtualizedFourRowGrid/MainlineTimelineView 的 ref
*/
const EventScrollList = React.memo(({
events,
displayEvents,
loadNextPage,
loadPrevPage,
onFourRowEventClick,
selectedEvent,
onEventSelect,
borderColor,
currentPage,
totalPages,
onPageChange,
loading = false,
error,
mode = 'vertical',
hasMore = true,
eventFollowStatus = {},
onToggleFollow,
virtualizedGridRef
}) => {
const scrollContainerRef = useRef(null);
const EventScrollList = React.memo(
({
events,
displayEvents,
filters = {},
loadNextPage,
loadPrevPage,
onFourRowEventClick,
selectedEvent,
onEventSelect,
borderColor,
currentPage,
totalPages,
onPageChange,
loading = false,
error,
mode = "vertical",
hasMore = true,
eventFollowStatus = {},
onToggleFollow,
virtualizedGridRef,
}) => {
const scrollContainerRef = useRef(null);
// 所有 useColorModeValue 必须在组件顶层调用(不能在条件渲染中)
const timelineBg = useColorModeValue('gray.50', 'gray.700');
const timelineBorderColor = useColorModeValue('gray.400', 'gray.500');
const timelineTextColor = useColorModeValue('blue.600', 'blue.400');
// 所有 useColorModeValue 必须在组件顶层调用(不能在条件渲染中)
const timelineBg = useColorModeValue("gray.50", "gray.700");
const timelineBorderColor = useColorModeValue("gray.400", "gray.500");
const timelineTextColor = useColorModeValue("blue.600", "blue.400");
// 滚动条颜色
const scrollbarTrackBg = useColorModeValue('#f1f1f1', '#2D3748');
const scrollbarThumbBg = useColorModeValue('#888', '#4A5568');
const scrollbarThumbHoverBg = useColorModeValue('#555', '#718096');
// 滚动条颜色
const scrollbarTrackBg = useColorModeValue("#f1f1f1", "#2D3748");
const scrollbarThumbBg = useColorModeValue("#888", "#4A5568");
const scrollbarThumbHoverBg = useColorModeValue("#555", "#718096");
const getTimelineBoxStyle = () => {
return {
bg: timelineBg,
borderColor: timelineBorderColor,
borderWidth: '2px',
textColor: timelineTextColor,
boxShadow: 'sm',
const getTimelineBoxStyle = () => {
return {
bg: timelineBg,
borderColor: timelineBorderColor,
borderWidth: "2px",
textColor: timelineTextColor,
boxShadow: "sm",
};
};
};
// 重试函数
const handleRetry = useCallback(() => {
if (onPageChange) {
onPageChange(currentPage);
// 重试函数
const handleRetry = useCallback(() => {
if (onPageChange) {
onPageChange(currentPage);
}
}, [onPageChange, currentPage]);
{
/* 事件卡片容器 */
}
}, [onPageChange, currentPage]);
return (
<Box
ref={scrollContainerRef}
overflowX="hidden"
h="100%"
pt={0}
pb={4}
px={mode === "four-row" || mode === "mainline" ? 0 : { base: 0, md: 2 }}
position="relative"
data-scroll-container="true"
css={{
// 统一滚动条样式(支持横向和纵向)
"&::-webkit-scrollbar": {
width: "1px",
height: "1px",
},
"&::-webkit-scrollbar-track": {
background: scrollbarTrackBg,
borderRadius: "10px",
},
"&::-webkit-scrollbar-thumb": {
background: scrollbarThumbBg,
borderRadius: "10px",
},
"&::-webkit-scrollbar-thumb:hover": {
background: scrollbarThumbHoverBg,
},
scrollBehavior: "smooth",
WebkitOverflowScrolling: "touch",
}}
>
{/* 平铺网格模式 - 使用虚拟滚动 + 双向无限滚动 */}
<VirtualizedFourRowGrid
ref={mode === "four-row" ? virtualizedGridRef : null}
display={mode === "four-row" ? "block" : "none"}
columnsPerRow={4} // 每行显示4列
events={displayEvents || events} // 使用累积列表(如果有)
selectedEvent={selectedEvent}
onEventSelect={onFourRowEventClick} // 四排模式点击打开弹窗
eventFollowStatus={eventFollowStatus}
onToggleFollow={onToggleFollow}
getTimelineBoxStyle={getTimelineBoxStyle}
borderColor={borderColor}
loadNextPage={loadNextPage} // 加载下一页
loadPrevPage={loadPrevPage} // 加载上一页(双向滚动)
hasMore={hasMore} // 是否还有更多数据
loading={loading} // 加载状态
error={error} // 错误状态
onRetry={handleRetry} // 重试回调
/>
{/* 事件卡片容器 */}
return (
<Box
ref={scrollContainerRef}
overflowX="hidden"
h="100%"
pt={0}
pb={4}
px={mode === 'four-row' || mode === 'mainline' ? 0 : { base: 0, md: 2 }}
position="relative"
data-scroll-container="true"
css={{
// 统一滚动条样式(支持横向和纵向)
'&::-webkit-scrollbar': {
width: '1px',
height: '1px',
},
'&::-webkit-scrollbar-track': {
background: scrollbarTrackBg,
borderRadius: '10px',
},
'&::-webkit-scrollbar-thumb': {
background: scrollbarThumbBg,
borderRadius: '10px',
},
'&::-webkit-scrollbar-thumb:hover': {
background: scrollbarThumbHoverBg,
},
scrollBehavior: 'smooth',
WebkitOverflowScrolling: 'touch',
}}
>
{/* 平铺网格模式 - 使用虚拟滚动 + 双向无限滚动 */}
<VirtualizedFourRowGrid
ref={mode === 'four-row' ? virtualizedGridRef : null}
display={mode === 'four-row' ? 'block' : 'none'}
columnsPerRow={4} // 每行显示4列
events={displayEvents || events} // 使用累积列表(如果有)
selectedEvent={selectedEvent}
onEventSelect={onFourRowEventClick} // 四排模式点击打开弹窗
eventFollowStatus={eventFollowStatus}
onToggleFollow={onToggleFollow}
getTimelineBoxStyle={getTimelineBoxStyle}
borderColor={borderColor}
loadNextPage={loadNextPage} // 加载下一页
loadPrevPage={loadPrevPage} // 加载上一页(双向滚动)
hasMore={hasMore} // 是否还有更多数据
loading={loading} // 加载状态
error={error} // 错误状态
onRetry={handleRetry} // 重试回调
/>
{/* 主线时间轴模式 - 按 lv2 概念分组,调用独立 API */}
<MainlineTimelineView
ref={mode === "mainline" ? virtualizedGridRef : null}
display={mode === "mainline" ? "block" : "none"}
filters={filters}
columnsPerRow={3}
selectedEvent={selectedEvent}
onEventSelect={onFourRowEventClick}
eventFollowStatus={eventFollowStatus}
onToggleFollow={onToggleFollow}
borderColor={borderColor}
/>
{/* 主线分组模式 - 按 lv2 概念分组 */}
<GroupedFourRowGrid
ref={mode === 'mainline' ? virtualizedGridRef : null}
display={mode === 'mainline' ? 'block' : 'none'}
columnsPerRow={4}
events={displayEvents || events}
selectedEvent={selectedEvent}
onEventSelect={onFourRowEventClick}
eventFollowStatus={eventFollowStatus}
onToggleFollow={onToggleFollow}
getTimelineBoxStyle={getTimelineBoxStyle}
borderColor={borderColor}
loadNextPage={loadNextPage}
hasMore={hasMore}
loading={loading}
error={error}
onRetry={handleRetry}
/>
{/* 纵向分栏模式 */}
<VerticalModeLayout
display={mode === 'vertical' ? 'flex' : 'none'}
events={events}
selectedEvent={selectedEvent}
onEventSelect={onEventSelect}
eventFollowStatus={eventFollowStatus}
onToggleFollow={onToggleFollow}
getTimelineBoxStyle={getTimelineBoxStyle}
borderColor={borderColor}
currentPage={currentPage}
totalPages={totalPages}
onPageChange={onPageChange}
/>
</Box>
);
});
{/* 纵向分栏模式 */}
<VerticalModeLayout
display={mode === "vertical" ? "flex" : "none"}
events={events}
selectedEvent={selectedEvent}
onEventSelect={onEventSelect}
eventFollowStatus={eventFollowStatus}
onToggleFollow={onToggleFollow}
getTimelineBoxStyle={getTimelineBoxStyle}
borderColor={borderColor}
currentPage={currentPage}
totalPages={totalPages}
onPageChange={onPageChange}
/>
</Box>
);
}
);
export default EventScrollList;

View File

@@ -0,0 +1,537 @@
// src/views/Community/components/DynamicNews/layouts/MainlineTimelineView.js
// 主线时间轴布局组件 - 按 lv2 概念分组展示事件
import React, {
useState,
useEffect,
forwardRef,
useImperativeHandle,
useCallback,
} from "react";
import {
Box,
VStack,
HStack,
Text,
Badge,
Flex,
Icon,
Collapse,
Spinner,
Center,
IconButton,
useColorModeValue,
Tooltip,
Grid,
} from "@chakra-ui/react";
import {
ChevronDownIcon,
ChevronRightIcon,
RepeatIcon,
TimeIcon,
} from "@chakra-ui/icons";
import { FiTrendingUp, FiClock, FiZap } from "react-icons/fi";
import DynamicNewsEventCard from "../../EventCard/DynamicNewsEventCard";
import { getApiBase } from "@utils/apiConfig";
/**
* 主线时间轴布局组件
*
* 功能:
* 1. 调用 /api/events/mainline 获取预分组数据
* 2. 按 lv2 概念分组展示,时间轴样式
* 3. 不使用无限滚动,一次性加载全部数据
*/
const MainlineTimelineViewComponent = forwardRef(
(
{
display = "block",
filters = {},
selectedEvent,
onEventSelect,
eventFollowStatus = {},
onToggleFollow,
borderColor,
columnsPerRow = 3,
},
ref
) => {
// 状态
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [mainlineData, setMainlineData] = useState(null);
const [expandedGroups, setExpandedGroups] = useState({});
// 主题颜色
const bgColor = useColorModeValue("white", "gray.800");
const headerBg = useColorModeValue("gray.50", "gray.700");
const headerHoverBg = useColorModeValue("gray.100", "gray.600");
const textColor = useColorModeValue("gray.700", "gray.200");
const secondaryTextColor = useColorModeValue("gray.500", "gray.400");
const timelineBorderColor = useColorModeValue("gray.200", "gray.600");
const timelineLineColor = useColorModeValue("blue.200", "blue.600");
const scrollbarTrackBg = useColorModeValue("#f1f1f1", "#2D3748");
const scrollbarThumbBg = useColorModeValue("#888", "#4A5568");
const scrollbarThumbHoverBg = useColorModeValue("#555", "#718096");
// 根据主线类型获取配色
const getColorScheme = useCallback((lv2Name) => {
if (!lv2Name) return "gray";
const name = lv2Name.toLowerCase();
if (
name.includes("ai") ||
name.includes("人工智能") ||
name.includes("算力") ||
name.includes("大模型")
)
return "purple";
if (
name.includes("半导体") ||
name.includes("芯片") ||
name.includes("光刻")
)
return "blue";
if (name.includes("机器人") || name.includes("人形")) return "pink";
if (
name.includes("消费电子") ||
name.includes("手机") ||
name.includes("xr")
)
return "cyan";
if (
name.includes("汽车") ||
name.includes("驾驶") ||
name.includes("新能源车")
)
return "teal";
if (
name.includes("新能源") ||
name.includes("电力") ||
name.includes("光伏") ||
name.includes("储能")
)
return "green";
if (
name.includes("低空") ||
name.includes("航天") ||
name.includes("卫星")
)
return "orange";
if (name.includes("军工") || name.includes("国防")) return "red";
if (
name.includes("医药") ||
name.includes("医疗") ||
name.includes("生物")
)
return "messenger";
if (
name.includes("消费") ||
name.includes("食品") ||
name.includes("白酒")
)
return "yellow";
if (
name.includes("煤炭") ||
name.includes("石油") ||
name.includes("钢铁")
)
return "blackAlpha";
if (
name.includes("金融") ||
name.includes("银行") ||
name.includes("券商")
)
return "linkedin";
return "gray";
}, []);
// 加载主线数据
const fetchMainlineData = useCallback(async () => {
if (display === "none") return;
setLoading(true);
setError(null);
try {
const apiBase = getApiBase();
const params = new URLSearchParams();
// 添加筛选参数
if (filters.recent_days)
params.append("recent_days", filters.recent_days);
if (filters.importance && filters.importance !== "all")
params.append("importance", filters.importance);
const url = `${apiBase}/api/events/mainline?${params.toString()}`;
console.log("[MainlineTimelineView] 🔄 请求主线数据:", url);
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result = await response.json();
console.log("[MainlineTimelineView] 📦 响应数据:", {
success: result.success,
mainlineCount: result.data?.mainlines?.length,
totalEvents: result.data?.total_events,
});
if (result.success) {
setMainlineData(result.data);
// 初始化展开状态默认展开前5个
const initialExpanded = {};
result.data.mainlines?.slice(0, 5).forEach((mainline) => {
initialExpanded[mainline.lv2_id] = true;
});
setExpandedGroups(initialExpanded);
} else {
throw new Error(result.error || "获取数据失败");
}
} catch (err) {
console.error("[MainlineTimelineView] ❌ 请求失败:", err);
setError(err.message);
} finally {
setLoading(false);
}
}, [display, filters.recent_days, filters.importance]);
// 初始加载 & 筛选变化时刷新
useEffect(() => {
fetchMainlineData();
}, [fetchMainlineData]);
// 暴露方法给父组件
useImperativeHandle(
ref,
() => ({
refresh: fetchMainlineData,
getScrollPosition: () => null, // 不使用滚动位置判断
}),
[fetchMainlineData]
);
// 切换分组展开/折叠
const toggleGroup = useCallback((lv2Id) => {
setExpandedGroups((prev) => ({
...prev,
[lv2Id]: !prev[lv2Id],
}));
}, []);
// 全部展开/折叠
const toggleAll = useCallback(
(expand) => {
if (!mainlineData?.mainlines) return;
const newState = {};
mainlineData.mainlines.forEach((mainline) => {
newState[mainline.lv2_id] = expand;
});
setExpandedGroups(newState);
},
[mainlineData]
);
// 渲染加载状态
if (loading) {
return (
<Box display={display} p={8}>
<Center h="400px">
<VStack spacing={4}>
<Spinner size="xl" color="blue.500" thickness="4px" />
<Text color={secondaryTextColor}>正在加载主线数据...</Text>
</VStack>
</Center>
</Box>
);
}
// 渲染错误状态
if (error) {
return (
<Box display={display} p={8}>
<Center h="400px">
<VStack spacing={4}>
<Text color="red.500">加载失败: {error}</Text>
<IconButton
icon={<RepeatIcon />}
colorScheme="blue"
onClick={fetchMainlineData}
aria-label="重试"
/>
</VStack>
</Center>
</Box>
);
}
// 渲染空状态
if (!mainlineData?.mainlines?.length) {
return (
<Box display={display} p={8}>
<Center h="400px">
<VStack spacing={4}>
<Icon as={FiZap} boxSize={12} color="gray.400" />
<Text color={secondaryTextColor}>暂无主线数据</Text>
<Text fontSize="sm" color={secondaryTextColor}>
尝试调整筛选条件
</Text>
</VStack>
</Center>
</Box>
);
}
const {
mainlines,
total_events,
mainline_count,
ungrouped_count,
} = mainlineData;
return (
<Box
display={display}
overflowY="auto"
minH="600px"
maxH="800px"
w="100%"
bg={bgColor}
borderRadius="md"
css={{
"&::-webkit-scrollbar": { width: "6px" },
"&::-webkit-scrollbar-track": {
background: scrollbarTrackBg,
borderRadius: "10px",
},
"&::-webkit-scrollbar-thumb": {
background: scrollbarThumbBg,
borderRadius: "10px",
},
"&::-webkit-scrollbar-thumb:hover": {
background: scrollbarThumbHoverBg,
},
scrollBehavior: "smooth",
}}
>
{/* 顶部统计信息 */}
<Flex
justify="space-between"
align="center"
px={4}
py={3}
borderBottomWidth="1px"
borderColor={timelineBorderColor}
position="sticky"
top={0}
bg={bgColor}
zIndex={10}
>
<HStack spacing={4}>
<HStack spacing={2}>
<Icon as={FiTrendingUp} color="blue.500" />
<Text fontWeight="semibold" color={textColor}>
{mainline_count} 条主线
</Text>
</HStack>
<HStack spacing={2}>
<Icon as={FiClock} color="green.500" />
<Text fontSize="sm" color={secondaryTextColor}>
{total_events} 个事件
</Text>
</HStack>
{ungrouped_count > 0 && (
<Text fontSize="sm" color="orange.500">
({ungrouped_count} 个未归类)
</Text>
)}
</HStack>
<HStack spacing={2}>
<Tooltip label="全部展开">
<IconButton
icon={<ChevronDownIcon />}
size="sm"
variant="ghost"
onClick={() => toggleAll(true)}
aria-label="全部展开"
/>
</Tooltip>
<Tooltip label="全部折叠">
<IconButton
icon={<ChevronRightIcon />}
size="sm"
variant="ghost"
onClick={() => toggleAll(false)}
aria-label="全部折叠"
/>
</Tooltip>
<Tooltip label="刷新">
<IconButton
icon={<RepeatIcon />}
size="sm"
variant="ghost"
onClick={fetchMainlineData}
aria-label="刷新"
/>
</Tooltip>
</HStack>
</Flex>
{/* 主线列表 - 时间轴样式 */}
<Box position="relative" px={4} py={4}>
{/* 时间轴垂直线 */}
<Box
position="absolute"
left="28px"
top="0"
bottom="0"
w="2px"
bg={timelineLineColor}
opacity={0.5}
/>
<VStack spacing={4} align="stretch">
{mainlines.map((mainline, index) => {
const colorScheme = getColorScheme(mainline.lv2_name);
const isExpanded = expandedGroups[mainline.lv2_id];
return (
<Box key={mainline.lv2_id} position="relative" pl={10}>
{/* 时间轴圆点 */}
<Box
position="absolute"
left="22px"
top="16px"
w="14px"
h="14px"
borderRadius="full"
bg={`${colorScheme}.500`}
border="3px solid"
borderColor={bgColor}
boxShadow="0 0 0 2px"
sx={{ boxShadowColor: `${colorScheme}.200` }}
zIndex={2}
/>
{/* 分组头部 */}
<Flex
align="center"
justify="space-between"
px={4}
py={3}
bg={headerBg}
borderRadius="lg"
borderWidth="1px"
borderColor={timelineBorderColor}
cursor="pointer"
_hover={{ bg: headerHoverBg }}
onClick={() => toggleGroup(mainline.lv2_id)}
transition="all 0.2s"
boxShadow="sm"
>
<HStack spacing={3}>
<Icon
as={isExpanded ? ChevronDownIcon : ChevronRightIcon}
boxSize={5}
color={textColor}
transition="transform 0.2s"
/>
<VStack align="start" spacing={0}>
<HStack spacing={2}>
<Text
fontWeight="bold"
fontSize="md"
color={textColor}
>
{mainline.lv2_name}
</Text>
<Badge
colorScheme={colorScheme}
fontSize="xs"
borderRadius="full"
px={2}
>
{mainline.event_count}
</Badge>
</HStack>
<Text fontSize="xs" color={secondaryTextColor}>
{mainline.lv1_name}
</Text>
</VStack>
</HStack>
<HStack spacing={2}>
<Icon
as={TimeIcon}
color={secondaryTextColor}
boxSize={3}
/>
<Text fontSize="xs" color={secondaryTextColor}>
#{index + 1}
</Text>
</HStack>
</Flex>
{/* 分组内容 */}
<Collapse in={isExpanded} animateOpacity>
<Box
mt={3}
pl={2}
borderLeftWidth="2px"
borderLeftColor={`${colorScheme}.200`}
borderLeftStyle="dashed"
>
<Grid
templateColumns={`repeat(${columnsPerRow}, 1fr)`}
gap={3}
w="100%"
>
{mainline.events.map((event, eventIndex) => (
<Box key={event.id} w="100%" minW={0}>
<DynamicNewsEventCard
event={event}
index={eventIndex}
isFollowing={
eventFollowStatus[event.id]?.isFollowing ||
false
}
followerCount={
eventFollowStatus[event.id]?.followerCount ||
event.follower_count ||
0
}
isSelected={selectedEvent?.id === event.id}
onEventClick={(clickedEvent) => {
onEventSelect?.(clickedEvent);
}}
onTitleClick={(e) => {
e.preventDefault();
e.stopPropagation();
onEventSelect?.(event);
}}
onToggleFollow={() => onToggleFollow?.(event.id)}
borderColor={borderColor}
/>
</Box>
))}
</Grid>
</Box>
</Collapse>
</Box>
);
})}
</VStack>
</Box>
</Box>
);
}
);
MainlineTimelineViewComponent.displayName = "MainlineTimelineView";
const MainlineTimelineView = React.memo(MainlineTimelineViewComponent);
export default MainlineTimelineView;