Files
timeline-frontend/src/pages/story/detail.tsx

533 lines
17 KiB
TypeScript
Raw Normal View History

2025-08-07 19:48:36 +08:00
// src/pages/story/detail.tsx
2025-08-05 19:02:14 +08:00
import AddTimeLineItemModal from '@/pages/story/components/AddTimeLineItemModal';
import TimelineItem from '@/pages/story/components/TimelineItem/TimelineItem';
import { StoryItem, StoryItemTimeQueryParams } from '@/pages/story/data';
2025-08-07 19:48:36 +08:00
import { queryStoryDetail, queryStoryItem } from '@/pages/story/service';
import { PlusOutlined, SyncOutlined } from '@ant-design/icons';
2025-08-05 19:02:14 +08:00
import { PageContainer } from '@ant-design/pro-components';
2025-08-08 17:42:07 +08:00
import { history, useRequest } from '@umijs/max';
import { Button, Empty, FloatButton, message, Spin } from 'antd';
2025-08-07 19:48:36 +08:00
import React, { useCallback, useEffect, useRef, useState } from 'react';
2025-08-05 19:02:14 +08:00
import { useParams } from 'react-router';
2025-08-07 19:48:36 +08:00
import AutoSizer from 'react-virtualized-auto-sizer';
2025-08-08 17:42:07 +08:00
import { VariableSizeList as List } from 'react-window';
2025-08-05 19:02:14 +08:00
import './index.css';
// 格式化时间数组为易读格式
const formatTimeArray = (time: string | number[] | undefined): string => {
if (!time) return '';
// 如果是数组格式 [2025, 12, 23, 8, 55, 39]
if (Array.isArray(time)) {
const [year, month, day, hour, minute, second] = time;
return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')} ${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}:${String(second).padStart(2, '0')}`;
}
// 如果已经是字符串格式,直接返回
return String(time);
};
2025-08-05 19:02:14 +08:00
const Index = () => {
const { id: lineId } = useParams<{ id: string }>();
const containerRef = useRef<HTMLDivElement>(null);
2025-08-08 17:42:07 +08:00
const listRef = useRef<any>(null);
const outerRef = useRef<HTMLDivElement>(null);
const topSentinelRef = useRef<HTMLDivElement>(null);
const bottomSentinelRef = useRef<HTMLDivElement>(null);
2025-08-07 19:48:36 +08:00
const [items, setItems] = useState<StoryItem[]>([]);
2025-08-05 19:02:14 +08:00
const [loading, setLoading] = useState(false);
2025-08-08 17:42:07 +08:00
const [hasMoreOld, setHasMoreOld] = useState(true); // 是否有更老的数据
const [hasMoreNew, setHasMoreNew] = useState(true); // 是否有更新的数据
2025-08-05 19:02:14 +08:00
const [openAddItemModal, setOpenAddItemModal] = useState(false);
const [currentItem, setCurrentItem] = useState<StoryItem>();
2025-08-07 19:48:36 +08:00
const [currentOption, setCurrentOption] = useState<
'add' | 'edit' | 'addSubItem' | 'editSubItem'
>();
const [pagination, setPagination] = useState({ current: 1, pageSize: 10 });
2025-08-08 17:42:07 +08:00
// 存储每个item的高度
const [itemSizes, setItemSizes] = useState<Record<string, number>>({});
// 存储已测量高度的item ID集合
const measuredItemsRef = useRef<Set<string>>(new Set());
const [isRefreshing, setIsRefreshing] = useState(false); // 是否正在刷新最新数据
const [showScrollTop, setShowScrollTop] = useState(false); // 是否显示回到顶部按钮
const [currentTimeArr, setCurrentTimeArr] = useState<[string | undefined, string | undefined]>([
undefined,
undefined,
]);
const [loadDirection, setLoadDirection] = useState<'init' | 'older' | 'newer' | 'refresh'>(
'init',
);
// 添加在其他 useRef 之后
const hasShownNoMoreOldRef = useRef(false);
const hasShownNoMoreNewRef = useRef(false);
const topLoadingRef = useRef(false); // 防止顶部循环加载
type QueryParams = StoryItemTimeQueryParams & { current?: number; pageSize?: number };
2025-08-05 19:02:14 +08:00
2025-08-07 19:48:36 +08:00
const { data: response, run } = useRequest(
(params?: QueryParams) => {
return queryStoryItem({ storyInstanceId: lineId, pageSize: pagination.pageSize, ...params });
2025-08-05 19:02:14 +08:00
},
{
manual: true,
},
);
2025-08-07 19:48:36 +08:00
2025-08-05 19:02:14 +08:00
const {
data: detail,
run: queryDetail,
loading: queryDetailLoading,
} = useRequest(() => {
return queryStoryDetail(lineId ?? '');
});
2025-08-07 19:48:36 +08:00
2025-08-05 19:02:14 +08:00
// 初始化加载数据
useEffect(() => {
2025-08-08 17:42:07 +08:00
setHasMoreOld(true);
setHasMoreNew(true);
// 重置高度缓存
setItemSizes({});
measuredItemsRef.current = new Set();
setLoadDirection('init');
setLoading(true);
run({ current: 1 });
2025-08-05 19:02:14 +08:00
}, [lineId]);
2025-08-07 19:48:36 +08:00
// 处理响应数据
2025-08-05 19:02:14 +08:00
useEffect(() => {
2025-08-07 19:48:36 +08:00
if (!response) return;
const fetched = response.list || [];
const pageSize = pagination.pageSize;
const noMore = !(fetched.length === pageSize);
// 若无新数据则避免触发列表重绘,只更新加载状态
if (!fetched.length) {
if (loadDirection === 'older') {
setHasMoreOld(false);
} else if (loadDirection === 'newer') {
setHasMoreNew(false);
topLoadingRef.current = false;
}
setLoading(false);
setIsRefreshing(false);
setLoadDirection('init');
return;
2025-08-07 19:48:36 +08:00
}
if (loadDirection === 'older') {
setItems((prev) => {
const next = [...prev, ...fetched];
setCurrentTimeArr([next[0]?.storyItemTime, next[next.length - 1]?.storyItemTime]);
return next;
});
setHasMoreOld(!noMore);
if (noMore && !hasShownNoMoreOldRef.current) {
hasShownNoMoreOldRef.current = true;
message.info('没有更多历史内容了');
}
} else if (loadDirection === 'newer') {
setItems((prev) => {
const next = [...fetched, ...prev];
setCurrentTimeArr([next[0]?.storyItemTime, next[next.length - 1]?.storyItemTime]);
if (listRef.current && fetched.length) {
requestAnimationFrame(() => listRef.current?.scrollToItem(fetched.length + 1, 'start'));
}
return next;
});
setHasMoreNew(!noMore);
if (noMore && !hasShownNoMoreNewRef.current) {
hasShownNoMoreNewRef.current = true;
message.info('没有更多更新内容了');
}
topLoadingRef.current = false;
} else if (loadDirection === 'refresh') {
topLoadingRef.current = false;
} else {
setItems(fetched);
setCurrentTimeArr([fetched[0]?.storyItemTime, fetched[fetched.length - 1]?.storyItemTime]);
setHasMoreOld(!noMore);
setHasMoreNew(true);
2025-08-08 17:42:07 +08:00
}
2025-08-07 19:48:36 +08:00
setLoading(false);
2025-08-08 17:42:07 +08:00
setIsRefreshing(false);
setLoadDirection('init');
}, [response, loadDirection, pagination.pageSize]);
2025-08-05 19:02:14 +08:00
2025-08-08 17:42:07 +08:00
// 获取item高度的函数
const getItemSize = useCallback(
(index: number) => {
2025-08-08 17:42:07 +08:00
const item = items[index];
if (!item) return 400; // 默认高度
const key = String(item.id ?? item.instanceId);
2025-08-08 17:42:07 +08:00
if (itemSizes[key]) {
return itemSizes[key];
2025-08-08 17:42:07 +08:00
}
return 400;
},
[items, itemSizes, loadDirection, loading],
);
2025-08-08 17:42:07 +08:00
// 当item尺寸发生变化时调用
const onItemResize = useCallback(
(itemId: string, height: number) => {
2025-08-08 17:42:07 +08:00
// 只有当高度发生变化时才更新
if (itemSizes[itemId] !== height) {
setItemSizes((prev) => ({
2025-08-08 17:42:07 +08:00
...prev,
[itemId]: height,
2025-08-08 17:42:07 +08:00
}));
// 通知List组件重新计算尺寸
if (listRef.current) {
listRef.current.resetAfterIndex(0);
}
}
},
[itemSizes],
);
// 滚动到底部加载更老的数据
const loadOlder = useCallback(() => {
if (loading || !hasMoreOld) {
if (!hasMoreOld && !loading) {
message.info('没有更多历史内容了');
}
return;
}
const beforeTime = items[items.length - 1]?.storyItemTime || currentTimeArr[1];
if (!beforeTime) return;
const nextPage = pagination.current + 1;
setPagination((prev) => ({ ...prev, current: nextPage }));
setLoadDirection('older');
setLoading(true);
run({ current: nextPage });
}, [loading, hasMoreOld, items, currentTimeArr, pagination.current, run]);
// 滚动到顶部加载更新的数据
const loadNewer = useCallback(() => {
if (loading || !hasMoreNew || isRefreshing || topLoadingRef.current) {
if (!hasMoreNew && !loading && !isRefreshing) {
message.info('没有更多更新内容了');
}
return;
}
const afterTime = items[0]?.storyItemTime || currentTimeArr[0];
if (!afterTime) return;
setPagination((prev) => ({ ...prev, current: 1 }));
setLoadDirection('newer');
setIsRefreshing(true);
setLoading(true);
topLoadingRef.current = true;
run({ current: 1 });
}, [loading, hasMoreNew, isRefreshing, items, currentTimeArr, run]);
2025-08-08 17:42:07 +08:00
2025-08-07 19:48:36 +08:00
// 渲染单个时间线项的函数
const renderTimelineItem = useCallback(
({ index, style }: { index: number; style: React.CSSProperties }) => {
const item = items[index];
if (!item) return null;
const key = String(item.id ?? item.instanceId);
2025-08-07 19:48:36 +08:00
return (
<div style={style}>
2025-08-08 17:42:07 +08:00
<div
ref={(el) => {
// 当元素被渲染时测量其实际高度
if (el && !measuredItemsRef.current.has(key)) {
measuredItemsRef.current.add(key);
2025-08-08 17:42:07 +08:00
// 使用requestAnimationFrame确保DOM已经渲染完成
requestAnimationFrame(() => {
if (el) {
const height = el.getBoundingClientRect().height;
onItemResize(key, height);
2025-08-08 17:42:07 +08:00
}
});
}
2025-08-07 19:48:36 +08:00
}}
style={{
margin: '12px 0',
padding: '16px',
backgroundColor: '#fff',
borderRadius: '8px',
boxShadow: '0 1px 4px rgba(0,0,0,0.05)',
border: '1px solid #f0f0f0',
transition: 'all 0.2s ease-in-out',
}}
onMouseEnter={(e) => {
(e.currentTarget as HTMLDivElement).style.boxShadow = '0 2px 8px rgba(0,0,0,0.1)';
(e.currentTarget as HTMLDivElement).style.transform = 'translateY(-2px)';
}}
onMouseLeave={(e) => {
(e.currentTarget as HTMLDivElement).style.boxShadow = '0 1px 4px rgba(0,0,0,0.05)';
(e.currentTarget as HTMLDivElement).style.transform = 'translateY(0)';
}}
2025-08-08 17:42:07 +08:00
>
<TimelineItem
item={item}
handleOption={(
item: StoryItem,
option: 'add' | 'edit' | 'addSubItem' | 'editSubItem',
) => {
setCurrentItem(item);
setCurrentOption(option);
setOpenAddItemModal(true);
}}
refresh={() => {
// 刷新当前页数据
setPagination((prev) => ({ ...prev, current: 1 }));
2025-08-08 17:42:07 +08:00
// 重置高度测量
measuredItemsRef.current = new Set();
hasShownNoMoreOldRef.current = false;
hasShownNoMoreNewRef.current = false;
setLoadDirection('refresh');
run({ current: 1 });
2025-08-08 17:42:07 +08:00
queryDetail();
}}
/>
</div>
2025-08-07 19:48:36 +08:00
</div>
);
},
[items, hasMoreOld, loadDirection, loading, onItemResize, run, queryDetail],
2025-08-07 19:48:36 +08:00
);
// 使用 IntersectionObserver 监听顶部/底部哨兵实现无限滚动
useEffect(() => {
const root = outerRef.current;
const topEl = topSentinelRef.current;
const bottomEl = bottomSentinelRef.current;
if (!root || !topEl || !bottomEl) return;
const topObserver = new IntersectionObserver(
(entries) => {
if (entries.some((e) => e.isIntersecting)) {
loadNewer();
}
},
{ root, rootMargin: '120px 0px 0px 0px', threshold: 0 },
);
const bottomObserver = new IntersectionObserver(
(entries) => {
if (entries.some((e) => e.isIntersecting)) {
loadOlder();
}
},
{ root, rootMargin: '0px 0px 120px 0px', threshold: 0 },
);
2025-08-08 17:42:07 +08:00
topObserver.observe(topEl);
bottomObserver.observe(bottomEl);
2025-08-08 17:42:07 +08:00
// 仅用于显示"回到顶部"按钮
const handleScroll = () => {
const { scrollTop } = root;
setShowScrollTop(scrollTop > 200);
};
root.addEventListener('scroll', handleScroll);
return () => {
topObserver.disconnect();
bottomObserver.disconnect();
root.removeEventListener('scroll', handleScroll);
};
}, [loadNewer, loadOlder]);
2025-08-08 17:42:07 +08:00
// 手动刷新最新数据
const handleRefresh = () => {
if (isRefreshing) return;
setIsRefreshing(true);
setLoadDirection('refresh');
setPagination((prev) => ({ ...prev, current: 1 }));
hasShownNoMoreOldRef.current = false;
hasShownNoMoreNewRef.current = false;
run({ current: 1 });
2025-08-08 17:42:07 +08:00
};
// 回到顶部
const scrollToTop = () => {
if (listRef.current) {
listRef.current.scrollToItem(0, 'start');
}
};
2025-08-05 19:02:14 +08:00
return (
<PageContainer
onBack={() => history.push('/story')}
2025-08-07 19:48:36 +08:00
title={
queryDetailLoading ? '加载中' : `${detail?.title} ${`${detail?.itemCount ?? 0}个时刻`}`
}
2025-08-08 17:42:07 +08:00
extra={
<Button
icon={<SyncOutlined />}
onClick={() => {
setItems([]);
setPagination({ current: 1, pageSize: 10 });
setLoadDirection('refresh');
run({ current: 1 });
}}
2025-08-08 17:42:07 +08:00
loading={isRefreshing}
>
</Button>
}
2025-08-05 19:02:14 +08:00
>
2025-08-07 19:48:36 +08:00
<div
className="timeline"
ref={containerRef}
style={{
height: 'calc(100vh - 200px)',
2025-08-08 17:42:07 +08:00
overflow: 'hidden',
position: 'relative',
padding: '0 16px', // 添加一些内边距
2025-08-07 19:48:36 +08:00
}}
>
{items.length > 0 ? (
2025-08-08 17:42:07 +08:00
<>
<AutoSizer>
{({ height, width }) => (
<>
2025-08-07 19:48:36 +08:00
<List
2025-08-08 17:42:07 +08:00
ref={listRef}
outerRef={outerRef}
height={height}
itemCount={items.length}
2025-08-08 17:42:07 +08:00
itemSize={getItemSize}
2025-08-07 19:48:36 +08:00
width={width}
innerElementType={React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>((props, ref) => (
<div ref={ref} {...props}>
<div ref={topSentinelRef} style={{ height: 1 }} />
{props.children}
<div ref={bottomSentinelRef} style={{ height: 1 }} />
</div>
))}
2025-08-07 19:48:36 +08:00
>
{renderTimelineItem}
</List>
<div className="load-indicator">{loading && '加载中...'}</div>
<div className="no-more-data">{!loading && '已加载全部历史数据'}</div>
</>
2025-08-08 17:42:07 +08:00
)}
</AutoSizer>
{/* 回到顶部按钮 */}
{showScrollTop && (
<div
style={{
2025-08-08 17:42:07 +08:00
position: 'absolute',
bottom: 20,
right: 20,
zIndex: 10,
}}
>
2025-08-08 17:42:07 +08:00
<Button
type="primary"
shape="circle"
icon={<SyncOutlined />}
onClick={scrollToTop}
/>
2025-08-07 19:48:36 +08:00
</div>
)}
2025-08-08 17:42:07 +08:00
</>
2025-08-07 19:48:36 +08:00
) : (
<div
style={{
2025-08-08 17:42:07 +08:00
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
height: '100%',
textAlign: 'center',
}}
>
2025-08-08 17:42:07 +08:00
{loading ? (
<>
<Spin size="large" />
<div
style={{
marginTop: 16,
fontSize: '16px',
color: '#666',
2025-08-08 17:42:07 +08:00
}}
>
线...
</div>
2025-08-08 17:42:07 +08:00
</>
) : (
<>
<Empty
description="暂无时间线数据"
image={Empty.PRESENTED_IMAGE_SIMPLE}
imageStyle={{
height: 60,
}}
>
<div
style={{
fontSize: '16px',
color: '#999',
marginBottom: '16px',
}}
>
</div>
</Empty>
<Button
type="primary"
size="large"
onClick={() => {
setCurrentOption('add');
setCurrentItem(undefined);
setOpenAddItemModal(true);
}}
>
</Button>
</>
2025-08-08 17:42:07 +08:00
)}
2025-08-07 19:48:36 +08:00
</div>
)}
2025-08-05 19:02:14 +08:00
</div>
2025-08-07 19:48:36 +08:00
<FloatButton
onClick={() => {
setCurrentOption('add');
setCurrentItem(undefined);
2025-08-07 19:48:36 +08:00
setOpenAddItemModal(true);
}}
icon={<PlusOutlined />}
type="primary"
style={{
right: 24,
bottom: 24,
}}
2025-08-07 19:48:36 +08:00
/>
2025-08-05 19:02:14 +08:00
<AddTimeLineItemModal
visible={openAddItemModal}
initialValues={currentItem}
option={currentOption || 'add'}
2025-08-05 19:02:14 +08:00
onCancel={() => {
setOpenAddItemModal(false);
}}
onOk={() => {
setOpenAddItemModal(false);
2025-08-07 19:48:36 +08:00
// 添加新项后刷新数据
setPagination((prev) => ({ ...prev, current: 1 }));
2025-08-08 17:42:07 +08:00
// 重置高度测量
measuredItemsRef.current = new Set();
setLoadDirection('refresh');
run({ current: 1 });
2025-08-08 17:42:07 +08:00
queryDetail();
2025-08-05 19:02:14 +08:00
}}
storyId={lineId}
/>
</PageContainer>
);
};
export default Index;