summaryrefslogtreecommitdiff
path: root/apps/web/src/timeline/hooks/element/use-keyframe-drag.ts
blob: 5a1ff1f00799f061b12f180e37dee978b6bf49c2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { useEffect, useReducer, useRef } from "react";
import { useEditor } from "@/editor/use-editor";
import { useKeyframeSelection } from "./use-keyframe-selection";
import { registerCanceller } from "@/editor/cancel-interaction";
import {
	KeyframeDragController,
	type KeyframeDragConfig,
	type KeyframeDragState,
} from "@/timeline/controllers/keyframe-drag-controller";
import type { TimelineElement } from "@/timeline";

export type { KeyframeDragState };

export function useKeyframeDrag({
	zoomLevel,
	element,
	displayedStartTime,
}: {
	zoomLevel: number;
	element: TimelineElement;
	displayedStartTime: number;
}) {
	const editor = useEditor();
	const {
		selectedKeyframes,
		isKeyframeSelected,
		setKeyframeSelection,
		toggleKeyframeSelection,
		selectKeyframeRange,
	} = useKeyframeSelection();

	const config: KeyframeDragConfig = {
		zoomLevel,
		element,
		displayedStartTime,
		getFps: () => editor.project.getActive()?.settings.fps ?? null,
		selectedKeyframes,
		isKeyframeSelected,
		setKeyframeSelection,
		toggleKeyframeSelection,
		selectKeyframeRange,
		executeCommand: (command) => editor.command.execute({ command }),
		seek: (args) => editor.playback.seek(args),
		getTotalDuration: () => editor.timeline.getTotalDuration(),
	};

	const configRef = useRef<KeyframeDragConfig>(config);
	configRef.current = config;

	const controllerRef = useRef<KeyframeDragController | null>(null);
	if (!controllerRef.current) {
		controllerRef.current = new KeyframeDragController({ configRef });
	}
	const controller = controllerRef.current;

	const [, rerender] = useReducer((n: number) => n + 1, 0);
	useEffect(() => controller.subscribe(rerender), [controller]);

	useEffect(() => {
		if (!controller.isActive) return;
		return registerCanceller({ fn: () => controller.cancel() });
	}, [controller.isActive, controller]);

	useEffect(() => () => controller.destroy(), [controller]);

	return {
		keyframeDragState: controller.keyframeDragState,
		handleKeyframeMouseDown: controller.onKeyframeMouseDown,
		handleKeyframeClick: controller.onKeyframeClick,
		getVisualOffsetPx: controller.getVisualOffsetPx,
	};
}