2024-03-18 21:58:54 +01:00
|
|
|
import { useCallback } from "react";
|
|
|
|
|
2024-03-21 18:49:04 +01:00
|
|
|
export type TimelineUtilsProps = {
|
|
|
|
segmentDuration: number;
|
|
|
|
timelineDuration?: number;
|
|
|
|
timelineRef?: React.RefObject<HTMLElement>;
|
|
|
|
};
|
|
|
|
|
|
|
|
export function useTimelineUtils({
|
|
|
|
segmentDuration,
|
|
|
|
timelineDuration,
|
|
|
|
timelineRef,
|
|
|
|
}: TimelineUtilsProps) {
|
2024-03-18 21:58:54 +01:00
|
|
|
const alignEndDateToTimeline = useCallback(
|
|
|
|
(time: number): number => {
|
|
|
|
const remainder = time % segmentDuration;
|
|
|
|
const adjustment = remainder !== 0 ? segmentDuration - remainder : 0;
|
|
|
|
return time + adjustment;
|
|
|
|
},
|
|
|
|
[segmentDuration],
|
|
|
|
);
|
|
|
|
|
|
|
|
const alignStartDateToTimeline = useCallback(
|
|
|
|
(time: number): number => {
|
|
|
|
const remainder = time % segmentDuration;
|
|
|
|
const adjustment = remainder === 0 ? 0 : -remainder;
|
|
|
|
return time + adjustment;
|
|
|
|
},
|
|
|
|
[segmentDuration],
|
|
|
|
);
|
|
|
|
|
2024-03-21 03:56:15 +01:00
|
|
|
const getCumulativeScrollTop = useCallback((element: HTMLElement | null) => {
|
|
|
|
let scrollTop = 0;
|
|
|
|
while (element) {
|
|
|
|
scrollTop += element.scrollTop;
|
|
|
|
element = element.parentElement;
|
|
|
|
}
|
|
|
|
return scrollTop;
|
|
|
|
}, []);
|
|
|
|
|
2024-03-21 18:49:04 +01:00
|
|
|
const getVisibleTimelineDuration = useCallback(() => {
|
|
|
|
if (timelineRef?.current && timelineDuration) {
|
|
|
|
const {
|
|
|
|
scrollHeight: timelineHeight,
|
|
|
|
clientHeight: visibleTimelineHeight,
|
|
|
|
} = timelineRef.current;
|
|
|
|
|
|
|
|
const segmentHeight =
|
|
|
|
timelineHeight / (timelineDuration / segmentDuration);
|
|
|
|
|
|
|
|
const visibleTime =
|
|
|
|
(visibleTimelineHeight / segmentHeight) * segmentDuration;
|
|
|
|
|
|
|
|
return visibleTime;
|
|
|
|
}
|
|
|
|
}, [segmentDuration, timelineDuration, timelineRef]);
|
|
|
|
|
2024-03-18 21:58:54 +01:00
|
|
|
return {
|
|
|
|
alignEndDateToTimeline,
|
|
|
|
alignStartDateToTimeline,
|
2024-03-21 03:56:15 +01:00
|
|
|
getCumulativeScrollTop,
|
2024-03-21 18:49:04 +01:00
|
|
|
getVisibleTimelineDuration,
|
2024-03-18 21:58:54 +01:00
|
|
|
};
|
2024-03-21 18:49:04 +01:00
|
|
|
}
|