summaryrefslogtreecommitdiff
path: root/apps/web/src/timeline/components/graph-editor/use-controller.ts
blob: ea09148560d4bd8ef3cf5c40be7005131ecef786 (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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
"use client";

import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useEditor } from "@/editor/use-editor";
import { registerCanceller } from "@/editor/cancel-interaction";
import type { NormalizedCubicBezier } from "@/animation/types";
import { useKeyframeSelection } from "@/timeline/hooks/element/use-keyframe-selection";
import {
	applyGraphEditorCurvePreview,
	buildGraphEditorCurvePatches,
	resolveGraphEditorSelectionState,
	type GraphEditorSelectionState,
} from "./session";

export function useGraphEditorController() {
	const editor = useEditor();
	const renderTracks = useEditor(
		(currentEditor) =>
			currentEditor.timeline.getPreviewTracks() ??
			currentEditor.scenes.getActiveScene().tracks,
	);
	const { selectedKeyframes } = useKeyframeSelection();
	const [open, setOpen] = useState(false);
	const [activeComponentKey, setActiveComponentKey] = useState<string | null>(
		null,
	);
	const hasPreviewRef = useRef(false);

	const state = useMemo<GraphEditorSelectionState>(
		() =>
			resolveGraphEditorSelectionState({
				tracks: renderTracks,
				selectedKeyframes,
				preferredComponentKey: activeComponentKey,
			}),
		[activeComponentKey, renderTracks, selectedKeyframes],
	);

	const stateKey =
		state.status === "ready"
			? `${state.trackId}:${state.elementId}:${state.activeComponentKey}:${state.segments
					.map(
						(segment) =>
							`${segment.propertyPath}:${segment.keyframeId}:${segment.context.componentKey}`,
					)
					.join("|")}`
			: `${state.status}:${state.reason}:${state.activeComponentKey ?? "none"}`;
	const previousStateKeyRef = useRef(stateKey);

	const discardPreview = useCallback(() => {
		if (!hasPreviewRef.current) {
			return;
		}

		editor.timeline.discardPreview();
		hasPreviewRef.current = false;
	}, [editor]);

	useEffect(() => {
		if (hasPreviewRef.current && previousStateKeyRef.current !== stateKey) {
			discardPreview();
		}

		previousStateKeyRef.current = stateKey;
	}, [discardPreview, stateKey]);

	useEffect(() => {
		if (!open) {
			return;
		}

		return registerCanceller({
			fn: () => {
				discardPreview();
				setOpen(false);
			},
		});
	}, [discardPreview, open]);

	const handleOpenChange = useCallback(
		(nextOpen: boolean) => {
			if (!nextOpen) {
				discardPreview();
			}

			setOpen(nextOpen);
		},
		[discardPreview],
	);

	const handleActiveComponentKeyChange = useCallback(
		(nextComponentKey: string) => {
			discardPreview();
			setActiveComponentKey(nextComponentKey);
		},
		[discardPreview],
	);

	const handlePreviewValue = useCallback(
		(nextValue: NormalizedCubicBezier) => {
			if (state.status !== "ready") {
				return;
			}

			const nextAnimations = state.segments.reduce(
				(animations, segment) =>
					segment.allContexts.reduce(
						(nextAnimationsForSegment, context) =>
							applyGraphEditorCurvePreview({
								animations: nextAnimationsForSegment,
								context,
								cubicBezier: nextValue,
								referenceSpanValue: segment.referenceSpanValue,
							}),
						animations,
					),
				state.element.animations,
			);
			editor.timeline.previewElements({
				updates: [
					{
						trackId: state.trackId,
						elementId: state.elementId,
						updates: { animations: nextAnimations },
					},
				],
			});
			hasPreviewRef.current = true;
		},
		[editor, state],
	);

	const handleCommitValue = useCallback(
		(nextValue: NormalizedCubicBezier) => {
			if (state.status !== "ready") {
				return;
			}

			editor.timeline.updateKeyframeCurves({
				keyframes: state.segments.flatMap((segment) => {
					const patches = buildGraphEditorCurvePatches({
						context: segment.context,
						cubicBezier: nextValue,
						referenceSpanValue: segment.referenceSpanValue,
					});
					if (!patches) {
						return [];
					}

					return segment.allContexts.flatMap((context) =>
						patches.map(({ keyframeId, patch }) => ({
							trackId: state.trackId,
							elementId: state.elementId,
							propertyPath: segment.propertyPath,
							componentKey: context.componentKey,
							keyframeId,
							patch,
						})),
					);
				}),
			});
			hasPreviewRef.current = false;
		},
		[editor, state],
	);

	return {
		open,
		onOpenChange: handleOpenChange,
		canOpen: state.status === "ready",
		tooltip: state.status === "ready" ? "Open graph editor" : state.message,
		state,
		onActiveComponentKeyChange: handleActiveComponentKeyChange,
		onPreviewValue: handlePreviewValue,
		onCommitValue: handleCommitValue,
		onCancelPreview: discardPreview,
	};
}