summaryrefslogtreecommitdiff
path: root/apps/web/src/hooks/use-element-preview.ts
blob: d717143d510c6c51c666d83836661f0619c5b2dd (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
import { useEditor } from "@/hooks/use-editor";
import type { TimelineElement } from "@/lib/timeline";

/**
 * Subscribes to render tracks and returns the live (preview-aware) version of
 * an element alongside helpers for previewing and committing updates.
 *
 * Use this wherever property fields need to reflect in-progress preview state
 * (e.g. a slider being dragged) rather than the last committed value.
 */
export function useElementPreview<T extends TimelineElement>({
	trackId,
	elementId,
	fallback,
}: {
	trackId: string;
	elementId: string;
	fallback: T;
}) {
	const editor = useEditor();
	useEditor((e) => e.timeline.getRenderTracks());

	const renderElement =
		(editor.timeline
			.getRenderTracks()
			.find((t) => t.id === trackId)
			?.elements.find((el) => el.id === elementId) as T | undefined) ??
		fallback;

	const previewUpdates = (updates: Partial<TimelineElement>) =>
		editor.timeline.previewElements({
			updates: [{ trackId, elementId, updates }],
		});

	const commit = () => editor.timeline.commitPreview();

	return { renderElement, previewUpdates, commit };
}