-
Notifications
You must be signed in to change notification settings - Fork 3.1k
Expand file tree
/
Copy pathuseGestureCommit.ts
More file actions
328 lines (306 loc) · 13.2 KB
/
Copy pathuseGestureCommit.ts
File metadata and controls
328 lines (306 loc) · 13.2 KB
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
/**
* Manages gesture recording state and commit logic for the Studio.
* Extracted from App.tsx to keep file sizes under the 600-line limit.
*/
import { useState, useCallback, useRef, useEffect } from "react";
import { editLog } from "../utils/editDebugLog";
import { useGestureRecording } from "./useGestureRecording";
import { simplifyGestureSamples } from "../utils/rdpSimplify";
import { smoothGestureKeyframes } from "../utils/gestureSmoother";
import { usePlayerStore } from "../player";
import type { DomEditSelection } from "../components/editor/domEditing";
import type { GsapAnimation } from "@hyperframes/core/gsap-parser";
import { roundTo3 } from "../utils/rounding";
import { classifyPropertyGroup } from "@hyperframes/core/gsap-parser";
type RecordedKeyframe = { percentage: number; properties: Record<string, number | string> };
/**
* Split recorded keyframes into one keyframe-set per property group (position /
* scale / rotation / …), each keyframe carrying only that group's props.
*
* A mixed-prop gesture (e.g. x/y + opacity) emitted as ONE add-with-keyframes
* mutation parses back as an untagged legacy mixed tween, which breaks the
* position-only drag intercept (it can't find a pure position tween to edit).
* Emitting one tween per group keeps the position tween tagged and editable.
* Keyframes with no prop in a group are dropped from that group's set.
*/
function partitionKeyframesByGroup(keyframes: RecordedKeyframe[]): RecordedKeyframe[][] {
// Preserve first-seen group order for deterministic, stable mutation ordering.
const groupOrder: string[] = [];
const byGroup = new Map<string, RecordedKeyframe[]>();
for (const kf of keyframes) {
const perGroup = new Map<string, Record<string, number | string>>();
for (const [key, value] of Object.entries(kf.properties)) {
const group = classifyPropertyGroup(key);
let props = perGroup.get(group);
if (!props) {
props = {};
perGroup.set(group, props);
}
props[key] = value;
}
for (const [group, props] of perGroup) {
let set = byGroup.get(group);
if (!set) {
set = [];
byGroup.set(group, set);
groupOrder.push(group);
}
set.push({ percentage: kf.percentage, properties: props });
}
}
return groupOrder.map((group) => byGroup.get(group)!);
}
// Minimal subset of the session used by gesture commit
interface GestureSessionRef {
domEditSelection: DomEditSelection | null;
selectedGsapAnimations?: GsapAnimation[];
commitMutation?: (
mutation: Record<string, unknown>,
options: { label: string; softReload?: boolean },
) => Promise<void>;
}
interface UseGestureCommitParams {
domEditSessionRef: React.MutableRefObject<GestureSessionRef>;
previewIframeRef: React.RefObject<HTMLIFrameElement | null>;
showToast: (message: string, tone?: "error" | "info") => void;
isGestureRecordingRef: React.MutableRefObject<boolean>;
}
export interface UseGestureCommitResult {
gestureState: "idle" | "recording";
gestureRecording: ReturnType<typeof useGestureRecording>;
handleToggleRecording: () => void;
}
// fallow-ignore-next-line complexity
export function useGestureCommit({
domEditSessionRef,
previewIframeRef,
showToast,
isGestureRecordingRef,
}: UseGestureCommitParams): UseGestureCommitResult {
const gestureRecording = useGestureRecording();
const [gestureState, setGestureState] = useState<"idle" | "recording">("idle");
const gestureStateRef = useRef<"idle" | "recording">("idle");
const recordingAutoStopRef = useRef<ReturnType<typeof setInterval>>(undefined);
const recordingStartTimeRef = useRef(0);
const commitInFlightRef = useRef(false);
// Capture selection at recording start so commit always targets the recorded element,
// even if the user's selection changes mid-recording.
const capturedSelectionRef = useRef<DomEditSelection | null>(null);
// Unmount: clear auto-stop interval
useEffect(() => () => clearInterval(recordingAutoStopRef.current), []);
// fallow-ignore-next-line complexity
const stopAndCommitRecording = useCallback(async () => {
clearInterval(recordingAutoStopRef.current);
if (commitInFlightRef.current) {
return;
}
commitInFlightRef.current = true;
gestureStateRef.current = "idle";
isGestureRecordingRef.current = false;
const frozenSamples = gestureRecording.stopRecording();
const store = usePlayerStore.getState();
store.setIsPlaying(false);
try {
const liveSession = domEditSessionRef.current;
const sel = capturedSelectionRef.current;
if (!sel) {
if (frozenSamples.length > 2) {
showToast("Selection lost during recording", "error");
}
return;
}
const duration =
frozenSamples.length > 0 ? (frozenSamples[frozenSamples.length - 1]?.time ?? 0) : 0;
if (frozenSamples.length <= 2) {
showToast("No gesture detected — move the pointer while recording", "error");
return;
}
if (duration <= 0) {
showToast("Recording too short — try again", "error");
return;
}
// Per-property epsilon: small-range properties (opacity 0–1, scale ~0.01–10)
// need a much tighter tolerance than positional properties (x/y in px).
const simplified = simplifyGestureSamples(frozenSamples, duration, (key) => {
if (key === "opacity") return 0.01;
if (key === "scale" || key === "scaleX" || key === "scaleY") return 0.01;
return 5;
});
const sortedPcts = Array.from(simplified.keys()).sort((a, b) => a - b);
// Ensure a 0% keyframe exists with the element's start-of-recording position
if (!simplified.has(0) && frozenSamples.length > 0) {
simplified.set(0, frozenSamples[0]!.properties);
if (!sortedPcts.includes(0)) sortedPcts.unshift(0);
}
const selector = sel.id ? `#${sel.id}` : sel.selector;
if (!selector) {
showToast("Cannot save — element has no selector", "error");
return;
}
if (liveSession.commitMutation) {
const recStart = recordingStartTimeRef.current;
const rawKeyframes = sortedPcts.map((pct) => ({
percentage: pct,
properties: simplified.get(pct) as Record<string, number | string>,
}));
// Smooth jittery pointer input — Gaussian-weighted moving average
// rounds off sharp corners while preserving overall path shape.
const keyframes = smoothGestureKeyframes(rawKeyframes, 3);
const hasPositionProps = keyframes.some((kf) =>
Object.keys(kf.properties).some((k) => classifyPropertyGroup(k) === "position"),
);
const allAnims = liveSession.selectedGsapAnimations ?? [];
const existingPositionTween = hasPositionProps
? allAnims.find((a) => a.propertyGroup === "position" && a.targetSelector === selector)
: undefined;
if (existingPositionTween) {
if (existingPositionTween.method === "set") {
// A `set` is a static hold, not a tween to merge into — replace it with
// the recorded motion (which already starts from the set's position).
await liveSession.commitMutation(
{
type: "replace-with-keyframes",
animationId: existingPositionTween.id,
targetSelector: selector,
position: roundTo3(recStart),
duration: roundTo3(duration),
keyframes,
},
{ label: "Gesture recording (replace set)", softReload: true },
);
} else {
const tweenStart = existingPositionTween.resolvedStart ?? 0;
const tweenDur = existingPositionTween.duration ?? duration;
const tweenEnd = tweenStart + tweenDur;
const recEnd = recStart + duration;
// Only merge if the recording overlaps the existing tween's time range.
// No overlap → fall through to add-with-keyframes (creates a separate tween).
const overlaps = recStart < tweenEnd + 0.05 && recEnd > tweenStart - 0.05;
if (overlaps) {
const existingKfs = existingPositionTween.keyframes?.keyframes ?? [];
const rangeStartPct =
tweenDur > 0 ? Math.max(0, ((recStart - tweenStart) / tweenDur) * 100) : 0;
const rangeEndPct =
tweenDur > 0 ? Math.min(100, ((recEnd - tweenStart) / tweenDur) * 100) : 100;
const preserved = existingKfs
.filter(
(kf) => kf.percentage < rangeStartPct - 0.5 || kf.percentage > rangeEndPct + 0.5,
)
.map((kf) => ({
percentage: kf.percentage,
properties: kf.properties,
...(kf.ease ? { ease: kf.ease } : {}),
}));
const mapped = keyframes.map((kf) => ({
percentage: rangeStartPct + (kf.percentage / 100) * (rangeEndPct - rangeStartPct),
properties: kf.properties,
}));
const merged = [...preserved, ...mapped].sort((a, b) => a.percentage - b.percentage);
await liveSession.commitMutation(
{
type: "replace-with-keyframes",
animationId: existingPositionTween.id,
targetSelector: selector,
position:
typeof existingPositionTween.position === "number"
? existingPositionTween.position
: tweenStart,
duration: tweenDur,
keyframes: merged,
},
{ label: "Gesture recording (merge)", softReload: true },
);
} else {
// Emit one tween per property group so a mixed-prop gesture (e.g.
// x/y + opacity) doesn't collapse into an untagged legacy mixed
// tween that the position-only drag intercept can't edit.
for (const groupKfs of partitionKeyframesByGroup(keyframes)) {
await liveSession.commitMutation(
{
type: "add-with-keyframes",
targetSelector: selector,
position: roundTo3(recStart),
duration: roundTo3(duration),
keyframes: groupKfs,
easeEach: "power1.inOut",
},
{ label: "Gesture recording (new range)", softReload: true },
);
}
}
}
} else {
// No existing tween — same per-group split as the new-range branch above.
for (const groupKfs of partitionKeyframesByGroup(keyframes)) {
await liveSession.commitMutation(
{
type: "add-with-keyframes",
targetSelector: selector,
position: roundTo3(recStart),
duration: roundTo3(duration),
keyframes: groupKfs,
easeEach: "power1.inOut",
},
{ label: "Gesture recording", softReload: true },
);
}
}
}
showToast(`Recorded ${sortedPcts.length} keyframes`, "info");
} catch (err) {
console.error("[GR:error]", err);
showToast(`Gesture commit failed: ${err}`, "error");
} finally {
store.requestSeek(recordingStartTimeRef.current);
gestureRecording.clearSamples();
setGestureState("idle");
commitInFlightRef.current = false;
}
}, [gestureRecording, showToast, isGestureRecordingRef, domEditSessionRef]);
const handleToggleRecording = useCallback(() => {
editLog("gesture", gestureStateRef.current === "recording" ? "stop" : "start", {
id: domEditSessionRef.current.domEditSelection?.id,
});
if (gestureStateRef.current === "recording") {
void stopAndCommitRecording();
return;
}
const sel = domEditSessionRef.current.domEditSelection;
if (!sel) {
showToast("Select an element first", "error");
return;
}
const iframe = previewIframeRef.current;
if (!iframe) {
showToast("Preview not ready — try again", "error");
return;
}
const store = usePlayerStore.getState();
recordingStartTimeRef.current = store.currentTime;
const elStart = Number.parseFloat(sel.dataAttributes?.start ?? "0") || 0;
const elDur = Number.parseFloat(sel.dataAttributes?.duration ?? "0") || 0;
const elementEnd = elDur > 0 ? elStart + elDur : undefined;
capturedSelectionRef.current = sel;
gestureRecording.startRecording(sel.element, iframe, elementEnd);
gestureStateRef.current = "recording";
isGestureRecordingRef.current = true;
setGestureState("recording");
clearInterval(recordingAutoStopRef.current);
const autoStopAt = elementEnd ?? Infinity;
recordingAutoStopRef.current = setInterval(() => {
const { currentTime: t, duration: d } = usePlayerStore.getState();
const limit = Math.min(autoStopAt, d);
if (limit > 0 && t >= limit - 0.05) {
void stopAndCommitRecording();
}
}, 100);
}, [
gestureRecording,
showToast,
stopAndCommitRecording,
previewIframeRef,
domEditSessionRef,
isGestureRecordingRef,
]);
return { gestureState, gestureRecording, handleToggleRecording };
}