import dayjs from "dayjs"; import { useEffect, useRef, useState } from "react"; import "./index.less"; export interface IOnScrollParam { top: number; height: number; } export interface IModel { top: number; } interface IProps { className: string; data: any; onScroll?: (p: IOnScrollParam) => void; model?: IModel; } /** * 处理年份在时间轴上面的显示 */ const filterYearOnce = (data: any[]) => { const flag: any[] = []; return data.map((item) => { if (!flag.includes(item.year)) { flag.push(item.year); return { ...item, visible: true }; } else { return { ...item, visible: false }; } }); }; function Timeline(props: IProps) { const [cursorStatic, setCursorStatic] = useState({ top: -4, color: "var(--color-fill-4)", }); const [cursorActive, setCursorActive] = useState({ top: 0, color: "var(--color-border-3)", }); const [intervalPixel, setIntervalPixel] = useState(1); const [timelineData, setTimelineData] = useState(filterYearOnce(props.data)); const cursorActiveRef = useRef(null); const cursorStaticRef = useRef(null); const orbitRef = useRef(); /** * 点击打圈圈 cursorStatic */ const onMouseDown = (ev: any) => { const orbitClient = orbitRef.current!.getBoundingClientRect(); let mouseY = (ev || window.event).clientY; //鼠标按下的位置 if (mouseY > orbitClient.top && mouseY < orbitClient.bottom) setCursorStatic((p) => ({ ...p, top: mouseY - orbitClient.top - 4 })); }; /** * 移动圈圈 coursorActive */ const onMouseMove = (ev: any) => { const orbitClient = orbitRef.current!.getBoundingClientRect(); const mouseY = (ev || window.event).clientY; if (mouseY > orbitClient.top && mouseY < orbitClient.bottom) setCursorActive((p) => ({ ...p, top: mouseY - orbitClient.top - 4 })); }; useEffect(() => { setCursorStatic((p) => ({ ...p, top: props.model!.top })); }, [props.model]); useEffect(() => { if (props.onScroll && orbitRef.current) props.onScroll({ top: cursorStatic.top, height: orbitRef.current.clientHeight, }); }, [cursorStatic.top]); useEffect(() => { if (props.data && orbitRef.current) { setTimelineData(filterYearOnce(props.data)); // 全部的月份数数量平均划分 const avg = orbitRef.current.clientHeight / props.data.length; setIntervalPixel(avg); } }, [props.data]); useEffect(() => { window.addEventListener("resize", () => { if (props.data && orbitRef.current) { setTimelineData(filterYearOnce(props.data)); // 全部的月份数数量平均划分 const avg = orbitRef.current.clientHeight / props.data.length; setIntervalPixel(avg); } }); return () => window.removeEventListener("resize", () => {}); }, []); return (
{timelineData.map((item: any, index: number) => { return item.visible ? (
) : (
); })}
); } export default Timeline;