blakeblackshear.frigate/web/src/hooks/use-timeline-utils.ts
Josh Hawkins 0ac7aaabe3
Timeline minimap and scrolling changes (#10589)
* add function to get visible timeline duration

* Don't show minimap when minimap bounds exceed timeline area

* when minimap is hidden, only scroll timeline when needed

* observe only when not showing minimap

* no need to duplicate observer

* fix out of order param

* timeline utils hook props

---------

Co-authored-by: Nicolas Mowen <nickmowen213@gmail.com>
2024-03-21 11:49:04 -06:00

65 lines
1.7 KiB
TypeScript

import { useCallback } from "react";
export type TimelineUtilsProps = {
segmentDuration: number;
timelineDuration?: number;
timelineRef?: React.RefObject<HTMLElement>;
};
export function useTimelineUtils({
segmentDuration,
timelineDuration,
timelineRef,
}: TimelineUtilsProps) {
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],
);
const getCumulativeScrollTop = useCallback((element: HTMLElement | null) => {
let scrollTop = 0;
while (element) {
scrollTop += element.scrollTop;
element = element.parentElement;
}
return scrollTop;
}, []);
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]);
return {
alignEndDateToTimeline,
alignStartDateToTimeline,
getCumulativeScrollTop,
getVisibleTimelineDuration,
};
}