diff --git a/packages/studio-server/src/routes/files.test.ts b/packages/studio-server/src/routes/files.test.ts index f2db23a3d6..ffd9f61a8c 100644 --- a/packages/studio-server/src/routes/files.test.ts +++ b/packages/studio-server/src/routes/files.test.ts @@ -1830,6 +1830,47 @@ tl.to("#box", { opacity: 1, duration: 1 }, 0); expect(result.after).not.toContain("data-hf-studio-rotation"); }); + it("replace-with-keyframes preserves per-segment easing for exact temporal keyframes", async () => { + const projectDir = createProjectDir(); + const PATH_COMP = ` +
+ +`; + writeHtml(projectDir, "path.html", PATH_COMP); + const app = new Hono(); + registerFileRoutes(app, createAdapter(projectDir)); + + const anim = await getFirstAnimation(app, "path.html"); + const res = await app.request("http://localhost/projects/demo/gsap-mutations/path.html", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + type: "replace-with-keyframes", + animationId: anim.id, + targetSelector: "#box", + position: 12.17, + duration: 16.055, + keyframes: [ + { percentage: 0, properties: { x: 0, y: 0 } }, + { percentage: 23.2, properties: { x: 25, y: 30 } }, + { percentage: 100, properties: { x: 100, y: 100 } }, + ], + ease: "none", + }), + }); + const result = (await res.json()) as { ok: boolean; after: string }; + + expect(res.status).toBe(200); + expect(result.ok).toBe(true); + expect(result.after).toContain('"23.2%"'); + expect(result.after).toContain('easeEach: "power1.inOut"'); + expect(result.after).toContain('ease: "none"'); + expect(result.after).not.toContain("motionPath"); + }); + it("edits a template-wrapped tween in place, preserving gsap.set and the IIFE", async () => { const projectDir = createProjectDir(); writeComp(projectDir, "scene.html", TEMPLATE_COMP); diff --git a/packages/studio-server/src/routes/files.ts b/packages/studio-server/src/routes/files.ts index 01e7c3f841..3ec64bbff1 100644 --- a/packages/studio-server/src/routes/files.ts +++ b/packages/studio-server/src/routes/files.ts @@ -997,6 +997,7 @@ export type GsapMutationRequest = auto?: boolean; }>; ease?: string; + easeEach?: string; } | { type: "split-animations"; @@ -1052,6 +1053,18 @@ export type GsapMutationRequest = type GsapMutationResult = string | { script: string; skippedSelectors: string[] }; +function resolveReplacementEaseEach( + scriptText: string, + request: { animationId: string; easeEach?: string }, +): string | undefined { + if (request.easeEach !== undefined) return request.easeEach; + const original = parseGsapScriptAcorn(scriptText).animations.find( + (animation) => animation.id === request.animationId, + ); + if (!original?.arcPath?.enabled) return undefined; + return original?.keyframes?.easeEach ?? original?.ease; +} + // Mutations that can change a position tween's first keyframe (value/existence/timing) // and therefore require the pre-keyframe hold-`set`s to be re-synced afterwards. // `syncPositionHoldsBeforeKeyframes` rebuilds all `hf-hold` sets from scratch: it acts @@ -1507,6 +1520,7 @@ function executeGsapMutationAcorn( body.duration, body.keyframes, body.ease, + resolveReplacementEaseEach(block.scriptText, body), ); return added.script; } @@ -1877,6 +1891,7 @@ async function executeGsapMutationRecast( body.duration, body.keyframes, body.ease, + resolveReplacementEaseEach(block.scriptText, body), ); return added.script; } diff --git a/packages/studio/src/App.tsx b/packages/studio/src/App.tsx index ad131e3a62..b661872d67 100644 --- a/packages/studio/src/App.tsx +++ b/packages/studio/src/App.tsx @@ -1,7 +1,7 @@ import { useState, useCallback, useRef, useMemo, useEffect, useLayoutEffect } from "react"; import type { LeftSidebarHandle, SidebarTab } from "./components/sidebar/LeftSidebar"; import { useRenderQueue } from "./components/renders/useRenderQueue"; -import { usePlayerStore, type TimelineElement } from "./player"; +import { usePlayerStore } from "./player"; import { StudioOverlays } from "./components/StudioOverlays"; import { SaveQueuePausedBanner } from "./components/SaveQueuePausedBanner"; import { useCaptionStore } from "./captions/store"; @@ -12,9 +12,12 @@ import { useFileManager } from "./hooks/useFileManager"; import { usePreviewPersistence } from "./hooks/usePreviewPersistence"; import { usePreviewDocumentVersion } from "./hooks/usePreviewDocumentVersion"; import { useTimelineEditing } from "./hooks/useTimelineEditing"; -import { persistTimelineMoveEditsAtomically } from "./hooks/timelineMoveAdapter"; +import { + persistTimelineMoveEditsAtomically, + type TimelineMoveEditsHandler, + type TimelineMoveOperation, +} from "./hooks/timelineMoveAdapter"; import type { TimelineZIndexReorderCommit } from "./hooks/useTimelineEditingTypes"; -import type { TimelineStackingReorderIntent } from "./player/components/timelineStacking"; import type { BlockPreviewInfo } from "./components/sidebar/BlocksTab"; import { useDomEditSession } from "./hooks/useDomEditSession"; import { useSdkSelectionSync } from "./hooks/useSdkSelectionSync"; @@ -62,7 +65,6 @@ import { } from "./utils/studioUrlState"; import { trackStudioSessionStart } from "./telemetry/events"; import { hasFiredSessionStart, markSessionStartFired } from "./telemetry/config"; -type TimelineMoveOperation = Parameters[2]; // fallow-ignore-next-line complexity export function StudioApp() { const { projectId, resolving, waitingForServer } = useServerConnection(); @@ -154,6 +156,7 @@ export function StudioApp() { reloadPreview: () => setRefreshKey((k) => k + 1), pendingTimelineEditPathRef, }); + const invalidateGsapCacheRef = useRef<() => void>(() => {}); const timelineEditing = useTimelineEditing({ projectId, activeCompPath, @@ -171,20 +174,11 @@ export function StudioApp() { sdkSession: editFlowSdkSession, publishSdkSession: sdkHandle.publish, forceReloadSdkSession: sdkHandle.forceReload, + invalidateGsapCache: () => invalidateGsapCacheRef.current(), handleDomZIndexReorderCommitRef, }); - const handleTimelineElementsMove = useCallback( - async ( - edits: Array<{ - element: TimelineElement; - updates: Pick & { - stackingReorder?: TimelineStackingReorderIntent | null; - }; - }>, - coalesceKey?: string, - operation: TimelineMoveOperation = "timing", - coalesceMs?: number, - ) => { + const handleTimelineElementsMove: TimelineMoveEditsHandler = useCallback( + async (edits, coalesceKey, operation: TimelineMoveOperation = "timing", coalesceMs) => { const deps = { handleTimelineGroupMove: timelineEditing.handleTimelineGroupMove }; await persistTimelineMoveEditsAtomically(edits, coalesceKey, operation, deps, coalesceMs); }, @@ -228,7 +222,6 @@ export function StudioApp() { const domEditDeleteBridge = (s: DomEditSelection) => handleDomEditElementDeleteRef.current(s); const resetKeyframesRef = useRef<() => boolean>(() => false); const deleteSelectedKeyframesRef = useRef<() => void>(() => {}); - const invalidateGsapCacheRef = useRef<() => void>(() => {}); const { handleCopy, handlePaste, handleCut } = useClipboard({ projectId, activeCompPath, @@ -408,6 +401,7 @@ export function StudioApp() { panelLayout.rightInspectorPanes, panelLayout.rightCollapsed, isPlaying, + domEditSession.domEditSelection, gestureState === "recording", ); useStudioUrlState({ diff --git a/packages/studio/src/components/TimelineToolbar.test.tsx b/packages/studio/src/components/TimelineToolbar.test.tsx index 0c21e5e043..0050dcfc95 100644 --- a/packages/studio/src/components/TimelineToolbar.test.tsx +++ b/packages/studio/src/components/TimelineToolbar.test.tsx @@ -2,8 +2,10 @@ import React, { act } from "react"; import { createRoot } from "react-dom/client"; -import { afterEach, describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { GsapAnimation } from "@hyperframes/core/gsap-parser"; import { usePlayerStore } from "../player/store/playerStore"; +import { makeSelection } from "../hooks/domSelectionTestHarness"; import { TimelineToolbar } from "./TimelineToolbar"; (globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; @@ -13,12 +15,14 @@ afterEach(() => { usePlayerStore.setState({ autoKeyframeEnabled: true }); }); -function renderToolbar() { +function renderToolbar( + domEditSession?: React.ComponentProps["domEditSession"], +) { const host = document.createElement("div"); document.body.append(host); const root = createRoot(host); act(() => { - root.render(); + root.render(); }); return { host, root }; } @@ -54,3 +58,44 @@ describe("TimelineToolbar — auto-keyframe toggle (#1808)", () => { act(() => root.unmount()); }); }); +describe("TimelineToolbar — motion path endpoints", () => { + it("does not advertise a destructive keyframe toggle for a required endpoint", () => { + usePlayerStore.setState({ currentTime: 10 }); + const animation: GsapAnimation = { + id: "#el-to-0-position", + targetSelector: "#el", + method: "to", + position: 0, + duration: 10, + properties: {}, + keyframes: { + format: "object-array", + keyframes: [ + { percentage: 0, properties: { x: 0, y: 0 } }, + { percentage: 100, properties: { x: 100, y: 0 } }, + ], + }, + arcPath: { + enabled: true, + autoRotate: false, + segments: [{ curviness: 1 }], + }, + }; + const element = document.createElement("div"); + element.id = "el"; + const session = { + domEditSelection: makeSelection("Element", element), + selectedGsapAnimations: [animation], + handleGsapAddAnimation: vi.fn(), + handleGsapConvertToKeyframes: vi.fn(), + handleGsapRemoveKeyframe: vi.fn(), + } satisfies NonNullable["domEditSession"]>; + + const { host, root } = renderToolbar(session); + const button = host.querySelector( + 'button[aria-label="Motion path endpoint"]', + ); + expect(button?.disabled).toBe(true); + act(() => root.unmount()); + }); +}); diff --git a/packages/studio/src/components/TimelineToolbar.tsx b/packages/studio/src/components/TimelineToolbar.tsx index 1e314ed4ef..43416414d5 100644 --- a/packages/studio/src/components/TimelineToolbar.tsx +++ b/packages/studio/src/components/TimelineToolbar.tsx @@ -36,6 +36,60 @@ interface TimelineToolbarProps { onSplitElement?: (element: TimelineElement, splitTime: number) => void; } +interface KeyframeToggleState { + state: "active" | "inactive" | "none"; + isMotionPath: boolean; + pathEndpoint: boolean; + willExtend: boolean; +} + +const NO_KEYFRAME_TOGGLE: KeyframeToggleState = { + state: "none", + isMotionPath: false, + pathEndpoint: false, + willExtend: false, +}; + +function isMotionPathEndpoint(animation: GsapAnimation | undefined, percentage: number): boolean { + if (!animation?.keyframes) return false; + const keyframes = animation.keyframes.keyframes; + return ( + Math.abs((keyframes[0]?.percentage ?? -Infinity) - percentage) <= 1 || + Math.abs((keyframes.at(-1)?.percentage ?? Infinity) - percentage) <= 1 + ); +} + +function resolveKeyframeToggleState( + session: DomEditSessionSlice | undefined, + currentTime: number, +): KeyframeToggleState { + if (!session?.domEditSelection) return NO_KEYFRAME_TOGGLE; + const arcAnimation = session.selectedGsapAnimations.find( + (animation) => animation.arcPath && animation.keyframes, + ); + const animation = + arcAnimation ?? + session.selectedGsapAnimations.find((candidate) => candidate.keyframes && !candidate.arcPath); + if (!animation?.keyframes) return NO_KEYFRAME_TOGGLE; + + const isMotionPath = Boolean(arcAnimation); + if (!isPlayheadWithinTween(animation, currentTime)) { + return { state: "inactive", isMotionPath, pathEndpoint: false, willExtend: true }; + } + + const percentage = computeElementPercentage(currentTime, session.domEditSelection, animation); + const pathEndpoint = isMotionPathEndpoint(arcAnimation, percentage); + const active = animation.keyframes.keyframes.some( + (keyframe) => Math.abs(keyframe.percentage - percentage) <= 1, + ); + return { + state: pathEndpoint ? "none" : active ? "active" : "inactive", + isMotionPath, + pathEndpoint, + willExtend: false, + }; +} + function useKeyframeToggle(session?: DomEditSessionSlice) { const currentTime = usePlayerStore((s) => s.currentTime); const sessionRef = useRef(session); @@ -45,31 +99,12 @@ function useKeyframeToggle(session?: DomEditSessionSlice) { sessionRef as React.RefObject, ); - if (!session) return { state: "none" as const, onToggle: undefined }; - - const sel = session.domEditSelection; - const anims = session.selectedGsapAnimations; - const kfAnim = anims.find((a) => a.keyframes); - - let state: "active" | "inactive" | "none" = "none"; - // Outside the tween, clicking extends the animation to the playhead rather than - // toggling a (clamped) edge keyframe — so the button stays an "add" affordance. - let willExtend = false; - if (kfAnim?.keyframes && sel) { - if (!isPlayheadWithinTween(kfAnim, currentTime)) { - state = "inactive"; - willExtend = true; - } else { - // Tween-relative percentage (not the clip range) so the button state matches - // where the keyframe would actually land. - const pct = computeElementPercentage(currentTime, sel, kfAnim); - state = kfAnim.keyframes.keyframes.some((k) => Math.abs(k.percentage - pct) <= 1) - ? "active" - : "inactive"; - } - } + const toggleState = resolveKeyframeToggleState(session, currentTime); - return { state, willExtend, onToggle: sel ? onToggle : undefined }; + return { + ...toggleState, + onToggle: session?.domEditSelection && !toggleState.pathEndpoint ? onToggle : undefined, + }; } // fallow-ignore-next-line complexity @@ -91,6 +126,8 @@ export function TimelineToolbar({ domEditSession, onSplitElement }: TimelineTool const displayedTimelineZoomPercent = getTimelineZoomPercent(zoomMode, manualZoomPercent); const { state: keyframeState, + isMotionPath: keyframeIsMotionPath, + pathEndpoint: keyframePathEndpoint, willExtend: keyframeWillExtend, onToggle: onToggleKeyframe, } = useKeyframeToggle(domEditSession); @@ -180,15 +217,23 @@ export function TimelineToolbar({ domEditSession, onSplitElement }: TimelineTool // toolbar layout never shifts. + ))} + + + ) : ( + + )} + + ); +} diff --git a/packages/studio/src/components/editor/GsapAnimationSection.tsx b/packages/studio/src/components/editor/GsapAnimationSection.tsx index 33f6201b2f..1fac3972e9 100644 --- a/packages/studio/src/components/editor/GsapAnimationSection.tsx +++ b/packages/studio/src/components/editor/GsapAnimationSection.tsx @@ -2,13 +2,14 @@ import { memo, useState } from "react"; import type { GsapAnimation } from "@hyperframes/core/gsap-parser"; import { Film } from "../../icons/SystemIcons"; import { Section } from "./propertyPanelPrimitives"; -import { ADD_METHODS, ADD_METHOD_LABELS, METHOD_TOOLTIPS } from "./gsapAnimationConstants"; import { AnimationCard } from "./AnimationCard"; import { - trackAnimationMetaUpdate, type GsapAnimationEditCallbacks, + withTrackedGsapAnimationCallbacks, } from "./gsapAnimationCallbacks"; import { useTrackDesignInput } from "../../contexts/DesignPanelInputContext"; +import { usePlayerStore } from "../../player"; +import { GsapAddAnimationControl } from "./GsapAddAnimationControl"; interface GsapAnimationSectionProps extends GsapAnimationEditCallbacks { animations: GsapAnimation[]; @@ -21,41 +22,14 @@ export const GsapAnimationSection = memo(function GsapAnimationSection({ animations, multipleTimelines, unsupportedTimelinePattern, - onUpdateProperty, - onUpdateMeta, - onDeleteAnimation, - onAddProperty, - onRemoveProperty, - onUpdateFromProperty, - onAddFromProperty, - onRemoveFromProperty, onAddAnimation, - onLivePreview, - onLivePreviewEnd, - onSetArcPath, - onUpdateArcSegment, - onUpdateKeyframeEase, - onSetAllKeyframeEases, - onUnroll, + ...callbacks }: GsapAnimationSectionProps) { const track = useTrackDesignInput(); const [addMenuOpen, setAddMenuOpen] = useState(false); - const trackProperty = (property: string) => { - const control = - property === "visibility" - ? "toggle" - : property === "filter" || property === "clipPath" - ? "text" - : "metric"; - track(control, property); - }; - const updateMeta = ( - animationId: string, - updates: { duration?: number; ease?: string; position?: number }, - ) => { - trackAnimationMetaUpdate(track, updates); - onUpdateMeta(animationId, updates); - }; + const trackedCallbacks = withTrackedGsapAnimationCallbacks(callbacks, track); + const focusedEaseSegment = usePlayerStore((s) => s.focusedEaseSegment); + const setFocusedEaseSegment = usePlayerStore((s) => s.setFocusedEaseSegment); return (
}> @@ -76,137 +50,24 @@ export const GsapAnimationSection = memo(function GsapAnimationSection({
{animations.map((anim, index) => ( { - trackProperty(property); - onUpdateProperty(animationId, property, value); - }} - onUpdateMeta={updateMeta} - onDeleteAnimation={(animationId) => { - track("button", "Remove animation"); - onDeleteAnimation(animationId); - }} - onAddProperty={(animationId, property) => { - track("select", "Add effect property"); - onAddProperty(animationId, property); - }} - onRemoveProperty={(animationId, property) => { - track("button", `Remove ${property}`); - onRemoveProperty(animationId, property); - }} - onUpdateFromProperty={ - onUpdateFromProperty - ? (animationId, property, value) => { - trackProperty(property); - onUpdateFromProperty(animationId, property, value); - } - : undefined - } - onAddFromProperty={ - onAddFromProperty - ? (animationId, property) => { - track("select", "Add from property"); - onAddFromProperty(animationId, property); - } - : undefined - } - onRemoveFromProperty={ - onRemoveFromProperty - ? (animationId, property) => { - track("button", `Remove from ${property}`); - onRemoveFromProperty(animationId, property); - } - : undefined - } - onLivePreview={onLivePreview} - onLivePreviewEnd={onLivePreviewEnd} - onSetArcPath={ - onSetArcPath - ? (animationId, config) => { - track( - "toggle", - config.autoRotate !== undefined ? "Auto rotate" : "Arc motion", - ); - onSetArcPath(animationId, config); - } - : undefined - } - onUpdateArcSegment={ - onUpdateArcSegment - ? (animationId, segmentIndex, update) => { - if (update.curviness === undefined) { - track("button", `Reset arc segment ${segmentIndex + 1}`); - } - onUpdateArcSegment(animationId, segmentIndex, update); - } - : undefined - } - onUpdateKeyframeEase={ - onUpdateKeyframeEase - ? (animationId, percentage, ease) => { - track("select", "Keyframe ease"); - onUpdateKeyframeEase(animationId, percentage, ease); - } - : undefined - } - onSetAllKeyframeEases={ - onSetAllKeyframeEases - ? (animationId, ease) => { - track("select", "All keyframe eases"); - onSetAllKeyframeEases(animationId, ease); - } - : undefined - } - onUnroll={ - onUnroll - ? (animationId) => { - track("button", "Unroll animation"); - onUnroll(animationId); - } - : undefined + focusedSegment={ + focusedEaseSegment?.animationId === anim.id ? focusedEaseSegment : null } + onFocusSegmentConsumed={() => setFocusedEaseSegment(null)} /> ))} -
- {addMenuOpen ? ( -
- {ADD_METHODS.map((method) => ( - - ))} - -
- ) : ( - - )} -
+
)}
diff --git a/packages/studio/src/components/editor/KeyframeNavigation.tsx b/packages/studio/src/components/editor/KeyframeNavigation.tsx index c54047c305..b8016f1a6b 100644 --- a/packages/studio/src/components/editor/KeyframeNavigation.tsx +++ b/packages/studio/src/components/editor/KeyframeNavigation.tsx @@ -22,6 +22,36 @@ interface KeyframeNavigationProps { const TOLERANCE = 0.5; +interface NavigableKeyframe { + percentage: number; + tweenPercentage?: number; + properties: Record; +} + +export function getKeyframeNavigationState( + keyframes: readonly Keyframe[], + currentPercentage: number, + property?: string, +) { + const propertyKeyframes = property + ? keyframes.filter((keyframe) => property in keyframe.properties) + : keyframes; + return { + propertyKeyframes, + prevKeyframe: + propertyKeyframes + .filter((keyframe) => keyframe.percentage < currentPercentage - TOLERANCE) + .at(-1) ?? null, + nextKeyframe: + propertyKeyframes.find((keyframe) => keyframe.percentage > currentPercentage + TOLERANCE) ?? + null, + currentKeyframe: + propertyKeyframes.find( + (keyframe) => Math.abs(keyframe.percentage - currentPercentage) <= TOLERANCE, + ) ?? null, + }; +} + /** * Convert a clip-relative percentage (element lifetime, used for display/seek) to * the TWEEN-relative percentage the GSAP writer/runtime key on. The clip→tween @@ -92,18 +122,12 @@ export const KeyframeNavigation = memo(function KeyframeNavigation({ onRemoveKeyframe, onConvertToKeyframes, }: KeyframeNavigationProps) { - // Find keyframes that contain this property - const propertyKeyframes = keyframes?.filter((kf) => property in kf.properties) ?? []; - - const prevKf = - propertyKeyframes.filter((kf) => kf.percentage < currentPercentage - TOLERANCE).at(-1) ?? null; - - const nextKf = - propertyKeyframes.find((kf) => kf.percentage > currentPercentage + TOLERANCE) ?? null; - - const atCurrent = - propertyKeyframes.find((kf) => Math.abs(kf.percentage - currentPercentage) <= TOLERANCE) ?? - null; + const { + propertyKeyframes, + prevKeyframe: prevKf, + nextKeyframe: nextKf, + currentKeyframe: atCurrent, + } = getKeyframeNavigationState(keyframes ?? [], currentPercentage, property); // Diamond state let diamondState: DiamondState; diff --git a/packages/studio/src/components/editor/MotionPathOverlay.tsx b/packages/studio/src/components/editor/MotionPathOverlay.tsx index 1ed95b0ced..81a10a8d1b 100644 --- a/packages/studio/src/components/editor/MotionPathOverlay.tsx +++ b/packages/studio/src/components/editor/MotionPathOverlay.tsx @@ -88,6 +88,13 @@ export const MotionPathOverlay = memo(function MotionPathOverlay({ // The keyframe % selected by clicking its node — highlighted, and the next drag // modifies it rather than adding a keyframe. const activeKeyframePct = usePlayerStore((s) => s.activeKeyframePct); + const timelineElement = usePlayerStore((state) => { + if (!selection) return undefined; + const sourceScopedId = `${selection.sourceFile || "index.html"}#${selection.id}`; + return state.elements.find( + (element) => (element.key ?? element.id) === sourceScopedId || element.id === selection.id, + ); + }); // Set-destination mode is armed from the preview toolbar (replaces the old // double-click-on-canvas UX). See createMode effects below. const armed = usePlayerStore((s) => s.motionPathArmed); @@ -418,12 +425,13 @@ export const MotionPathOverlay = memo(function MotionPathOverlay({ // Right-click a keyframe node → the timeline's keyframe context menu (delete // this keyframe / delete all), so motion-path keyframes are removable in place. const onNodeContextMenu = (e: React.MouseEvent, ref: MotionNodeRef) => { - if (ref.type !== "keyframe" || !animId || !elementId) return; + if (ref.type !== "keyframe" || !animId || !elementId || !timelineElement) return; e.preventDefault(); e.stopPropagation(); setKfMenu({ x: e.clientX, y: e.clientY, + element: timelineElement, elementId, percentage: ref.pct, tweenPercentage: ref.pct, diff --git a/packages/studio/src/components/editor/PropertyPanelFlat.tsx b/packages/studio/src/components/editor/PropertyPanelFlat.tsx index ef1393a60d..86900c1261 100644 --- a/packages/studio/src/components/editor/PropertyPanelFlat.tsx +++ b/packages/studio/src/components/editor/PropertyPanelFlat.tsx @@ -19,6 +19,7 @@ import { createGsapLivePreview } from "./gsapLivePreview"; import { formatTextFieldPreview } from "./propertyPanelSections"; import { STUDIO_GSAP_PANEL_ENABLED } from "./manualEditingAvailability"; import { useColorGradingController } from "./useColorGradingController"; +import { usePlayerStore } from "../../player"; import { FlatColorGradingAccessory, FlatColorGradingSection, @@ -231,7 +232,36 @@ export function PropertyPanelFlat({ : "layout", ); - // Animate only the groups that changed during this toggle cycle. + // Tracks which group(s) are actively transitioning this toggle cycle, so + // their header/body gets the fast entrance animation (hf-flat-group-enter) + // and no one else's does. Deliberately NOT derived from remounting alone: + // FlatGroupHeader instances are keyed by group id and React normally + // preserves them across re-renders, but toggling a non-adjacent group still + // shifts the untouched collapsed siblings between the before/after-open + // slices below, and Chromium restarts a CSS animation on that kind of + // position shift even though nothing about the sibling actually changed. + // Gating on these ids (cleared shortly after the 120ms CSS animation + // finishes) keeps the animation scoped to only the groups that actually + // just toggled. Two ids, not one: the clicked (newly-opening/closing) group + // AND whichever group was open immediately before the click and got + // implicitly closed by it — both freshly-mounted headers need to animate. + // When the inline timeline ease button focuses a segment on this element, + // force the Motion group open so its AnimationCard (which only mounts while + // the group is expanded) can consume the focus and reveal the ease editor. + const focusedEaseSegment = usePlayerStore((s) => s.focusedEaseSegment); + // Identity of the element THIS panel actually renders (not the store's + // selectedElementId, which flips synchronously on selection while the panel + // still renders the previous element during async DOM-selection resolution): + // a stale panel would otherwise consume a focus request meant for its + // successor when both share a class-selector animation id. + const renderedElementId = `${element.sourceFile}#${element.id}`; + useEffect(() => { + if (!focusedEaseSegment || focusedEaseSegment.elementId !== renderedElementId) return; + if (gsapAnimations.some((a) => a.id === focusedEaseSegment.animationId)) { + setOpenGroupId("motion"); + } + }, [focusedEaseSegment, gsapAnimations, renderedElementId]); + const [justToggledIds, setJustToggledIds] = useState([]); const justToggledTimeoutRef = useRef | null>(null); const panelBodyRef = useRef(null); @@ -492,6 +522,17 @@ export function PropertyPanelFlat({ const beforeOpen = openIndex === -1 ? groups : groups.slice(0, openIndex); const openGroup = openIndex === -1 ? null : groups[openIndex]; const afterOpen = openIndex === -1 ? [] : groups.slice(openIndex + 1); + const renderClosedGroup = (group: FlatGroupDescriptor) => ( + + toggleOpen(group.id)} + summary={group.summary} + animateEntrance={justToggledIds.includes(group.id)} + /> + + ); return ( @@ -519,17 +560,7 @@ export function PropertyPanelFlat({ data-flat-panel-body="true" className="flex min-h-0 flex-1 flex-col overflow-y-auto" > - {beforeOpen.map((g) => ( - - toggleOpen(g.id)} - summary={g.summary} - animateEntrance={justToggledIds.includes(g.id)} - /> - - ))} + {beforeOpen.map(renderClosedGroup)} {openGroup && (
@@ -548,17 +579,7 @@ export function PropertyPanelFlat({
)} - {afterOpen.map((g) => ( - - toggleOpen(g.id)} - summary={g.summary} - animateEntrance={justToggledIds.includes(g.id)} - /> - - ))} + {afterOpen.map(renderClosedGroup)} (callback: T | undefined): T { + if (callback === undefined) throw new Error("expected callback to be present"); + return callback; +} + +describe("withTrackedGsapAnimationCallbacks", () => { + it("keeps absent optional callbacks absent and passes preview callbacks through unchanged", () => { + const callbacks = requiredCallbacks(); + const onLivePreview = vi.fn(); + const onLivePreviewEnd = vi.fn(); + callbacks.onLivePreview = onLivePreview; + callbacks.onLivePreviewEnd = onLivePreviewEnd; + + const tracked = withTrackedGsapAnimationCallbacks(callbacks, vi.fn()); + + expect(tracked.onUpdateFromProperty).toBeUndefined(); + expect(tracked.onAddFromProperty).toBeUndefined(); + expect(tracked.onRemoveFromProperty).toBeUndefined(); + expect(tracked.onSetArcPath).toBeUndefined(); + expect(tracked.onUpdateArcSegment).toBeUndefined(); + expect(tracked.onUpdateKeyframeEase).toBeUndefined(); + expect(tracked.onSetAllKeyframeEases).toBeUndefined(); + expect(tracked.onUnroll).toBeUndefined(); + expect(tracked.onLivePreview).toBe(onLivePreview); + expect(tracked.onLivePreviewEnd).toBe(onLivePreviewEnd); + }); + + it("tracks each edit once before invoking its mutation callback", () => { + const events: string[] = []; + const mutation = (name: string) => () => events.push(`mutate:${name}`); + const callbacks: GsapAnimationEditCallbacks = { + onUpdateProperty: mutation("update-property"), + onUpdateMeta: mutation("update-meta"), + onDeleteAnimation: mutation("delete"), + onAddProperty: mutation("add-property"), + onRemoveProperty: mutation("remove-property"), + onUpdateFromProperty: mutation("update-from"), + onAddFromProperty: mutation("add-from"), + onRemoveFromProperty: mutation("remove-from"), + onSetArcPath: mutation("arc-path"), + onUpdateArcSegment: mutation("arc-segment"), + onUpdateKeyframeEase: mutation("keyframe-ease"), + onSetAllKeyframeEases: mutation("all-eases"), + onUnroll: mutation("unroll"), + }; + const tracked = withTrackedGsapAnimationCallbacks(callbacks, (control, name) => { + events.push(`track:${control}:${name}`); + }); + + tracked.onUpdateProperty("a1", "visibility", 1); + tracked.onUpdateProperty("a1", "filter", "blur(2px)"); + tracked.onUpdateProperty("a1", "opacity", 0.5); + tracked.onUpdateMeta("a1", { duration: 2, ease: "none", position: 1 }); + tracked.onDeleteAnimation("a1"); + tracked.onAddProperty("a1", "scale"); + tracked.onRemoveProperty("a1", "scale"); + requireCallback(tracked.onUpdateFromProperty)("a1", "clipPath", "none"); + requireCallback(tracked.onAddFromProperty)("a1", "x"); + requireCallback(tracked.onRemoveFromProperty)("a1", "x"); + requireCallback(tracked.onSetArcPath)("a1", { enabled: true }); + requireCallback(tracked.onSetArcPath)("a1", { enabled: true, autoRotate: true }); + requireCallback(tracked.onUpdateArcSegment)("a1", 1, {}); + requireCallback(tracked.onUpdateArcSegment)("a1", 1, { curviness: 0.5 }); + requireCallback(tracked.onUpdateKeyframeEase)("a1", 50, "power2.out"); + requireCallback(tracked.onSetAllKeyframeEases)("a1", "none"); + requireCallback(tracked.onUnroll)("a1"); + + expect(events).toEqual([ + "track:toggle:visibility", + "mutate:update-property", + "track:text:filter", + "mutate:update-property", + "track:metric:opacity", + "mutate:update-property", + "track:metric:Length", + "track:select:Speed", + "track:metric:Starts at", + "mutate:update-meta", + "track:button:Remove animation", + "mutate:delete", + "track:select:Add effect property", + "mutate:add-property", + "track:button:Remove scale", + "mutate:remove-property", + "track:text:clipPath", + "mutate:update-from", + "track:select:Add from property", + "mutate:add-from", + "track:button:Remove from x", + "mutate:remove-from", + "track:toggle:Arc motion", + "mutate:arc-path", + "track:toggle:Auto rotate", + "mutate:arc-path", + "track:button:Reset arc segment 2", + "mutate:arc-segment", + "mutate:arc-segment", + "track:select:Keyframe ease", + "mutate:keyframe-ease", + "track:select:All keyframe eases", + "mutate:all-eases", + "track:button:Unroll animation", + "mutate:unroll", + ]); + }); +}); diff --git a/packages/studio/src/components/editor/gsapAnimationCallbacks.ts b/packages/studio/src/components/editor/gsapAnimationCallbacks.ts index c07d9c83b4..d35cf4479d 100644 --- a/packages/studio/src/components/editor/gsapAnimationCallbacks.ts +++ b/packages/studio/src/components/editor/gsapAnimationCallbacks.ts @@ -35,6 +35,18 @@ export interface GsapAnimationEditCallbacks { onUnroll?: (animationId: string) => void; } +type TrackDesignInput = (control: string, name: string) => void; + +function trackAnimationProperty(track: TrackDesignInput, property: string): void { + const control = + property === "visibility" + ? "toggle" + : property === "filter" || property === "clipPath" + ? "text" + : "metric"; + track(control, property); +} + // User-facing control label for each animation-meta field. The ease control is // labelled "Speed" in the card UI, so ease/easeEach map there. const ANIMATION_META_LABELS: Record = { @@ -51,13 +63,95 @@ const ANIMATION_META_LABELS: Record = * added later is attributed honestly by its own key instead of poisoning another * control's usage count. */ -export function trackAnimationMetaUpdate( - track: (control: string, name: string) => void, - updates: Record, -): void { +function trackAnimationMetaUpdate(track: TrackDesignInput, updates: Record): void { for (const key of Object.keys(updates)) { const mapped = ANIMATION_META_LABELS[key]; if (mapped) track(mapped.control, mapped.name); else track("select", key); } } + +/** + * Add design-input telemetry to the shared animation-edit callback surface. + * Optional callbacks remain absent, pass-through preview callbacks keep their + * original identity, and every tracked event fires once before its mutation. + */ +export function withTrackedGsapAnimationCallbacks( + callbacks: GsapAnimationEditCallbacks, + track: TrackDesignInput, +): GsapAnimationEditCallbacks { + return { + onUpdateProperty: (animationId, property, value) => { + trackAnimationProperty(track, property); + callbacks.onUpdateProperty(animationId, property, value); + }, + onUpdateMeta: (animationId, updates) => { + trackAnimationMetaUpdate(track, updates); + callbacks.onUpdateMeta(animationId, updates); + }, + onDeleteAnimation: (animationId) => { + track("button", "Remove animation"); + callbacks.onDeleteAnimation(animationId); + }, + onAddProperty: (animationId, property) => { + track("select", "Add effect property"); + callbacks.onAddProperty(animationId, property); + }, + onRemoveProperty: (animationId, property) => { + track("button", `Remove ${property}`); + callbacks.onRemoveProperty(animationId, property); + }, + onUpdateFromProperty: callbacks.onUpdateFromProperty + ? (animationId, property, value) => { + trackAnimationProperty(track, property); + callbacks.onUpdateFromProperty?.(animationId, property, value); + } + : undefined, + onAddFromProperty: callbacks.onAddFromProperty + ? (animationId, property) => { + track("select", "Add from property"); + callbacks.onAddFromProperty?.(animationId, property); + } + : undefined, + onRemoveFromProperty: callbacks.onRemoveFromProperty + ? (animationId, property) => { + track("button", `Remove from ${property}`); + callbacks.onRemoveFromProperty?.(animationId, property); + } + : undefined, + onLivePreview: callbacks.onLivePreview, + onLivePreviewEnd: callbacks.onLivePreviewEnd, + onSetArcPath: callbacks.onSetArcPath + ? (animationId, config) => { + track("toggle", config.autoRotate !== undefined ? "Auto rotate" : "Arc motion"); + callbacks.onSetArcPath?.(animationId, config); + } + : undefined, + onUpdateArcSegment: callbacks.onUpdateArcSegment + ? (animationId, segmentIndex, update) => { + if (update.curviness === undefined) { + track("button", `Reset arc segment ${segmentIndex + 1}`); + } + callbacks.onUpdateArcSegment?.(animationId, segmentIndex, update); + } + : undefined, + onUpdateKeyframeEase: callbacks.onUpdateKeyframeEase + ? (animationId, percentage, ease) => { + track("select", "Keyframe ease"); + callbacks.onUpdateKeyframeEase?.(animationId, percentage, ease); + } + : undefined, + onSetAllKeyframeEases: callbacks.onSetAllKeyframeEases + ? (animationId, ease) => { + track("select", "All keyframe eases"); + callbacks.onSetAllKeyframeEases?.(animationId, ease); + } + : undefined, + onUnroll: callbacks.onUnroll + ? (animationId) => { + track("button", "Unroll animation"); + callbacks.onUnroll?.(animationId); + } + : undefined, + }; +} diff --git a/packages/studio/src/components/editor/keyframeRetime.test.ts b/packages/studio/src/components/editor/keyframeRetime.test.ts index 876c5129a5..db8ff21179 100644 --- a/packages/studio/src/components/editor/keyframeRetime.test.ts +++ b/packages/studio/src/components/editor/keyframeRetime.test.ts @@ -11,6 +11,22 @@ const KEYFRAMES: RetimeKeyframe[] = [ const WINDOW = { tweenStart: 2, tweenDuration: 4 }; const LEFT_BOUNDARY_DROP = { ...WINDOW, dropAbsTime: 0.5 }; +function expectLeftResize( + keyframes: RetimeKeyframe[], + draggedTweenPct: number, + pctRemap: Array<{ from: number; to: number }>, +): void { + const result = resolveKeyframeRetime({ + ...LEFT_BOUNDARY_DROP, + keyframes, + draggedTweenPct, + }); + expect(result.kind).toBe("resize"); + expect(result.position).toBeCloseTo(0.5, 5); + expect(result.duration).toBeCloseTo(5.5, 5); + expect(result.pctRemap).toEqual(pctRemap); +} + describe("resolveKeyframeRetime — move (within the tween window)", () => { it("re-keys an interior keyframe to the tween-% of the drop", () => { const r = resolveKeyframeRetime({ @@ -94,29 +110,21 @@ describe("resolveKeyframeRetime — resize (past the tween boundary)", () => { expect(r.kind).toBe("resize"); expect(r.position).toBeCloseTo(2, 5); // start unchanged expect(r.duration).toBeCloseTo(6, 5); // 8 - 2 - // abs 2/4/8 over the new [2,8] window → 0 / 33.3 / 100. pctRemap carries each + // abs 2/4/8 over the new [2,8] window → 0 / 33.333 / 100. pctRemap carries each // existing keyframe's old→new tween-%; the commit re-keys in place (value + // ease + _auto preserved by round-tripping the source node, not re-emitted here). expect(r.pctRemap).toEqual([ { from: 0, to: 0 }, - { from: 50, to: 33.3 }, + { from: 50, to: 33.333 }, { from: 100, to: 100 }, ]); }); it("extends the FIRST keyframe before the start, shifting position earlier", () => { - const r = resolveKeyframeRetime({ - ...LEFT_BOUNDARY_DROP, - keyframes: KEYFRAMES, - draggedTweenPct: 0, - }); - expect(r.kind).toBe("resize"); - expect(r.position).toBeCloseTo(0.5, 5); - expect(r.duration).toBeCloseTo(5.5, 5); // 6 - 0.5 - // abs 0.5/4/6 over [0.5,6] → 0 / 63.6 / 100. - expect(r.pctRemap).toEqual([ + // abs 0.5/4/6 over [0.5,6] → 0 / 63.636 / 100. + expectLeftResize(KEYFRAMES, 0, [ { from: 0, to: 0 }, - { from: 50, to: 63.6 }, + { from: 50, to: 63.636 }, { from: 100, to: 100 }, ]); }); @@ -139,15 +147,7 @@ describe("resolveKeyframeRetime — single keyframe (both first and last)", () = }); it("resizes left before the start", () => { - const r = resolveKeyframeRetime({ - ...LEFT_BOUNDARY_DROP, - keyframes: lone, - draggedTweenPct: 100, - }); - expect(r.kind).toBe("resize"); - expect(r.position).toBeCloseTo(0.5, 5); - expect(r.duration).toBeCloseTo(5.5, 5); - expect(r.pctRemap).toEqual([{ from: 100, to: 0 }]); + expectLeftResize(lone, 100, [{ from: 100, to: 0 }]); }); }); diff --git a/packages/studio/src/components/editor/keyframeRetime.ts b/packages/studio/src/components/editor/keyframeRetime.ts index f235b418ed..f7fa1d1344 100644 --- a/packages/studio/src/components/editor/keyframeRetime.ts +++ b/packages/studio/src/components/editor/keyframeRetime.ts @@ -55,7 +55,6 @@ const EPSILON_TIME = 1e-4; const MIN_TWEEN_DURATION = 0.01; const round3 = (n: number) => Math.round(n * 1000) / 1000; -const round1 = (n: number) => Math.round(n * 10) / 10; // 0.1% precision const clamp = (n: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, n)); /** Resolve timing for a flat tween's synthesized start/end diamond. */ @@ -153,7 +152,7 @@ export function resolveKeyframeRetime(opts: { const pctRemap: KeyframePctRemap[] = keyframes.map((kf, i) => { const absTime = i === draggedIdx ? dropAbsTime : tweenStart + (kf.percentage / 100) * tweenDuration; - return { from: kf.percentage, to: round1(((absTime - newStart) / newDuration) * 100) }; + return { from: kf.percentage, to: round3(((absTime - newStart) / newDuration) * 100) }; }); return { diff --git a/packages/studio/src/components/editor/propertyPanelFlatMotionSection.tsx b/packages/studio/src/components/editor/propertyPanelFlatMotionSection.tsx index 7458ad508a..c8edf195b5 100644 --- a/packages/studio/src/components/editor/propertyPanelFlatMotionSection.tsx +++ b/packages/studio/src/components/editor/propertyPanelFlatMotionSection.tsx @@ -6,12 +6,13 @@ import { formatTimingValue, RESPONSIVE_GRID } from "./propertyPanelHelpers"; import { parseTimingValue } from "./propertyPanelTimingSection"; import { CommitField } from "./propertyPanelPrimitives"; import { AnimationCard } from "./AnimationCard"; -import { ADD_METHODS, ADD_METHOD_LABELS, METHOD_TOOLTIPS } from "./gsapAnimationConstants"; import { - trackAnimationMetaUpdate, type GsapAnimationEditCallbacks, + withTrackedGsapAnimationCallbacks, } from "./gsapAnimationCallbacks"; import { deriveElementTiming } from "./propertyPanelFlatTimingDerivation"; +import { usePlayerStore } from "../../player"; +import { GsapAddAnimationControl } from "./GsapAddAnimationControl"; export function FlatTimingRow({ element, @@ -135,15 +136,18 @@ export function FlatMotionSection({ } & GsapAnimationEditCallbacks) { const track = useTrackDesignInput(); const [addMenuOpen, setAddMenuOpen] = useState(false); - const trackProperty = (property: string) => { - const control = - property === "visibility" - ? "toggle" - : property === "filter" || property === "clipPath" - ? "text" - : "metric"; - track(control, property); - }; + const trackedCallbacks = withTrackedGsapAnimationCallbacks(callbacks, track); + const focusedEaseSegment = usePlayerStore((s) => s.focusedEaseSegment); + const setFocusedEaseSegment = usePlayerStore((s) => s.setFocusedEaseSegment); + // Only consume a focus request aimed at the element THIS panel renders (not + // the store's selectedElementId, which flips synchronously during async + // selection resolution), so a shared class-selector animation id can't open + // the wrong element's editor. + const renderedElementId = `${element.sourceFile}#${element.id}`; + const focusedHere = + focusedEaseSegment && focusedEaseSegment.elementId === renderedElementId + ? focusedEaseSegment + : null; return (
@@ -172,140 +176,22 @@ export function FlatMotionSection({
{animations.map((anim, index) => ( { - trackProperty(property); - callbacks.onUpdateProperty(animationId, property, value); - }} - onUpdateMeta={(animationId, updates) => { - trackAnimationMetaUpdate(track, updates); - callbacks.onUpdateMeta(animationId, updates); - }} - onDeleteAnimation={(animationId) => { - track("button", "Remove animation"); - callbacks.onDeleteAnimation(animationId); - }} - onAddProperty={(animationId, property) => { - track("select", "Add effect property"); - callbacks.onAddProperty(animationId, property); - }} - onRemoveProperty={(animationId, property) => { - track("button", `Remove ${property}`); - callbacks.onRemoveProperty(animationId, property); - }} - onUpdateFromProperty={ - callbacks.onUpdateFromProperty - ? (animationId, property, value) => { - trackProperty(property); - callbacks.onUpdateFromProperty?.(animationId, property, value); - } - : undefined - } - onAddFromProperty={ - callbacks.onAddFromProperty - ? (animationId, property) => { - track("select", "Add from property"); - callbacks.onAddFromProperty?.(animationId, property); - } - : undefined - } - onRemoveFromProperty={ - callbacks.onRemoveFromProperty - ? (animationId, property) => { - track("button", `Remove from ${property}`); - callbacks.onRemoveFromProperty?.(animationId, property); - } - : undefined - } - onLivePreview={callbacks.onLivePreview} - onLivePreviewEnd={callbacks.onLivePreviewEnd} - onSetArcPath={ - callbacks.onSetArcPath - ? (animationId, config) => { - track( - "toggle", - config.autoRotate !== undefined ? "Auto rotate" : "Arc motion", - ); - callbacks.onSetArcPath?.(animationId, config); - } - : undefined - } - onUpdateArcSegment={ - callbacks.onUpdateArcSegment - ? (animationId, segmentIndex, update) => { - if (update.curviness === undefined) { - track("button", `Reset arc segment ${segmentIndex + 1}`); - } - callbacks.onUpdateArcSegment?.(animationId, segmentIndex, update); - } - : undefined - } - onUpdateKeyframeEase={ - callbacks.onUpdateKeyframeEase - ? (animationId, percentage, ease) => { - track("select", "Keyframe ease"); - callbacks.onUpdateKeyframeEase?.(animationId, percentage, ease); - } - : undefined - } - onSetAllKeyframeEases={ - callbacks.onSetAllKeyframeEases - ? (animationId, ease) => { - track("select", "All keyframe eases"); - callbacks.onSetAllKeyframeEases?.(animationId, ease); - } - : undefined - } - onUnroll={ - callbacks.onUnroll - ? (animationId) => { - track("button", "Unroll animation"); - callbacks.onUnroll?.(animationId); - } - : undefined - } + focusedSegment={focusedHere?.animationId === anim.id ? focusedHere : null} + onFocusSegmentConsumed={() => setFocusedEaseSegment(null)} /> ))} -
- {addMenuOpen ? ( -
- {ADD_METHODS.map((method) => ( - - ))} - -
- ) : ( - - )} -
+
)} diff --git a/packages/studio/src/components/editor/propertyPanelFlatTextSection.test.tsx b/packages/studio/src/components/editor/propertyPanelFlatTextSection.test.tsx index 56a7714d7c..4dbe02cc0f 100644 --- a/packages/studio/src/components/editor/propertyPanelFlatTextSection.test.tsx +++ b/packages/studio/src/components/editor/propertyPanelFlatTextSection.test.tsx @@ -299,22 +299,17 @@ describe("FlatTextFieldEditor controls", () => { describe("FlatTextSection — multi-field", () => { it("shows the layer list, switches the active field's rows on selection, and has no doubled heading (this component never renders its own heading — the parent FlatGroup does)", () => { - const host = document.createElement("div"); - document.body.append(host); - const root = createRoot(host); - act(() => { - root.render( - , - ); - }); + const { host, root } = renderInto( + , + ); expect(host.textContent).toContain("Headline"); expect(host.textContent).toContain("Subhead"); // Active field's editor rows are visible (Font/Weight/etc. from FlatTextFieldEditor). @@ -408,6 +403,27 @@ describe("FlatTextSection — multi-field", () => { act(() => root.unmount()); }); + it("does not steal canvas focus when a multi-field element is selected", () => { + const focusOwner = document.createElement("button"); + document.body.append(focusOwner); + focusOwner.focus(); + + const { root } = renderInto( + , + ); + + expect(document.activeElement).toBe(focusOwner); + act(() => root.unmount()); + }); + it("auto-focuses the Content textarea when a new text field is added", async () => { let addResolved = false; diff --git a/packages/studio/src/components/editor/propertyPanelFlatTextSection.tsx b/packages/studio/src/components/editor/propertyPanelFlatTextSection.tsx index ebabf758d3..636955de60 100644 --- a/packages/studio/src/components/editor/propertyPanelFlatTextSection.tsx +++ b/packages/studio/src/components/editor/propertyPanelFlatTextSection.tsx @@ -257,6 +257,7 @@ export function FlatTextSection({ const [activeFieldKey, setActiveFieldKey] = useState( element.textFields[0]?.key ?? null, ); + const [autoFocusFieldKey, setAutoFocusFieldKey] = useState(null); useEffect(() => { const nextFields = element.textFields; @@ -266,6 +267,16 @@ export function FlatTextSection({ }); }, [element.id, element.selector, element.textFields]); + useEffect(() => { + setAutoFocusFieldKey(null); + }, [element.id, element.selector]); + + useEffect(() => { + if (autoFocusFieldKey && autoFocusFieldKey === activeFieldKey) { + setAutoFocusFieldKey(null); + } + }, [activeFieldKey, autoFocusFieldKey]); + if (!isTextEditableSelection(element)) return null; const textFields = element.textFields; const activeField = textFields.find((field) => field.key === activeFieldKey) ?? textFields[0]; @@ -278,10 +289,15 @@ export function FlatTextSection({ fields={textFields} activeFieldKey={activeField.key} styles={styles} - onSelect={setActiveFieldKey} + onSelect={(fieldKey) => { + setAutoFocusFieldKey(null); + setActiveFieldKey(fieldKey); + }} onAdd={() => void Promise.resolve(onAddTextField(activeField.key)).then((nextKey) => { - if (nextKey) setActiveFieldKey(nextKey); + if (!nextKey) return; + setAutoFocusFieldKey(nextKey); + setActiveFieldKey(nextKey); }) } onRemove={onRemoveTextField} @@ -295,7 +311,7 @@ export function FlatTextSection({ onSetText={onSetText} onSetTextFieldStyle={onSetTextFieldStyle} onPreviewTextFieldStyle={onPreviewTextFieldStyle} - autoFocus + autoFocus={autoFocusFieldKey === activeField.key} />
); @@ -316,7 +332,11 @@ export function FlatTextSection({ type="button" onClick={() => { track("button", "Add text field"); - void onAddTextField(activeField.key); + void Promise.resolve(onAddTextField(activeField.key)).then((nextKey) => { + if (!nextKey) return; + setAutoFocusFieldKey(nextKey); + setActiveFieldKey(nextKey); + }); }} className="mt-0.5 flex items-center gap-[5px] text-[10px] text-panel-text-4 hover:text-panel-text-2" > diff --git a/packages/studio/src/components/nle/useTimelineEditCallbacks.test.ts b/packages/studio/src/components/nle/useTimelineEditCallbacks.test.ts index 662234daa0..361cfd615a 100644 --- a/packages/studio/src/components/nle/useTimelineEditCallbacks.test.ts +++ b/packages/studio/src/components/nle/useTimelineEditCallbacks.test.ts @@ -40,6 +40,36 @@ describe("resolveTimelineKeyframeTarget", () => { ).toBeNull(); }); + it("uses the rendered animation identity to resolve a same-group collision", () => { + expect( + resolveTimelineKeyframeTarget( + 50, + [ + { + percentage: 50, + tweenPercentage: 25, + propertyGroup: "position", + animationId: "position-b", + }, + ], + [ + { id: "position-a", propertyGroup: "position" }, + { id: "position-b", propertyGroup: "position" }, + ], + ), + ).toEqual({ animId: "position-b", tweenPct: 25 }); + }); + + it("rejects a rendered animation identity absent from the element", () => { + expect( + resolveTimelineKeyframeTarget( + 50, + [{ percentage: 50, animationId: "stale-position" }], + [{ id: "position", propertyGroup: "position" }], + ), + ).toBeNull(); + }); + it("keeps a keyframed and flat tween in the same property group unresolved", () => { expect( resolveTimelineKeyframeTarget( diff --git a/packages/studio/src/components/nle/useTimelineEditCallbacks.test.tsx b/packages/studio/src/components/nle/useTimelineEditCallbacks.test.tsx new file mode 100644 index 0000000000..5248aa0717 --- /dev/null +++ b/packages/studio/src/components/nle/useTimelineEditCallbacks.test.tsx @@ -0,0 +1,395 @@ +// @vitest-environment happy-dom + +import React, { act } from "react"; +import type { GsapAnimation } from "@hyperframes/core/gsap-parser"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { TimelineElement } from "../../player"; +import type { TimelineEditCallbacks } from "../../player/components/timelineCallbacks"; +import { usePlayerStore } from "../../player/store/playerStore"; +import { installReactActEnvironment, mountReactHarness } from "../../hooks/domSelectionTestHarness"; + +installReactActEnvironment(); + +const mocks = vi.hoisted(() => ({ + actions: { + handleGsapRemoveKeyframe: vi.fn(), + handleGsapMoveKeyframeToPlayhead: vi.fn(), + handleGsapMoveKeyframe: vi.fn().mockResolvedValue(true), + handleGsapResizeKeyframedTween: vi.fn().mockResolvedValue(true), + handleGsapUpdateMeta: vi.fn(), + handleGsapAddKeyframe: vi.fn(), + handleGsapAddKeyframeBatch: vi.fn().mockResolvedValue(undefined), + handleGsapConvertToKeyframes: vi.fn(), + handleGsapRemoveAllKeyframes: vi.fn(), + handleGsapDeleteAnimation: vi.fn(), + buildDomSelectionForTimelineElement: vi.fn(), + }, + selection: { id: "box", selector: "#box", sourceFile: "index.html" }, + animations: Array(), +})); + +vi.mock("../../contexts/StudioContext", () => ({ + useStudioShellContext: () => ({ projectId: "project", activeCompPath: "index.html" }), +})); + +vi.mock("../../contexts/DomEditContext", () => ({ + useDomEditActionsContext: () => mocks.actions, + useDomEditSelectionContext: () => ({ + domEditSelection: mocks.selection, + selectedGsapAnimations: mocks.animations, + }), +})); + +import { useTimelineEditCallbacks } from "./useTimelineEditCallbacks"; + +const element: TimelineElement = { + id: "box", + key: "index.html#box", + domId: "box", + tag: "div", + start: 0, + duration: 1, + track: 0, + sourceFile: "index.html", +}; + +const flatAnimation: GsapAnimation = { + id: "box-to-0-position", + targetSelector: "#box", + method: "to", + position: 0, + resolvedStart: 0, + duration: 1, + properties: { x: 420 }, + propertyGroup: "position", +}; + +const otherFlatAnimation: GsapAnimation = { + ...flatAnimation, + id: "circle-to-0-position", + targetSelector: "#circle", +}; + +const otherKeyframedAnimation: GsapAnimation = { + ...otherFlatAnimation, + keyframes: { + format: "percentage", + keyframes: [ + { percentage: 0, properties: { x: 0 } }, + { percentage: 100, properties: { x: 420 } }, + ], + }, +}; + +function authoredInteriorAnimation(): GsapAnimation { + return { + ...flatAnimation, + keyframes: { + format: "percentage", + keyframes: [ + { percentage: 0, properties: { x: 0 } }, + { percentage: 50, properties: { x: 210 } }, + { percentage: 100, properties: { x: 420 } }, + ], + }, + }; +} + +function renderCallbacks(): { callbacks: TimelineEditCallbacks; unmount: () => void } { + let callbacks: TimelineEditCallbacks | null = null; + function Harness() { + callbacks = useTimelineEditCallbacks({ + handleTimelineElementMove: vi.fn(), + handleTimelineElementsMove: vi.fn(), + handleTimelineElementResize: vi.fn(), + handleTimelineGroupResize: vi.fn(), + handleToggleTrackHidden: vi.fn(), + handleBlockedTimelineEdit: vi.fn(), + handleTimelineElementSplit: vi.fn(), + handleRazorSplit: vi.fn(), + handleRazorSplitAll: vi.fn(), + }); + return null; + } + const root = mountReactHarness(); + if (!callbacks) throw new Error("timeline callbacks did not initialize"); + return { callbacks, unmount: () => act(() => root.unmount()) }; +} + +function arrangeClickedCircle(): { + circle: TimelineElement; + selection: { id: string; selector: string; sourceFile: string }; +} { + const elementKey = "scenes/main.html#circle"; + const circle: TimelineElement = { + ...element, + id: "circle", + key: elementKey, + domId: "circle", + sourceFile: "scenes/main.html", + }; + const selection = { id: "circle", selector: "#circle", sourceFile: "scenes/main.html" }; + usePlayerStore.setState({ + elements: [element, circle], + gsapAnimations: new Map([[elementKey, [otherKeyframedAnimation]]]), + }); + mocks.actions.buildDomSelectionForTimelineElement.mockResolvedValue(selection); + return { circle, selection }; +} + +beforeEach(() => { + vi.clearAllMocks(); + mocks.animations = [flatAnimation]; + mocks.actions.buildDomSelectionForTimelineElement.mockResolvedValue(mocks.selection); + usePlayerStore.setState({ + currentTime: 0.5, + elements: [element], + domClipChildren: [], + keyframeCache: new Map(), + gsapAnimations: new Map([["box", [flatAnimation]]]), + }); +}); + +afterEach(() => { + usePlayerStore.setState({ + elements: [], + domClipChildren: [], + keyframeCache: new Map(), + gsapAnimations: new Map(), + }); +}); + +describe("useTimelineEditCallbacks — flat tween keyframe lanes", () => { + it("adds an interior point through the add-keyframe persist boundary", async () => { + const view = renderCallbacks(); + + await act(async () => { + await view.callbacks.onTogglePropertyGroupKeyframe?.(element, { + animationId: flatAnimation.id, + propertyGroup: "position", + tweenPercentage: 50, + properties: { x: 210 }, + remove: false, + }); + }); + + expect(mocks.actions.handleGsapAddKeyframeBatch).toHaveBeenCalledWith( + flatAnimation.id, + 50, + { x: 210 }, + undefined, + mocks.selection, + ); + expect(mocks.actions.handleGsapConvertToKeyframes).not.toHaveBeenCalled(); + view.unmount(); + }); + + it("settles false for a boundary drag while the tween is still flat", async () => { + const view = renderCallbacks(); + + await expect( + view.callbacks.onMoveKeyframe?.("box", 0, 25, "position", 0, flatAnimation.id), + ).resolves.toBe(false); + + expect(mocks.actions.handleGsapMoveKeyframe).not.toHaveBeenCalled(); + expect(mocks.actions.handleGsapResizeKeyframedTween).not.toHaveBeenCalled(); + view.unmount(); + }); + + it("deletes a non-selected element flat boundary through the clicked element's selection", async () => { + const circle: TimelineElement = { + ...element, + id: "circle", + key: "scenes/main.html#circle", + domId: "circle", + }; + usePlayerStore.setState({ + elements: [element, circle], + gsapAnimations: new Map([["scenes/main.html#circle", [otherFlatAnimation]]]), + }); + const view = renderCallbacks(); + + await act(async () => { + view.callbacks.onDeleteKeyframe?.( + "scenes/main.html#circle", + 0, + "position", + 0, + otherFlatAnimation.id, + ); + await Promise.resolve(); + await Promise.resolve(); + }); + + // Persisted through the CLICKED element's own selection, not the current one. + expect(mocks.actions.handleGsapDeleteAnimation).toHaveBeenCalledWith( + otherFlatAnimation.id, + mocks.selection, + ); + expect(mocks.actions.handleGsapRemoveKeyframe).not.toHaveBeenCalled(); + view.unmount(); + }); + + it("removes a non-selected element authored endpoint through the clicked element's selection", async () => { + const circle: TimelineElement = { + ...element, + id: "circle", + key: "scenes/main.html#circle", + domId: "circle", + }; + usePlayerStore.setState({ + elements: [element, circle], + gsapAnimations: new Map([["index.html#circle", [otherKeyframedAnimation]]]), + }); + const view = renderCallbacks(); + + await act(async () => { + view.callbacks.onDeleteKeyframe?.( + "scenes/main.html#circle", + 100, + "position", + 100, + otherKeyframedAnimation.id, + ); + await Promise.resolve(); + await Promise.resolve(); + }); + + expect(mocks.actions.handleGsapRemoveKeyframe).toHaveBeenCalledWith( + otherKeyframedAnimation.id, + 100, + undefined, + mocks.selection, + ); + expect(mocks.actions.handleGsapDeleteAnimation).not.toHaveBeenCalled(); + view.unmount(); + }); + + it("deletes all keyframes through the clicked non-selected element's identity", async () => { + const { circle, selection } = arrangeClickedCircle(); + const view = renderCallbacks(); + + await act(async () => { + view.callbacks.onDeleteAllKeyframes?.(circle); + await Promise.resolve(); + }); + + expect(mocks.actions.handleGsapRemoveAllKeyframes).toHaveBeenCalledWith( + otherKeyframedAnimation.id, + selection, + ); + view.unmount(); + }); + + it("moves a keyframe to the playhead through the clicked non-selected element's identity", async () => { + const { circle, selection } = arrangeClickedCircle(); + const view = renderCallbacks(); + + await act(async () => { + view.callbacks.onMoveKeyframeToPlayhead?.( + circle, + 100, + "position", + 100, + otherKeyframedAnimation.id, + ); + await Promise.resolve(); + }); + + expect(mocks.actions.handleGsapMoveKeyframeToPlayhead).toHaveBeenCalledWith( + otherKeyframedAnimation.id, + 100, + selection, + otherKeyframedAnimation, + ); + view.unmount(); + }); + + it("keeps selected-element flat boundary deletion on the animation delete path", () => { + const view = renderCallbacks(); + + act(() => { + view.callbacks.onDeleteKeyframe?.("box", 0, "position", 0, flatAnimation.id); + }); + + expect(mocks.actions.handleGsapDeleteAnimation).toHaveBeenCalledWith(flatAnimation.id); + expect(mocks.actions.handleGsapRemoveKeyframe).not.toHaveBeenCalled(); + view.unmount(); + }); + + it("routes the flat lane-header remove toggle through the guarded delete path", async () => { + const view = renderCallbacks(); + + await act(async () => { + await view.callbacks.onTogglePropertyGroupKeyframe?.(element, { + animationId: flatAnimation.id, + propertyGroup: "position", + tweenPercentage: 100, + properties: { x: 420 }, + remove: true, + }); + }); + + expect(mocks.actions.handleGsapDeleteAnimation).toHaveBeenCalledWith( + flatAnimation.id, + mocks.selection, + ); + expect(mocks.actions.handleGsapRemoveKeyframe).not.toHaveBeenCalled(); + view.unmount(); + }); + + it("keeps authored interior deletion on the per-keyframe path", () => { + mocks.animations = [authoredInteriorAnimation()]; + usePlayerStore.setState({ gsapAnimations: new Map([["box", mocks.animations]]) }); + const view = renderCallbacks(); + + act(() => { + view.callbacks.onDeleteKeyframe?.("box", 50, "position", 50, flatAnimation.id); + }); + + expect(mocks.actions.handleGsapRemoveKeyframe).toHaveBeenCalledWith(flatAnimation.id, 50); + expect(mocks.actions.handleGsapDeleteAnimation).not.toHaveBeenCalled(); + view.unmount(); + }); + + it("keeps an authored interior drag on the per-keyframe move path", async () => { + mocks.animations = [authoredInteriorAnimation()]; + const view = renderCallbacks(); + + await expect( + view.callbacks.onMoveKeyframe?.("box", 50, 75, "position", 50, flatAnimation.id), + ).resolves.toBe(true); + + expect(mocks.actions.handleGsapMoveKeyframe).toHaveBeenCalledWith(flatAnimation.id, 50, 75); + expect(mocks.actions.handleGsapResizeKeyframedTween).not.toHaveBeenCalled(); + view.unmount(); + }); + + it("uses the clip timing basis when retiming a duration-less tween", async () => { + const durationless = { + ...authoredInteriorAnimation(), + position: 3.2, + resolvedStart: 3.2, + duration: undefined, + }; + const wideElement = { ...element, start: 10.94, duration: 16.26 }; + mocks.animations = [durationless]; + usePlayerStore.setState({ + elements: [wideElement], + gsapAnimations: new Map([["box", [durationless]]]), + }); + const view = renderCallbacks(); + + await expect( + view.callbacks.onMoveKeyframe?.("box", 19.1, 40, "position", 50, durationless.id), + ).resolves.toBe(true); + + expect(mocks.actions.handleGsapMoveKeyframe).toHaveBeenCalledWith( + durationless.id, + 50, + expect.any(Number), + ); + expect(mocks.actions.handleGsapResizeKeyframedTween).not.toHaveBeenCalled(); + view.unmount(); + }); +}); diff --git a/packages/studio/src/components/nle/useTimelineEditCallbacks.ts b/packages/studio/src/components/nle/useTimelineEditCallbacks.ts index 76122eb47c..3787586746 100644 --- a/packages/studio/src/components/nle/useTimelineEditCallbacks.ts +++ b/packages/studio/src/components/nle/useTimelineEditCallbacks.ts @@ -1,4 +1,5 @@ import { useCallback, useMemo } from "react"; +import type { GsapAnimation } from "@hyperframes/core/gsap-parser"; import type { TimelineElement } from "../../player"; import { usePlayerStore } from "../../player/store/playerStore"; import type { BlockedTimelineEditIntent } from "../../player/components/timelineEditing"; @@ -11,7 +12,9 @@ import { import { resolveTweenStart, resolveTweenDuration } from "../../utils/globalTimeCompiler"; import { resolveClipTimingBasis } from "../../hooks/useGsapTweenCache"; import { resolveKeyframeRetime } from "../editor/keyframeRetime"; +import type { DomEditSelection } from "../editor/domEditingTypes"; import type { TimelineMoveOperation } from "../../hooks/timelineMoveAdapter"; +import { getTimelineElementIdentity } from "../../player/lib/timelineElementHelpers"; export interface TimelineEditCallbackDeps { handleTimelineElementMove: ( @@ -46,15 +49,14 @@ interface TimelineCachedKeyframe { percentage: number; tweenPercentage?: number; propertyGroup?: string; + animationId?: string; } /** * Resolve a rendered timeline diamond back to the animation that authored it. - * Flat tweens use synthesized diamonds, so a mixed flat tween may have neither - * a property group nor real keyframes. The cache currently carries a property - * group, not an animation id, so resolution is safe only when that group has a - * single candidate. Ambiguous candidates remain unresolved rather than - * retiming an arbitrary tween. + * Prefer the animation identity carried by the rendered keyframe. Legacy cache + * entries without one are safe only when their property group has one candidate; + * ambiguous candidates remain unresolved rather than retiming an arbitrary tween. */ export function resolveTimelineKeyframeTarget( pct: number, @@ -63,6 +65,14 @@ export function resolveTimelineKeyframeTarget( ): { animId: string; tweenPct: number } | null { const kf = keyframes.find((item) => Math.abs(item.percentage - pct) < 0.2); if (!kf) return null; + const identifiedAnimation = kf.animationId + ? animations.find((animation) => animation.id === kf.animationId) + : undefined; + if (kf.animationId) { + return identifiedAnimation + ? { animId: identifiedAnimation.id, tweenPct: kf.tweenPercentage ?? pct } + : null; + } const group = kf?.propertyGroup; const candidates = group ? animations.filter((animation) => animation.propertyGroup === group) @@ -98,22 +108,78 @@ export function useTimelineEditCallbacks({ handleGsapResizeKeyframedTween, handleGsapUpdateMeta, handleGsapAddKeyframe, + handleGsapAddKeyframeBatch, handleGsapConvertToKeyframes, handleGsapRemoveAllKeyframes, + handleGsapDeleteAnimation, buildDomSelectionForTimelineElement, } = useDomEditActionsContext(); + const resolveElementAnimations = useCallback( + (elementKey: string): GsapAnimation[] => { + const { gsapAnimations } = usePlayerStore.getState(); + const hashIndex = elementKey.lastIndexOf("#"); + const elementId = hashIndex === -1 ? elementKey : elementKey.slice(hashIndex + 1); + const sourceFile = + hashIndex === -1 ? (activeCompPath ?? "index.html") : elementKey.slice(0, hashIndex); + return ( + gsapAnimations.get(`${sourceFile}#${elementId}`) ?? + gsapAnimations.get(`index.html#${elementId}`) ?? + gsapAnimations.get(elementId) ?? + [] + ); + }, + [activeCompPath], + ); + // Resolve a timeline-diamond callback's clip-% to the keyframe's anim id + its // tween-relative percentage (shared by the delete/move keyframe callbacks): the // diamond reports a clip-% but the script ops key on the tween-%. Prefers the // anim in the keyframe's property group, falling back to the first keyframed one. const resolveKeyframeTarget = useCallback( // fallow-ignore-next-line complexity - (pct: number): { animId: string; tweenPct: number } | null => { - const cached = usePlayerStore.getState().keyframeCache.get(domEditSelection?.id ?? ""); - return resolveTimelineKeyframeTarget(pct, cached?.keyframes ?? [], selectedGsapAnimations); + ( + elementKey: string, + pct: number, + propertyGroup?: string, + tweenPercentage?: number, + animationId?: string, + animations: GsapAnimation[] = selectedGsapAnimations, + ): { animId: string; tweenPct: number } | null => { + const explicitTarget = + propertyGroup !== undefined || tweenPercentage !== undefined || animationId !== undefined + ? [{ percentage: pct, propertyGroup, tweenPercentage, animationId }] + : undefined; + const hashIndex = elementKey.lastIndexOf("#"); + const elementId = hashIndex === -1 ? elementKey : elementKey.slice(hashIndex + 1); + const keyframeCache = usePlayerStore.getState().keyframeCache; + const cached = keyframeCache.get(elementKey) ?? keyframeCache.get(elementId); + return resolveTimelineKeyframeTarget( + pct, + explicitTarget ?? cached?.keyframes ?? [], + animations, + ); }, - [domEditSelection?.id, selectedGsapAnimations], + [selectedGsapAnimations], + ); + + const removeKeyframeTarget = useCallback( + ( + animationId: string, + percentage: number, + animations: GsapAnimation[], + selectionOverride?: DomEditSelection | null, + ) => { + const animation = animations.find((candidate) => candidate.id === animationId); + if (animation && !animation.keyframes) { + if (selectionOverride === undefined) handleGsapDeleteAnimation(animationId); + else handleGsapDeleteAnimation(animationId, selectionOverride); + return; + } + if (selectionOverride === undefined) handleGsapRemoveKeyframe(animationId, percentage); + else handleGsapRemoveKeyframe(animationId, percentage, undefined, selectionOverride); + }, + [handleGsapDeleteAnimation, handleGsapRemoveKeyframe], ); return useMemo( @@ -127,22 +193,55 @@ export function useTimelineEditCallbacks({ onSplitElement: handleTimelineElementSplit, onRazorSplit: handleRazorSplit, onRazorSplitAll: handleRazorSplitAll, - onDeleteAllKeyframes: () => { + onDeleteAllKeyframes: (element) => { // Hold the element where it is (collapse keyframes to a static set) rather // than deleting the whole animation — deleting strands a stale GSAP base // that the next drag adds to, flinging the element off-screen. - const anim = selectedGsapAnimations.find((a) => a.keyframes); + const elementKey = getTimelineElementIdentity(element); + const anim = resolveElementAnimations(elementKey).find((animation) => animation.keyframes); if (!anim) return; - handleGsapRemoveAllKeyframes(anim.id); + void buildDomSelectionForTimelineElement(element).then((selection) => { + if (selection) handleGsapRemoveAllKeyframes(anim.id, selection); + }); }, - onDeleteKeyframe: (_elId: string, pct: number) => { - const target = resolveKeyframeTarget(pct); - if (target) handleGsapRemoveKeyframe(target.animId, target.tweenPct); + onDeleteKeyframe: (elId, pct, group, tweenPct, animationId) => { + const animations = resolveElementAnimations(elId); + const target = resolveKeyframeTarget(elId, pct, group, tweenPct, animationId, animations); + if (!target) return; + const element = usePlayerStore.getState().elements.find((el) => (el.key ?? el.id) === elId); + if (!element) { + removeKeyframeTarget(target.animId, target.tweenPct, animations); + return; + } + // Persist through the CLICKED element's own selection so a deletion on a + // non-selected element (especially one in a different source file) commits + // against the right element instead of the current domEditSelection. + void buildDomSelectionForTimelineElement(element).then((selection) => { + if (selection) + removeKeyframeTarget(target.animId, target.tweenPct, animations, selection); + }); }, // Retime the keyframe to the playhead, preserving its value + ease. - onMoveKeyframeToPlayhead: (_elId: string, pct: number) => { - const target = resolveKeyframeTarget(pct); - if (target) handleGsapMoveKeyframeToPlayhead(target.animId, target.tweenPct); + onMoveKeyframeToPlayhead: (element, pct, group, tweenPct, animationId) => { + const elementKey = getTimelineElementIdentity(element); + const animations = resolveElementAnimations(elementKey); + const target = resolveKeyframeTarget( + elementKey, + pct, + group, + tweenPct, + animationId, + animations, + ); + const animation = target + ? animations.find((candidate) => candidate.id === target.animId) + : undefined; + if (!target || !animation) return; + void buildDomSelectionForTimelineElement(element).then((selection) => { + if (selection) { + handleGsapMoveKeyframeToPlayhead(target.animId, target.tweenPct, selection, animation); + } + }); }, // Drag-to-retime. The diamond reports clip-%s; resolveKeyframeTarget gives // the dragged keyframe's anim + tween-%. We convert the clip-% drop to an @@ -152,14 +251,17 @@ export function useTimelineEditCallbacks({ // resizes the tween — position/duration grow so the dragged keyframe lands at // the drop while every other keyframe keeps its absolute time (value+ease too). // fallow-ignore-next-line complexity - onMoveKeyframe: (_elId: string, fromClipPct: number, toClipPct: number) => { - const target = resolveKeyframeTarget(fromClipPct); + onMoveKeyframe: (elId, fromClipPct, toClipPct, group, tweenPct, animationId) => { + const target = resolveKeyframeTarget(elId, fromClipPct, group, tweenPct, animationId); const sel = domEditSelection; - if (!target || !sel) return; + if (!target || !sel) return Promise.resolve(false); const anim = selectedGsapAnimations.find((a) => a.id === target.animId); const tweenStart = anim ? resolveTweenStart(anim) : null; - if (!anim || tweenStart === null) return; - const tweenDuration = anim.duration ?? resolveTweenDuration(anim); + if (!anim || tweenStart === null) return Promise.resolve(false); + // Synthesized flat endpoints are clip boundaries, not authored keyframes. + // Boundary-to-clip resize wiring is intentionally deferred; ignore the + // drag rather than dispatching a free keyframe move that cannot be written. + if (!anim.keyframes) return Promise.resolve(false); const sourceFile = sel.sourceFile || activeCompPath || "index.html"; const { elements, domClipChildren } = usePlayerStore.getState(); const { elStart, elDuration } = resolveClipTimingBasis( @@ -168,6 +270,7 @@ export function useTimelineEditCallbacks({ elements, domClipChildren, ); + const tweenDuration = resolveTweenDuration(anim, elDuration); const dropAbsTime = elStart + (toClipPct / 100) * elDuration; const decision = resolveKeyframeRetime({ keyframes: anim.keyframes?.keyframes ?? [], @@ -177,30 +280,21 @@ export function useTimelineEditCallbacks({ dropAbsTime, }); if (decision.kind === "move" && decision.toTweenPct != null) { - handleGsapMoveKeyframe(target.animId, target.tweenPct, decision.toTweenPct); + return handleGsapMoveKeyframe(target.animId, target.tweenPct, decision.toTweenPct); } else if ( decision.kind === "resize" && decision.pctRemap && decision.position != null && decision.duration != null ) { - if (anim.keyframes) { - handleGsapResizeKeyframedTween( - target.animId, - decision.position, - decision.duration, - decision.pctRemap, - ); - } else { - // resize-keyframed-tween requires an authored `keyframes` AST node - // and intentionally no-ops for a flat tween. Update its real tween - // window through the metadata writer (and SDK cutover path) instead. - handleGsapUpdateMeta(target.animId, { - position: decision.position, - duration: decision.duration, - }); - } + return handleGsapResizeKeyframedTween( + target.animId, + decision.position, + decision.duration, + decision.pctRemap, + ); } + return Promise.resolve(false); }, onChangeKeyframeEase: (_elId: string, _pct: number, ease: string) => { for (const anim of selectedGsapAnimations) { @@ -227,6 +321,26 @@ export function useTimelineEditCallbacks({ if (flatAnim) handleGsapConvertToKeyframes(flatAnim.id); } }, + onTogglePropertyGroupKeyframe: async (element, target) => { + const selection = await buildDomSelectionForTimelineElement(element); + if (!selection) return; + if (target.remove) { + removeKeyframeTarget( + target.animationId, + target.tweenPercentage, + selectedGsapAnimations, + selection, + ); + return; + } + await handleGsapAddKeyframeBatch( + target.animationId, + target.tweenPercentage, + target.properties, + undefined, + selection, + ); + }, }), // eslint-disable-next-line react-hooks/exhaustive-deps [ @@ -240,14 +354,16 @@ export function useTimelineEditCallbacks({ handleRazorSplit, handleRazorSplitAll, handleGsapRemoveAllKeyframes, + resolveElementAnimations, resolveKeyframeTarget, + removeKeyframeTarget, selectedGsapAnimations, - handleGsapRemoveKeyframe, handleGsapMoveKeyframeToPlayhead, handleGsapMoveKeyframe, handleGsapResizeKeyframedTween, handleGsapUpdateMeta, handleGsapAddKeyframe, + handleGsapAddKeyframeBatch, handleGsapConvertToKeyframes, buildDomSelectionForTimelineElement, projectId, diff --git a/packages/studio/src/contexts/TimelineEditContext.tsx b/packages/studio/src/contexts/TimelineEditContext.tsx index c2b6edc6ce..be7f4e9ad6 100644 --- a/packages/studio/src/contexts/TimelineEditContext.tsx +++ b/packages/studio/src/contexts/TimelineEditContext.tsx @@ -44,6 +44,7 @@ export function TimelineEditProvider({ value.onMoveKeyframeToPlayhead, value.onMoveKeyframe, value.onToggleKeyframeAtPlayhead, + value.onTogglePropertyGroupKeyframe, ], ); return {children}; diff --git a/packages/studio/src/hooks/deleteSelectedKeyframes.ts b/packages/studio/src/hooks/deleteSelectedKeyframes.ts index 20d5c9ff0d..79342aa04b 100644 --- a/packages/studio/src/hooks/deleteSelectedKeyframes.ts +++ b/packages/studio/src/hooks/deleteSelectedKeyframes.ts @@ -1,5 +1,5 @@ import { usePlayerStore } from "../player/store/playerStore"; -import { selectedKeyframePercentagesForElement } from "../utils/keyframeSelection"; +import { timelineKeyframeTargetFromSelectionKey } from "../player/components/timelineKeyframeIdentity"; import type { CommitMutationOptions } from "./gsapScriptCommitTypes"; let deleteKeyframesCommitCounter = 0; @@ -18,18 +18,31 @@ export function deleteSelectedKeyframes(session: { ) => void; }): void { const { selectedKeyframes, selectedElementId } = usePlayerStore.getState(); - const animation = session.selectedGsapAnimations.find((anim) => anim.keyframes); - if (!animation) return; - // Only the active element's keyframes; a stale cross-element selection must not delete here. - const percentages = selectedKeyframePercentagesForElement(selectedKeyframes, selectedElementId); + if (!selectedElementId) return; + const keyframedAnimations = session.selectedGsapAnimations.filter((anim) => anim.keyframes); + const fallbackAnimation = keyframedAnimations[0]; + const animationsById = new Map(keyframedAnimations.map((animation) => [animation.id, animation])); + const removals = new Map(); + for (const key of selectedKeyframes) { + const target = timelineKeyframeTargetFromSelectionKey(selectedElementId, key); + if (!target) continue; + const animation = target.animationId + ? animationsById.get(target.animationId) + : fallbackAnimation; + if (!animation) continue; + const percentage = target.tweenPercentage ?? target.percentage; + removals.set(`${animation.id}\0${percentage}`, { animationId: animation.id, percentage }); + } + const targets = [...removals.values()]; + if (targets.length === 0) return; const coalesceOptions = { coalesceKey: `delete-keyframes:${++deleteKeyframesCommitCounter}`, coalesceMs: Number.POSITIVE_INFINITY, }; - for (const [index, pct] of percentages.entries()) { - session.handleGsapRemoveKeyframe(animation.id, pct, { + for (const [index, target] of targets.entries()) { + session.handleGsapRemoveKeyframe(target.animationId, target.percentage, { ...coalesceOptions, - ...(index === percentages.length - 1 ? { softReload: true } : { skipReload: true }), + ...(index === targets.length - 1 ? { softReload: true } : { skipReload: true }), }); } } diff --git a/packages/studio/src/hooks/gsapDragCommit.ts b/packages/studio/src/hooks/gsapDragCommit.ts index 167ce438d5..4774c17e1b 100644 --- a/packages/studio/src/hooks/gsapDragCommit.ts +++ b/packages/studio/src/hooks/gsapDragCommit.ts @@ -12,7 +12,7 @@ import { usePlayerStore } from "../player/store/playerStore"; import { readRuntimeKeyframes, scanAllRuntimeKeyframes } from "./gsapRuntimeKeyframes"; import { resolveTweenStart, resolveTweenDuration } from "../utils/globalTimeCompiler"; import { roundTo3 } from "../utils/rounding"; -import { computeElementPercentage } from "./gsapShared"; +import { computeElementPercentage, idSelector } from "./gsapShared"; import { computeDraggedGsapPosition } from "./draggedGsapPosition"; import type { RuntimeTweenChange } from "./gsapRuntimePatch"; import { isGestureTransactionCommit, runGestureTransaction } from "./gestureTransaction"; @@ -117,7 +117,7 @@ export async function materializeIfDynamic( const allScanned = scanAllRuntimeKeyframes(iframe); if (allScanned.size === 0) return; const allElements = Array.from(allScanned.entries()).map(([id, data]) => ({ - selector: `#${id}`, + selector: idSelector(id), keyframes: data.keyframes, easeEach: data.easeEach, })); diff --git a/packages/studio/src/hooks/gsapDragPositionCommit.ts b/packages/studio/src/hooks/gsapDragPositionCommit.ts index ac1d760126..b54847dcad 100644 --- a/packages/studio/src/hooks/gsapDragPositionCommit.ts +++ b/packages/studio/src/hooks/gsapDragPositionCommit.ts @@ -11,6 +11,21 @@ import { materializeIfDynamic, } from "./gsapDragCommit"; +export function buildTemporalArcKeyframes( + anim: GsapAnimation, + percentage: number, + properties: Record, +) { + return [ + ...(anim.keyframes?.keyframes ?? []).map((keyframe) => ({ + percentage: keyframe.percentage, + properties: { ...keyframe.properties }, + ...(keyframe.ease ? { ease: keyframe.ease } : {}), + })), + { percentage, properties }, + ].sort((a, b) => a.percentage - b.percentage); +} + async function extendTweenAndAddKeyframe( selection: DomEditSelection, anim: GsapAnimation, @@ -259,6 +274,47 @@ export async function commitGsapPositionFromDrag( const backfillDefaults: Record = { x: baseGsapX, y: baseGsapY }; const ct = usePlayerStore.getState().currentTime; + if (anim.arcPath?.enabled) { + const { activeKeyframePct, setActiveKeyframePct } = usePlayerStore.getState(); + const pct = activeKeyframePct ?? computeCurrentPercentage(selection, anim); + const keyframes = anim.keyframes?.keyframes ?? []; + const pointIndex = keyframes.findIndex((kf) => Math.abs(kf.percentage - pct) < 0.05); + if (pointIndex >= 0) { + await callbacks.commitMutation( + selection, + { + type: "update-motion-path-point", + animationId: anim.id, + pointIndex, + x: newX, + y: newY, + }, + { label: "Move layer (waypoint)", softReload: true, beforeReload: restoreOffset }, + ); + setActiveKeyframePct(null); + parkPlayheadOnKeyframe(anim, pct); + return; + } + + const tweenStart = resolveTweenStart(anim); + const tweenDuration = resolveTweenDuration(anim); + if (tweenStart === null || tweenDuration <= 0 || keyframes.length < 2) return; + const temporalKeyframes = buildTemporalArcKeyframes(anim, pct, { x: newX, y: newY }); + await callbacks.commitMutation( + selection, + { + type: "replace-with-keyframes", + animationId: anim.id, + targetSelector: anim.targetSelector, + position: roundTo3(tweenStart), + duration: roundTo3(tweenDuration), + keyframes: temporalKeyframes, + ease: "none", + }, + { label: "Move layer (new keyframe)", softReload: true, beforeReload: restoreOffset }, + ); + return; + } if (anim.keyframes) { const newId = await materializeIfDynamic(anim, iframe, callbacks.commitMutation, selection); const effectiveAnim = newId ? { ...anim, id: newId } : anim; diff --git a/packages/studio/src/hooks/gsapKeyframeCacheHelpers.test.ts b/packages/studio/src/hooks/gsapKeyframeCacheHelpers.test.ts index 16fc62b206..ee72035f5e 100644 --- a/packages/studio/src/hooks/gsapKeyframeCacheHelpers.test.ts +++ b/packages/studio/src/hooks/gsapKeyframeCacheHelpers.test.ts @@ -28,7 +28,7 @@ const animWithKeyframes = (id: string): GsapAnimation => ({ }); beforeEach(() => { - usePlayerStore.setState({ keyframeCache: new Map(), elements: [] }); + usePlayerStore.setState({ keyframeCache: new Map(), gsapAnimations: new Map(), elements: [] }); }); describe("clearKeyframeCacheForElement", () => { @@ -98,6 +98,41 @@ describe("clearKeyframeCacheForFile", () => { }); describe("updateKeyframeCacheFromParsed", () => { + it("serializes a multi-keyframe tween with a stable shape and animation identity", () => { + const animation: GsapAnimation = { + ...animWithKeyframes("hero"), + duration: 2, + resolvedStart: 3, + keyframes: { + format: "percentage", + keyframes: [ + { percentage: 0, properties: { x: 0 } }, + { percentage: 50, properties: { x: 100 }, ease: "power1.inOut" }, + { percentage: 100, properties: { x: 200 } }, + ], + easeEach: "power1.inOut", + }, + }; + usePlayerStore.setState({ + elements: [ + { + id: "hero-clip", + domId: "hero", + tag: "div", + start: 2, + duration: 4, + track: 0, + }, + ], + }); + + updateKeyframeCacheFromParsed([animation], "scene.html", "hero", {}); + + expect(JSON.stringify(cache().get("scene.html#hero"))).toBe( + '{"format":"percentage","keyframes":[{"percentage":25,"properties":{"x":0},"tweenPercentage":0,"propertyGroup":"position","animationId":"hero"},{"percentage":50,"properties":{"x":100},"ease":"power1.inOut","tweenPercentage":50,"propertyGroup":"position","animationId":"hero"},{"percentage":75,"properties":{"x":200},"tweenPercentage":100,"propertyGroup":"position","animationId":"hero"}],"easeEach":"power1.inOut"}', + ); + }); + it("clears the bare key when the selected element no longer has keyframes", () => { // Element previously had keyframes, so a bare entry exists (writes set both). seed("index.html#box"); @@ -118,4 +153,63 @@ describe("updateKeyframeCacheFromParsed", () => { expect(cache().has("index.html#hero")).toBe(true); expect(cache().has("hero")).toBe(true); }); + + it("caches flat tweens as clip-relative start and end keyframes", () => { + const animation: GsapAnimation = { + id: "flat-box", + targetSelector: "#box", + method: "to", + position: 1, + properties: { x: 420 }, + duration: 2, + resolvedStart: 1, + ease: "power2.out", + propertyGroup: "position", + }; + usePlayerStore.setState({ + elements: [{ id: "box-clip", domId: "box", tag: "div", start: 1, duration: 2, track: 0 }], + }); + + updateKeyframeCacheFromParsed([animation], "scene.html", "box", {}); + + expect(cache().get("scene.html#box")).toEqual({ + format: "percentage", + keyframes: [ + { + percentage: 0, + properties: { x: 0 }, + tweenPercentage: 0, + propertyGroup: "position", + animationId: "flat-box", + }, + { + percentage: 100, + properties: { x: 420 }, + ease: "power2.out", + tweenPercentage: 100, + propertyGroup: "position", + animationId: "flat-box", + }, + ], + }); + expect(usePlayerStore.getState().gsapAnimations.get("scene.html#box")).toEqual([animation]); + }); + + it("does not cache a flat tween without animatable numeric properties", () => { + const animation: GsapAnimation = { + id: "flat-box", + targetSelector: "#box", + method: "to", + position: 0, + properties: { backgroundColor: "#fff" }, + duration: 1, + propertyGroup: "visual", + }; + + updateKeyframeCacheFromParsed([animation], "scene.html", "box", {}); + + expect(cache().has("scene.html#box")).toBe(false); + expect(cache().has("box")).toBe(false); + expect(usePlayerStore.getState().gsapAnimations.has("scene.html#box")).toBe(false); + }); }); diff --git a/packages/studio/src/hooks/gsapKeyframeCacheHelpers.ts b/packages/studio/src/hooks/gsapKeyframeCacheHelpers.ts index 1b5bef62b0..58da5c7aae 100644 --- a/packages/studio/src/hooks/gsapKeyframeCacheHelpers.ts +++ b/packages/studio/src/hooks/gsapKeyframeCacheHelpers.ts @@ -5,6 +5,7 @@ import type { GsapAnimation } from "@hyperframes/core/gsap-parser"; import { usePlayerStore, type KeyframeCacheEntry } from "../player/store/playerStore"; import { toAbsoluteTime } from "./gsapShared"; +import { synthesizeFlatTweenKeyframes } from "./gsapTweenSynth"; export function updateKeyframeCacheFromParsed( animations: GsapAnimation[], @@ -15,10 +16,16 @@ export function updateKeyframeCacheFromParsed( const { setKeyframeCache, elements } = usePlayerStore.getState(); const idsWithKeyframes = new Set(); const merged = new Map(); + const sourceAnimations = new Map(); for (const anim of animations) { const id = anim.targetSelector.match(/^#([\w-]+)/)?.[1]; - if (!id || !anim.keyframes) continue; + const kfSource = + anim.keyframes?.keyframes ?? synthesizeFlatTweenKeyframes(anim)?.keyframes ?? []; + if (!id || kfSource.length === 0) continue; idsWithKeyframes.add(id); + if (anim.propertyGroup) { + sourceAnimations.set(id, [...(sourceAnimations.get(id) ?? []), anim]); + } // Convert tween-relative percentages to clip-relative so diamonds // render at the correct position within the timeline clip. @@ -29,7 +36,7 @@ export function updateKeyframeCacheFromParsed( ); const elStart = timelineEl?.start ?? 0; const elDuration = timelineEl?.duration ?? 1; - const clipKeyframes = anim.keyframes.keyframes.map((kf) => { + const clipKeyframes = kfSource.map((kf) => { const absTime = toAbsoluteTime(tweenPos, tweenDur, kf.percentage); const clipPct = elDuration > 0 ? Math.round(((absTime - elStart) / elDuration) * 1000) / 10 : kf.percentage; @@ -38,6 +45,7 @@ export function updateKeyframeCacheFromParsed( percentage: clipPct, tweenPercentage: kf.percentage, propertyGroup: anim.propertyGroup, + animationId: anim.id, }; }); @@ -48,6 +56,17 @@ export function updateKeyframeCacheFromParsed( const prev = byPct.get(kf.percentage); if (prev) { prev.properties = { ...prev.properties, ...kf.properties }; + // Mirror deduplicateKeyframes: a same-% collision across different + // source animations is an ambiguous merged segment (the button can + // only target one arbitrary animation). Flag it so the collapsed row + // suppresses the inline ease button there. + if ( + prev.animationId !== undefined && + kf.animationId !== undefined && + prev.animationId !== kf.animationId + ) { + prev.easeAmbiguous = true; + } if (kf.ease) prev.ease = kf.ease; } else { byPct.set(kf.percentage, { ...kf, properties: { ...kf.properties } }); @@ -55,13 +74,18 @@ export function updateKeyframeCacheFromParsed( } existing.keyframes = Array.from(byPct.values()).sort((a, b) => a.percentage - b.percentage); } else { - merged.set(id, { ...anim.keyframes, keyframes: clipKeyframes }); + merged.set(id, { + ...anim.keyframes, + format: anim.keyframes?.format ?? "percentage", + keyframes: clipKeyframes, + }); } } for (const [id, entry] of merged) { setKeyframeCache(`${targetPath}#${id}`, entry); setKeyframeCache(id, entry); if (targetPath !== "index.html") setKeyframeCache(`index.html#${id}`, entry); + writeGsapAnimationsForElement(targetPath, id, sourceAnimations.get(id)); } const targetId = (mutation as { targetSelector?: string }).targetSelector?.match(/^#([\w-]+)/)?.[1] ?? @@ -84,13 +108,12 @@ export function updateKeyframeCacheFromParsed( * a new cache map and re-render every subscriber. */ export function clearKeyframeCacheForElement(sourceFile: string, elementId: string): void { - const { keyframeCache, setKeyframeCache } = usePlayerStore.getState(); - const keys = - sourceFile === "index.html" - ? [`index.html#${elementId}`, elementId] - : [`${sourceFile}#${elementId}`, `index.html#${elementId}`, elementId]; + const { keyframeCache, setKeyframeCache, gsapAnimations, setGsapAnimations } = + usePlayerStore.getState(); + const keys = elementCacheKeys(sourceFile, elementId); for (const key of keys) { if (keyframeCache.has(key)) setKeyframeCache(key, undefined); + if (gsapAnimations.has(key)) setGsapAnimations(key, undefined); } } @@ -102,11 +125,11 @@ export function clearKeyframeCacheForElement(sourceFile: string, elementId: stri * absent from the re-scan) leaves no stale bare entry behind. */ export function clearKeyframeCacheForFile(sourceFile: string): void { - const { keyframeCache } = usePlayerStore.getState(); + const { keyframeCache, gsapAnimations } = usePlayerStore.getState(); const sfPrefix = `${sourceFile}#`; const fallbackPrefix = "index.html#"; const ids = new Set(); - for (const key of keyframeCache.keys()) { + for (const key of [...keyframeCache.keys(), ...gsapAnimations.keys()]) { const matchesFile = key.startsWith(sfPrefix) || (sourceFile !== "index.html" && key.startsWith(fallbackPrefix)); if (!matchesFile) continue; @@ -118,6 +141,23 @@ export function clearKeyframeCacheForFile(sourceFile: string): void { } } +function elementCacheKeys(sourceFile: string, elementId: string): string[] { + return sourceFile === "index.html" + ? [`index.html#${elementId}`, elementId] + : [`${sourceFile}#${elementId}`, `index.html#${elementId}`, elementId]; +} + +export function writeGsapAnimationsForElement( + sourceFile: string, + elementId: string, + animations: GsapAnimation[] | undefined, +): void { + const { setGsapAnimations } = usePlayerStore.getState(); + for (const key of elementCacheKeys(sourceFile, elementId)) { + setGsapAnimations(key, animations); + } +} + function buildCacheKey(sourceFile: string, elementId: string): string { return `${sourceFile}#${elementId}`; } diff --git a/packages/studio/src/hooks/gsapRuntimeBridge.test.ts b/packages/studio/src/hooks/gsapRuntimeBridge.test.ts index 7c78c05872..de5c5ef78d 100644 --- a/packages/studio/src/hooks/gsapRuntimeBridge.test.ts +++ b/packages/studio/src/hooks/gsapRuntimeBridge.test.ts @@ -280,3 +280,103 @@ describe("tryGsapDragIntercept — autoKeyframeEnabled toggle (#1808)", () => { expect(types).not.toContain("replace-with-keyframes"); }); }); + +describe("tryGsapDragIntercept — motion paths", () => { + const motionPathAnim = { + id: "#puck-b-to-12170-position", + targetSelector: "#puck-b", + propertyGroup: "position", + method: "to", + position: 12.17, + resolvedStart: 12.17, + duration: 16.055, + ease: "power1.inOut", + properties: {}, + keyframes: { + keyframes: [ + { percentage: 0, properties: { x: -184, y: 326 } }, + { percentage: 50, properties: { x: 416, y: 804 } }, + { percentage: 100, properties: { x: 796, y: 237 } }, + ], + }, + arcPath: { + enabled: true, + autoRotate: false, + segments: [{ curviness: 1 }, { curviness: 1 }], + }, + } as unknown as GsapAnimation; + const liveTween = { + targets: () => [{ id: "puck-b" }], + vars: { motionPath: { path: [] }, duration: 16.055 }, + duration: () => 16.055, + startTime: () => 12.17, + }; + + async function dragMotionPath(activeKeyframePct: number | null) { + usePlayerStore.setState({ + autoKeyframeEnabled: true, + activeKeyframePct, + currentTime: 15.9, + }); + const commitMutation = vi.fn(); + const handled = await tryGsapDragIntercept( + selection, + { x: -50, y: 30 }, + [motionPathAnim], + fakeIframe("puck-b", [liveTween]), + commitMutation, + ); + return { commitMutation, handled }; + } + + afterEach(() => { + usePlayerStore.setState({ activeKeyframePct: null }); + }); + + it("creates a temporal keyframe at the exact playhead instead of redistributing path waypoints", async () => { + const { commitMutation, handled } = await dragMotionPath(null); + + expect(handled).toBe(true); + expect(commitMutation).toHaveBeenCalledWith( + selection, + { + type: "replace-with-keyframes", + animationId: motionPathAnim.id, + targetSelector: "#puck-b", + position: 12.17, + duration: 16.055, + keyframes: [ + { percentage: 0, properties: { x: -184, y: 326 } }, + { percentage: 23.233, properties: { x: -50, y: 30 } }, + { percentage: 50, properties: { x: 416, y: 804 } }, + { percentage: 100, properties: { x: 796, y: 237 } }, + ], + ease: "none", + }, + expect.objectContaining({ label: "Move layer (new keyframe)", softReload: true }), + ); + expect(commitMutation.mock.calls.map(([, mutation]) => mutation.type)).not.toContain( + "add-motion-path-point", + ); + }); + + it("keeps an explicitly selected path waypoint as a spatial edit", async () => { + const { commitMutation, handled } = await dragMotionPath(50); + + expect(handled).toBe(true); + expect(commitMutation).toHaveBeenCalledWith( + selection, + { + type: "update-motion-path-point", + animationId: motionPathAnim.id, + pointIndex: 1, + x: -50, + y: 30, + }, + expect.objectContaining({ label: "Move layer (waypoint)", softReload: true }), + ); + expect(commitMutation.mock.calls.map(([, mutation]) => mutation.type)).not.toContain( + "replace-with-keyframes", + ); + }); +}); diff --git a/packages/studio/src/hooks/gsapScriptCommitHelpers.ts b/packages/studio/src/hooks/gsapScriptCommitHelpers.ts index d84c698608..e6d17338f3 100644 --- a/packages/studio/src/hooks/gsapScriptCommitHelpers.ts +++ b/packages/studio/src/hooks/gsapScriptCommitHelpers.ts @@ -2,12 +2,13 @@ import { findUnsafeDomPatchValues } from "@hyperframes/core/studio-api/finite-mu import type { DomEditSelection } from "../components/editor/domEditingTypes"; export { PROPERTY_DEFAULTS } from "./gsapShared"; +import { idSelector } from "./gsapShared"; export function ensureElementAddressable(selection: DomEditSelection): { selector: string; autoId?: string; } { - if (selection.id) return { selector: `#${selection.id}` }; + if (selection.id) return { selector: idSelector(selection.id) }; if (selection.selector) return { selector: selection.selector }; const el = selection.element; @@ -20,7 +21,7 @@ export function ensureElementAddressable(selection: DomEditSelection): { id = `${tag}-${n}`; } el.setAttribute("id", id); - return { selector: `#${id}`, autoId: id }; + return { selector: idSelector(id), autoId: id }; } export class GsapMutationHttpError extends Error { diff --git a/packages/studio/src/hooks/gsapScriptCommitTypes.ts b/packages/studio/src/hooks/gsapScriptCommitTypes.ts index 137dc2af18..929e79b8ec 100644 --- a/packages/studio/src/hooks/gsapScriptCommitTypes.ts +++ b/packages/studio/src/hooks/gsapScriptCommitTypes.ts @@ -16,6 +16,8 @@ export interface MutationResult { export interface CommitMutationOptions { label: string; + /** Observe the durable writer result without duplicating the request path. */ + onResult?: (result: MutationResult) => void; coalesceKey?: string; coalesceMs?: number; softReload?: boolean; diff --git a/packages/studio/src/hooks/gsapShared.test.ts b/packages/studio/src/hooks/gsapShared.test.ts index ba45743488..5c7afbdb1b 100644 --- a/packages/studio/src/hooks/gsapShared.test.ts +++ b/packages/studio/src/hooks/gsapShared.test.ts @@ -1,6 +1,26 @@ import { describe, it, expect } from "vitest"; import type { GsapAnimation } from "@hyperframes/core/gsap-parser"; -import { isInstantHold, parsePercentageKeyframes } from "./gsapShared"; +import type { DomEditSelection } from "../components/editor/domEditingTypes"; +import { + idSelector, + isInstantHold, + parsePercentageKeyframes, + resolveEditableTweenDuration, +} from "./gsapShared"; + +describe("resolveEditableTweenDuration", () => { + const selection = { dataAttributes: { duration: "16.26" } } as DomEditSelection; + + it("uses the owning clip duration when the tween omits an outer duration", () => { + expect(resolveEditableTweenDuration({ duration: undefined } as GsapAnimation, selection)).toBe( + 16.26, + ); + }); + + it("keeps an explicitly-authored tween duration", () => { + expect(resolveEditableTweenDuration({ duration: 4 } as GsapAnimation, selection)).toBe(4); + }); +}); describe("isInstantHold", () => { const animation = (method: GsapAnimation["method"], duration?: number) => @@ -74,3 +94,32 @@ describe("parsePercentageKeyframes", () => { expect(parsePercentageKeyframes({})).toBeNull(); }); }); + +describe("idSelector", () => { + it("uses #id for valid CSS identifiers", () => { + expect(idSelector("hero-word")).toBe("#hero-word"); + expect(idSelector("el_1")).toBe("#el_1"); + }); + + it("uses an attribute selector for ids that #id can't address (digit-leading, dots, spaces)", () => { + // #01-... / #a.b / #a b throw a SyntaxError in querySelector / GSAP, crashing + // the preview when such a target is committed (e.g. dragging the element). + expect(idSelector("01-hook-hero-word")).toBe('[id="01-hook-hero-word"]'); + expect(idSelector("my.class")).toBe('[id="my.class"]'); + expect(idSelector("1box")).toBe('[id="1box"]'); + }); + + it("escapes quotes and backslashes in the attribute selector value", () => { + expect(idSelector('1"x')).toBe('[id="1\\"x"]'); + }); + + it("only ever emits #id for ids that can't break querySelector", () => { + // Every id resolves to either a plain #id (only when safe) or an attribute + // selector — never a #id that would throw a SyntaxError. + for (const id of ["hero-word", "01-hook", "a.b", "a b", "1", "--x", '1"q']) { + const sel = idSelector(id); + if (sel.startsWith("#")) expect(sel).toBe(`#${id}`); + else expect(sel.startsWith('[id="')).toBe(true); + } + }); +}); diff --git a/packages/studio/src/hooks/gsapShared.ts b/packages/studio/src/hooks/gsapShared.ts index 459f303b46..ab4feb938e 100644 --- a/packages/studio/src/hooks/gsapShared.ts +++ b/packages/studio/src/hooks/gsapShared.ts @@ -53,14 +53,57 @@ export function isInstantHold(animation: GsapAnimation): boolean { * Returns `#id` if the selection has an id, otherwise the raw selector, * or null if neither exists. */ +/** + * A CSS-valid selector for an element id. `#id` for a valid CSS identifier, + * otherwise an `[id="..."]` attribute selector. IDs that start with a digit + * (e.g. "01-hook-hero-word") make `#id` an invalid selector, so + * `document.querySelector("#01-...")` / GSAP's `querySelectorAll` throw a + * SyntaxError — which surfaces as a masked cross-origin "Script error." and + * crashes the preview the moment such a target is committed (e.g. dragging). + */ +// Conservative: matches only ids that are unquestionably safe as a `#id` +// selector — ASCII identifier, starts with a letter/underscore (or a single +// leading hyphen), no dots/colons/spaces/digits-first. Anything it rejects +// (digit-leading like "01-hook-...", dots, spaces, non-ASCII, …) falls through +// to the attribute selector below, which is always valid. It can only ever err +// toward the safe form, never toward a `#id` that throws — and, unlike +// `CSS.escape`, it needs no browser global (this runs in node tests too). +const SAFE_HASH_ID = /^-?[A-Za-z_][\w-]*$/; + +export function idSelector(id: string): string { + // A `#id` selector is only valid for a CSS identifier. IDs that start with a + // digit (e.g. "01-hook-hero-word") make `document.querySelector("#01-...")` and + // GSAP's `querySelectorAll` throw a SyntaxError — surfacing as a masked + // cross-origin "Script error." that crashes the preview the moment such a + // target is committed (e.g. dragging the element). Address those via an + // attribute selector instead (quotes/backslashes escaped for the string). + return SAFE_HASH_ID.test(id) ? `#${id}` : `[id="${id.replace(/(["\\])/g, "\\$1")}"]`; +} + export function selectorFromSelection(selection: DomEditSelection): string | null { - if (selection.id) return `#${selection.id}`; + if (selection.id) return idSelector(selection.id); if (selection.selector) return selection.selector; return null; } // ── Percentage computation ──────────────────────────────────────────────────── +/** + * Resolve the timing basis used by editor keyframes. The timeline renders a + * duration-less tween across its owning clip, so mutations must use that same + * duration instead of silently falling back to GSAP's 0.5s default. + */ +export function resolveEditableTweenDuration( + animation: GsapAnimation, + selection: DomEditSelection, +): number { + const clipDuration = Number.parseFloat(selection.dataAttributes?.duration ?? ""); + return resolveTweenDuration( + animation, + Number.isFinite(clipDuration) && clipDuration > 0 ? clipDuration : 0.5, + ); +} + /** * Compute the current playback percentage within an element's animation range. * Uses the animation's resolved timing if available, otherwise falls back to @@ -73,7 +116,7 @@ export function computeElementPercentage( ): number { if (animation) { const start = resolveTweenStart(animation); - const duration = resolveTweenDuration(animation); + const duration = resolveEditableTweenDuration(animation, selection); if (duration <= 0) return 0; if (start !== null) { return absoluteToPercentage(currentTime, start, duration); @@ -81,9 +124,7 @@ export function computeElementPercentage( } const elStart = Number.parseFloat(selection.dataAttributes?.start ?? "0") || 0; const elDuration = Number.parseFloat(selection.dataAttributes?.duration ?? "1") || 1; - return elDuration > 0 - ? Math.max(0, Math.min(100, Math.round(((currentTime - elStart) / elDuration) * 1000) / 10)) - : 0; + return absoluteToPercentage(currentTime, elStart, elDuration); } // ── Iframe accessors ────────────────────────────────────────────────────────── @@ -118,6 +159,18 @@ export interface ParsedPercentageKeyframes { easeEach?: string; } +function collectAnimatableKeyframeProperties( + entry: Record, +): Record { + const properties: Record = {}; + for (const [property, value] of Object.entries(entry)) { + if (property === "ease") continue; + if (typeof value === "number") properties[property] = Math.round(value * 1000) / 1000; + else if (typeof value === "string") properties[property] = value; + } + return properties; +} + /** * Parse a GSAP percentage-keyframe object (`{ "0%": { x: 10 }, "100%": { x: 200 } }`) * into a sorted array of `{ percentage, properties }` entries. @@ -146,12 +199,7 @@ export function parsePercentageKeyframes( steps.forEach((entry, i) => { if (!entry || typeof entry !== "object") return; const percentage = steps.length > 1 ? Math.round((i / (steps.length - 1)) * 1000) / 10 : 0; - const properties: Record = {}; - for (const [pk, pv] of Object.entries(entry as Record)) { - if (pk === "ease") continue; - if (typeof pv === "number") properties[pk] = Math.round(pv * 1000) / 1000; - else if (typeof pv === "string") properties[pk] = pv; - } + const properties = collectAnimatableKeyframeProperties(entry as Record); if (Object.keys(properties).length > 0) keyframes.push({ percentage, properties }); }); return keyframes.length > 0 ? { keyframes } : null; @@ -165,12 +213,7 @@ export function parsePercentageKeyframes( const pctMatch = key.match(/^(\d+(?:\.\d+)?)%$/); if (!pctMatch || !val || typeof val !== "object") continue; const percentage = parseFloat(pctMatch[1]); - const properties: Record = {}; - for (const [pk, pv] of Object.entries(val as Record)) { - if (pk === "ease") continue; - if (typeof pv === "number") properties[pk] = Math.round(pv * 1000) / 1000; - else if (typeof pv === "string") properties[pk] = pv; - } + const properties = collectAnimatableKeyframeProperties(val as Record); if (Object.keys(properties).length > 0) { keyframes.push({ percentage, properties }); } diff --git a/packages/studio/src/hooks/gsapTweenSynth.test.ts b/packages/studio/src/hooks/gsapTweenSynth.test.ts index 3d8d771222..b5474cf1de 100644 --- a/packages/studio/src/hooks/gsapTweenSynth.test.ts +++ b/packages/studio/src/hooks/gsapTweenSynth.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; import type { GsapAnimation } from "@hyperframes/core/gsap-parser"; -import { synthesizeFlatTweenKeyframes } from "./gsapTweenSynth"; +import { deduplicateKeyframes, synthesizeFlatTweenKeyframes } from "./gsapTweenSynth"; function anim(overrides: Partial): GsapAnimation { return { @@ -53,3 +53,32 @@ describe("synthesizeFlatTweenKeyframes", () => { expect(out).not.toBeNull(); }); }); + +describe("deduplicateKeyframes ease ambiguity", () => { + it("flags a same-% collision from different animations (different eases)", () => { + const merged = deduplicateKeyframes([ + { percentage: 45, properties: { x: 10 }, ease: "power2.in", animationId: "#a-position" }, + { percentage: 45, properties: { opacity: 1 }, ease: "power2.out", animationId: "#a-visual" }, + ]); + const kf = merged.find((k) => k.percentage === 45); + expect(kf?.easeAmbiguous).toBe(true); + }); + + it("flags a cross-animation collision even when the raw eases match", () => { + // The button can still only target one arbitrary animation, and each may + // inherit a different easeEach/animation ease that raw comparison misses. + const merged = deduplicateKeyframes([ + { percentage: 45, properties: { x: 10 }, ease: "power2.in", animationId: "#a-position" }, + { percentage: 45, properties: { opacity: 1 }, ease: "power2.in", animationId: "#a-visual" }, + ]); + expect(merged.find((k) => k.percentage === 45)?.easeAmbiguous).toBe(true); + }); + + it("does not flag a same-% collision within a single animation", () => { + const merged = deduplicateKeyframes([ + { percentage: 45, properties: { x: 10 }, ease: "power2.in", animationId: "#a-position" }, + { percentage: 45, properties: { y: 20 }, ease: "power2.out", animationId: "#a-position" }, + ]); + expect(merged.find((k) => k.percentage === 45)?.easeAmbiguous).toBeFalsy(); + }); +}); diff --git a/packages/studio/src/hooks/gsapTweenSynth.ts b/packages/studio/src/hooks/gsapTweenSynth.ts index edb849f28c..20daf0812f 100644 --- a/packages/studio/src/hooks/gsapTweenSynth.ts +++ b/packages/studio/src/hooks/gsapTweenSynth.ts @@ -5,14 +5,26 @@ import type { } from "@hyperframes/core/gsap-parser"; import { PROPERTY_DEFAULTS } from "./gsapShared"; -export function deduplicateKeyframes( - keyframes: GsapPercentageKeyframe[], -): GsapPercentageKeyframe[] { - const byPct = new Map(); +export function deduplicateKeyframes< + T extends GsapPercentageKeyframe & { animationId?: string; easeAmbiguous?: boolean }, +>(keyframes: T[]): T[] { + const byPct = new Map(); for (const kf of keyframes) { const existing = byPct.get(kf.percentage); if (existing) { existing.properties = { ...existing.properties, ...kf.properties }; + // Two DIFFERENT source animations with a keyframe at the same clip %: a + // single inline ease button can only target one of them, and which one is + // arbitrary (each may also inherit a different easeEach/animation ease, so + // comparing raw keyframe eases isn't enough). Flag it so the collapsed row + // hides the button there and the user edits per-lane instead. + if ( + existing.animationId !== undefined && + kf.animationId !== undefined && + existing.animationId !== kf.animationId + ) { + existing.easeAmbiguous = true; + } if (kf.ease) existing.ease = kf.ease; } else { byPct.set(kf.percentage, { ...kf, properties: { ...kf.properties } }); @@ -41,29 +53,40 @@ export function synthesizeFlatTweenKeyframes(anim: GsapAnimation): GsapKeyframes const fromProps = anim.fromProperties; if (!toProps || Object.keys(toProps).length === 0) return null; - const startProps: Record = {}; - const endProps: Record = {}; + const rawStart: Record = {}; + const rawEnd: Record = {}; if (anim.method === "from") { for (const [k, v] of Object.entries(toProps)) { - startProps[k] = v; - endProps[k] = PROPERTY_DEFAULTS[k] ?? 0; + rawStart[k] = v; + rawEnd[k] = PROPERTY_DEFAULTS[k] ?? 0; } } else if (anim.method === "fromTo" && fromProps) { - Object.assign(startProps, fromProps); - Object.assign(endProps, toProps); + Object.assign(rawStart, fromProps); + Object.assign(rawEnd, toProps); } else { for (const [k, v] of Object.entries(toProps)) { - startProps[k] = PROPERTY_DEFAULTS[k] ?? 0; - endProps[k] = v; + rawStart[k] = PROPERTY_DEFAULTS[k] ?? 0; + rawEnd[k] = v; } } + // Only numeric props are keyframe-interpolatable — a flat tween of a + // non-numeric prop (e.g. backgroundColor: "#fff") can't be a 2-keyframe lane. + const numericKeys = Object.keys(rawEnd).filter( + (k) => typeof rawStart[k] === "number" && typeof rawEnd[k] === "number", + ); + if (numericKeys.length === 0) return null; + const startProps = Object.fromEntries(numericKeys.map((k) => [k, rawStart[k]])); + const endProps = Object.fromEntries(numericKeys.map((k) => [k, rawEnd[k]])); + return { format: "percentage", keyframes: [ { percentage: 0, properties: startProps }, - { percentage: 100, properties: endProps }, + // Segment ease lives on the destination keyframe (Figma/AE model) so the + // lane + cache surface it; also kept data-level for useGsapTweenCache. + { percentage: 100, properties: endProps, ...(anim.ease ? { ease: anim.ease } : {}) }, ], ...(anim.ease ? { ease: anim.ease } : {}), }; diff --git a/packages/studio/src/hooks/timelineEditingHelpers.test.ts b/packages/studio/src/hooks/timelineEditingHelpers.test.ts index 5ac3b69204..03db5a2b9c 100644 --- a/packages/studio/src/hooks/timelineEditingHelpers.test.ts +++ b/packages/studio/src/hooks/timelineEditingHelpers.test.ts @@ -12,6 +12,7 @@ import { import type { TimelineElement } from "../player/store/playerStore"; import { usePlayerStore } from "../player/store/playerStore"; import type { CommitMutationOptions } from "./gsapScriptCommitTypes"; +import { timelineKeyframeSelectionKey } from "../player/components/timelineKeyframeIdentity"; afterEach(() => { usePlayerStore.getState().reset(); @@ -342,4 +343,51 @@ describe("deleteSelectedKeyframes", () => { expect(options[1]).not.toHaveProperty("softReload"); expect(options[2]).not.toHaveProperty("skipReload"); }); + + it("deletes two expanded lanes through their own animation and tween percentages", () => { + usePlayerStore.setState({ + selectedElementId: "card", + selectedKeyframes: new Set([ + timelineKeyframeSelectionKey("card", { + percentage: 30, + tweenPercentage: 20, + propertyGroup: "position", + animationId: "card-position", + }), + timelineKeyframeSelectionKey("card", { + percentage: 70, + tweenPercentage: 80, + propertyGroup: "visual", + animationId: "card-visual", + }), + ]), + }); + const handleGsapRemoveKeyframe = + vi.fn<(animId: string, pct: number, options?: Partial) => void>(); + + deleteSelectedKeyframes({ + selectedGsapAnimations: [ + { id: "card-position", keyframes: {} }, + { id: "card-visual", keyframes: {} }, + ], + handleGsapRemoveKeyframe, + }); + + expect(handleGsapRemoveKeyframe).toHaveBeenCalledTimes(2); + expect( + handleGsapRemoveKeyframe.mock.calls.map(([animationId, percentage]) => [ + animationId, + percentage, + ]), + ).toEqual([ + ["card-position", 20], + ["card-visual", 80], + ]); + expect(handleGsapRemoveKeyframe.mock.calls[0]?.[2]).toEqual( + expect.objectContaining({ skipReload: true }), + ); + expect(handleGsapRemoveKeyframe.mock.calls[1]?.[2]).toEqual( + expect.objectContaining({ softReload: true }), + ); + }); }); diff --git a/packages/studio/src/hooks/timelineMoveAdapter.ts b/packages/studio/src/hooks/timelineMoveAdapter.ts index f5b9b2fb65..ee7544e8ea 100644 --- a/packages/studio/src/hooks/timelineMoveAdapter.ts +++ b/packages/studio/src/hooks/timelineMoveAdapter.ts @@ -4,7 +4,7 @@ import type { TimelineGroupMoveChange, } from "./useTimelineGroupEditing"; -interface MoveEdit { +export interface TimelineMoveEdit { element: TimelineElement; updates: Pick; } @@ -18,8 +18,15 @@ interface AtomicMoveDeps { export type TimelineMoveOperation = "timing" | "lane-reorder" | "track-insert"; +export type TimelineMoveEditsHandler = ( + edits: TimelineMoveEdit[], + coalesceKey?: string, + operation?: TimelineMoveOperation, + coalesceMs?: number, +) => Promise; + export function persistTimelineMoveEditsAtomically( - edits: MoveEdit[], + edits: TimelineMoveEdit[], coalesceKey: string | undefined, operation: TimelineMoveOperation, deps: AtomicMoveDeps, diff --git a/packages/studio/src/hooks/useDomEditWiring.ts b/packages/studio/src/hooks/useDomEditWiring.ts index 19e21d29b6..b9468d510a 100644 --- a/packages/studio/src/hooks/useDomEditWiring.ts +++ b/packages/studio/src/hooks/useDomEditWiring.ts @@ -92,14 +92,14 @@ export interface UseDomEditWiringParams { animId: string, fromPercentage: number, toPercentage: number, - ) => void; + ) => Promise; resizeKeyframedTween: ( sel: DomEditSelection, animId: string, position: number, duration: number, pctRemap: Array<{ from: number; to: number }>, - ) => void; + ) => Promise; convertToKeyframes: ( sel: DomEditSelection, animId: string, diff --git a/packages/studio/src/hooks/useDomSelection.ts b/packages/studio/src/hooks/useDomSelection.ts index 903894c7e9..568c964228 100644 --- a/packages/studio/src/hooks/useDomSelection.ts +++ b/packages/studio/src/hooks/useDomSelection.ts @@ -24,6 +24,7 @@ import { type DomEditSelection, } from "../components/editor/domEditing"; import { reapplyPositionEditsAfterSeek } from "../components/editor/manualEdits"; +import { useStudioTestHooks } from "./useStudioTestHooks"; // ── Types ── @@ -506,6 +507,9 @@ export function useDomSelection({ applyDomSelection(null, { revealPanel: false }); }, [applyDomSelection, captionEditMode]); + // Dev-only headless-QA shortcut (window.__studioTest.selectByDomId). No-op in prod. + useStudioTestHooks({ previewIframeRef, buildDomSelectionFromTarget, applyDomSelection }); + const applyMarqueeSelection = useCallback( // fallow-ignore-next-line complexity (selections: DomEditSelection[], additive: boolean) => { diff --git a/packages/studio/src/hooks/useEnableKeyframes.test.ts b/packages/studio/src/hooks/useEnableKeyframes.test.ts index 3967edf518..6fc5a823cb 100644 --- a/packages/studio/src/hooks/useEnableKeyframes.test.ts +++ b/packages/studio/src/hooks/useEnableKeyframes.test.ts @@ -5,6 +5,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import type { GsapAnimation } from "@hyperframes/core/gsap-parser"; import type { DomEditSelection } from "../components/editor/domEditingTypes"; import { + applyArcKeyframeAtPlayhead, animatedProps, buildExtendedKeyframes, isPlayheadWithinTween, @@ -219,6 +220,114 @@ describe("promoteSetToKeyframes — auto endpoint", () => { }); }); +describe("applyArcKeyframeAtPlayhead", () => { + const arcAnim = anim({ + id: "#el-to-0-position", + position: 0, + duration: 10, + keyframes: { + format: "object-array", + keyframes: [ + { percentage: 0, properties: { x: 0, y: 0 } }, + { percentage: 50, properties: { x: 50, y: 50 } }, + { percentage: 100, properties: { x: 100, y: 0 } }, + ], + }, + arcPath: { + enabled: true, + autoRotate: false, + segments: [{ curviness: 1 }, { curviness: 1 }], + }, + }); + + function arcFixture(x: number, y: number) { + const commitMutation = vi.fn(async () => undefined); + const session = { commitMutation } as unknown as EnableKeyframesSession; + const sel = { + id: "el", + selector: "#el", + element: { isConnected: true } as HTMLElement, + dataAttributes: { duration: "10" }, + } as DomEditSelection; + const iframe = { + contentWindow: { + gsap: { getProperty: (_element: Element, property: string) => (property === "x" ? x : y) }, + }, + } as unknown as HTMLIFrameElement; + return { commitMutation, iframe, sel, session }; + } + + it("removes an existing interior stop without redistributing the remaining times", async () => { + const fixture = arcFixture(50, 50); + await applyArcKeyframeAtPlayhead(fixture.session, fixture.sel, arcAnim, 5, fixture.iframe); + expect(fixture.commitMutation).toHaveBeenCalledWith( + { + type: "replace-with-keyframes", + animationId: arcAnim.id, + targetSelector: "#el", + position: 0, + duration: 10, + keyframes: [ + { percentage: 0, properties: { x: 0, y: 0 } }, + { percentage: 100, properties: { x: 100, y: 0 } }, + ], + ease: "none", + }, + { label: "Remove keyframe", softReload: true }, + ); + }); + + it("preserves the path endpoints", async () => { + const fixture = arcFixture(0, 0); + await applyArcKeyframeAtPlayhead(fixture.session, fixture.sel, arcAnim, 0, fixture.iframe); + expect(fixture.commitMutation).not.toHaveBeenCalled(); + }); + + it("adds a temporal keyframe at the exact playhead while preserving authored times", async () => { + const fixture = arcFixture(25, 25); + await applyArcKeyframeAtPlayhead(fixture.session, fixture.sel, arcAnim, 2.5, fixture.iframe); + expect(fixture.commitMutation).toHaveBeenCalledWith( + { + type: "replace-with-keyframes", + animationId: arcAnim.id, + targetSelector: "#el", + position: 0, + duration: 10, + keyframes: [ + { percentage: 0, properties: { x: 0, y: 0 } }, + { percentage: 25, properties: { x: 25, y: 25 } }, + { percentage: 50, properties: { x: 50, y: 50 } }, + { percentage: 100, properties: { x: 100, y: 0 } }, + ], + ease: "none", + }, + { label: "Add keyframe", softReload: true }, + ); + }); + + it("uses the owning clip duration when an arc omits its outer duration", async () => { + const fixture = arcFixture(25, 25); + const durationlessArc = { ...arcAnim, duration: undefined }; + + await applyArcKeyframeAtPlayhead( + fixture.session, + fixture.sel, + durationlessArc, + 2.5, + fixture.iframe, + ); + + expect(fixture.commitMutation).toHaveBeenCalledWith( + expect.objectContaining({ + type: "replace-with-keyframes", + duration: 10, + keyframes: expect.arrayContaining([{ percentage: 25, properties: { x: 25, y: 25 } }]), + }), + { label: "Add keyframe", softReload: true }, + ); + }); +}); + function renderEnableKeyframes(session: EnableKeyframesSession): () => Promise { let enable: (() => Promise) | null = null; function Probe() { diff --git a/packages/studio/src/hooks/useEnableKeyframes.ts b/packages/studio/src/hooks/useEnableKeyframes.ts index 805af7bcb6..f55a8e49dd 100644 --- a/packages/studio/src/hooks/useEnableKeyframes.ts +++ b/packages/studio/src/hooks/useEnableKeyframes.ts @@ -12,16 +12,22 @@ import type { GsapAnimation, GsapPercentageKeyframe } from "@hyperframes/core/gs import type { DomEditSelection } from "../components/editor/domEditingTypes"; import { usePlayerStore } from "../player/store/playerStore"; import { fetchParsedAnimations, getAnimationsForElement } from "./useGsapTweenCache"; -import { selectorFromSelection, computeElementPercentage, isInstantHold } from "./gsapShared"; import { + selectorFromSelection, + computeElementPercentage, + isInstantHold, + resolveEditableTweenDuration, +} from "./gsapShared"; +import { + absoluteToPercentage, resolveTweenStart, resolveTweenDuration, isTimeWithinTween, } from "../utils/globalTimeCompiler"; import { POSITION_PROPS } from "./gsapRuntimeReaders"; import { roundTo3 } from "../utils/rounding"; -import { nearestPointOnPath } from "../components/editor/motionPathGeometry"; import type { CommitMutationOptions } from "./gsapScriptCommitTypes"; +import { buildTemporalArcKeyframes } from "./gsapDragPositionCommit"; let enableKeyframesTransactionCounter = 0; @@ -89,9 +95,10 @@ export function buildExtendedKeyframes( anim: GsapAnimation, currentTime: number, position: Record, + sourceDuration = resolveTweenDuration(anim), ): { position: number; duration: number; keyframes: GsapPercentageKeyframe[] } { const oldStart = resolveTweenStart(anim) ?? 0; - const oldDuration = resolveTweenDuration(anim); + const oldDuration = sourceDuration; const newStart = Math.min(oldStart, currentTime); const newEnd = Math.max(oldStart + oldDuration, currentTime); const newDuration = roundTo3(newEnd - newStart); @@ -222,6 +229,37 @@ async function fetchAnimationsForElement(sel: DomEditSelection): Promise, +): Promise { + const selector = selectorFromSelection(sel); + const position = readElementPosition(iframe, sel, anim); + if (!selector || Object.keys(position).length === 0 || !session.commitMutation) return; + const extended = buildExtendedKeyframes(anim, currentTime, position, duration); + await session.commitMutation( + { + type: "replace-with-keyframes", + animationId: anim.id, + targetSelector: selector, + position: extended.position, + duration: extended.duration, + keyframes: extended.keyframes, + ease: anim.ease, + }, + { + label: "Add keyframe", + softReload: true, + ...commitOverrides, + }, + ); +} + /** * Apply "add keyframe at playhead" to a tween that already has x/y keyframes: * toggle off an existing stop, add one at the playhead's tween-relative %, or — @@ -237,31 +275,22 @@ async function applyKeyframeAtPlayhead( iframe: HTMLIFrameElement | null, commitOverrides?: Partial, ): Promise { - if (!isPlayheadWithinTween(kfAnim, t)) { - const position = readElementPosition(iframe, sel, kfAnim); - const selector = selectorFromSelection(sel); - if (selector && Object.keys(position).length > 0 && session.commitMutation) { - const extended = buildExtendedKeyframes(kfAnim, t, position); - await session.commitMutation( - { - type: "replace-with-keyframes", - animationId: kfAnim.id, - targetSelector: selector, - position: extended.position, - duration: extended.duration, - keyframes: extended.keyframes, - ease: kfAnim.ease, - }, - { - label: "Add keyframe", - softReload: true, - ...commitOverrides, - }, - ); - } + const duration = resolveEditableTweenDuration(kfAnim, sel); + const start = resolveTweenStart(kfAnim); + if (start !== null && !isTimeWithinTween(t, start, duration)) { + await extendKeyframedTweenToPlayhead( + session, + sel, + kfAnim, + t, + duration, + iframe, + commitOverrides, + ); return; } - const pct = computeElementPercentage(t, sel, kfAnim); + const pct = + start === null ? computeElementPercentage(t, sel) : absoluteToPercentage(t, start, duration); const existing = kfAnim.keyframes?.keyframes.find((k) => Math.abs(k.percentage - pct) <= 1); if (existing) { session.handleGsapRemoveKeyframe(kfAnim.id, existing.percentage); @@ -332,14 +361,13 @@ export async function promoteSetToKeyframes( } /** - * An arc (motionPath) tween — its waypoints are reconstructed onto `keyframes`, so - * it must be edited as waypoints (not x/y keyframes, which would break the curve). - * "Add keyframe at playhead" drops a waypoint where the element currently sits on - * the path, inserted at the matching segment so the curve is preserved. Outside the - * range, extend the duration so the motion reaches the playhead. + * Convert an arc (motionPath) tween to temporal x/y keyframes before toggling the + * playhead stop. A toolbar command named "Add keyframe at playhead" must preserve + * every authored stop's time; inserting a spatial waypoint instead redistributes + * the path and can silently compress the animation. */ // fallow-ignore-next-line complexity -async function applyArcWaypointAtPlayhead( +export async function applyArcKeyframeAtPlayhead( session: EnableKeyframesSession, sel: DomEditSelection, arcAnim: GsapAnimation, @@ -347,8 +375,11 @@ async function applyArcWaypointAtPlayhead( iframe: HTMLIFrameElement | null, ): Promise { if (!session.commitMutation) return; - if (!isPlayheadWithinTween(arcAnim, t)) { - const start = resolveTweenStart(arcAnim) ?? 0; + const targetSelector = selectorFromSelection(sel); + if (!targetSelector) return; + const start = resolveTweenStart(arcAnim) ?? 0; + const duration = resolveEditableTweenDuration(arcAnim, sel); + if (!isTimeWithinTween(t, start, duration)) { if (t > start) { await session.commitMutation( { @@ -361,30 +392,45 @@ async function applyArcWaypointAtPlayhead( } return; } + const nodes = arcAnim.keyframes?.keyframes ?? []; + const playheadPercentage = absoluteToPercentage(t, start, duration); + const timedNodeIndex = nodes.findIndex( + (node) => Math.abs(node.percentage - playheadPercentage) <= 1, + ); + if (timedNodeIndex !== -1) { + if (timedNodeIndex > 0 && timedNodeIndex < nodes.length - 1) { + await session.commitMutation( + { + type: "replace-with-keyframes", + animationId: arcAnim.id, + targetSelector, + position: roundTo3(start), + duration: roundTo3(duration), + keyframes: nodes.filter((_, index) => index !== timedNodeIndex), + ease: "none", + }, + { label: "Remove keyframe", softReload: true }, + ); + } + return; + } + const live = readElementPosition(iframe, sel, arcAnim); if (typeof live.x !== "number" || typeof live.y !== "number") return; - const liveX = live.x; - const liveY = live.y; - const nodes = (arcAnim.keyframes?.keyframes ?? []) - .map((k) => ({ x: k.properties.x, y: k.properties.y })) - .filter( - (p): p is { x: number; y: number } => typeof p.x === "number" && typeof p.y === "number", - ); - // Don't duplicate a waypoint that already sits where the element is (e.g. at the - // path endpoints). - const WAYPOINT_MERGE_PX = 6; - if (nodes.some((n) => Math.hypot(n.x - liveX, n.y - liveY) <= WAYPOINT_MERGE_PX)) return; - const proj = nearestPointOnPath(liveX, liveY, nodes); - if (!proj) return; await session.commitMutation( { - type: "add-motion-path-point", + type: "replace-with-keyframes", animationId: arcAnim.id, - index: proj.segIndex + 1, - x: liveX, - y: liveY, + targetSelector, + position: roundTo3(start), + duration: roundTo3(duration), + keyframes: buildTemporalArcKeyframes(arcAnim, playheadPercentage, { + x: live.x, + y: live.y, + }), + ease: "none", }, - { label: "Add waypoint", softReload: true }, + { label: "Add keyframe", softReload: true }, ); } @@ -420,7 +466,7 @@ export function useEnableKeyframes( const flatAnim = anims.find((a) => !a.keyframes && !a.arcPath && !isInstantHold(a)); if (arcAnim) { - await applyArcWaypointAtPlayhead(session, sel, arcAnim, t, iframe); + await applyArcKeyframeAtPlayhead(session, sel, arcAnim, t, iframe); } else if (kfAnim) { await applyKeyframeAtPlayhead(session, sel, kfAnim, t, iframe); } else if (setAnim) { diff --git a/packages/studio/src/hooks/useGestureCommit.ts b/packages/studio/src/hooks/useGestureCommit.ts index a0aba6747f..cdc51dcf97 100644 --- a/packages/studio/src/hooks/useGestureCommit.ts +++ b/packages/studio/src/hooks/useGestureCommit.ts @@ -13,7 +13,7 @@ import type { GsapAnimation } from "@hyperframes/core/gsap-parser"; import type { CommitMutationOptions } from "./gsapScriptCommitTypes"; import { roundTo3 } from "../utils/rounding"; import { classifyPropertyGroup } from "@hyperframes/core/gsap-parser"; -import { isInstantHold } from "./gsapShared"; +import { isInstantHold, idSelector } from "./gsapShared"; type RecordedKeyframe = { percentage: number; @@ -168,7 +168,7 @@ export function useGestureCommit({ if (!sortedPcts.includes(0)) sortedPcts.unshift(0); } - const selector = sel.id ? `#${sel.id}` : sel.selector; + const selector = sel.id ? idSelector(sel.id) : sel.selector; if (!selector) { showToast("Cannot save — element has no selector", "error"); return; diff --git a/packages/studio/src/hooks/useGsapKeyframeOps.test.tsx b/packages/studio/src/hooks/useGsapKeyframeOps.test.tsx index e697ab6127..6017353d08 100644 --- a/packages/studio/src/hooks/useGsapKeyframeOps.test.tsx +++ b/packages/studio/src/hooks/useGsapKeyframeOps.test.tsx @@ -19,11 +19,21 @@ afterEach(() => { const selection: DomEditSelection = { id: "box", selector: "#box" } as DomEditSelection; +function successfulCommitMutation() { + return vi.fn<(...args: unknown[]) => Promise>(async (...args) => { + const options = args[2] as { + onResult?: (result: { ok: boolean; changed: boolean }) => void; + }; + options.onResult?.({ ok: true, changed: true }); + }); +} + function renderKeyframeOps(over: { commitMutation: (...args: unknown[]) => Promise; trackGsapSaveFailure: (...args: unknown[]) => void; }) { const captured: { api: HookApi | null } = { api: null }; + // This hook harness intentionally mirrors the separate script-commit harness. function Probe() { // fallow-ignore-next-line code-duplication captured.api = useGsapKeyframeOps({ @@ -49,11 +59,21 @@ function renderKeyframeOps(over: { return captured.api; } +async function moveKeyframeWith( + commitMutation: (...args: unknown[]) => Promise, +): Promise<{ committed: boolean; trackGsapSaveFailure: ReturnType }> { + const trackGsapSaveFailure = vi.fn(); + const api = renderKeyframeOps({ commitMutation, trackGsapSaveFailure }); + let committed = true; + await act(async () => { + committed = await api.moveKeyframe(selection, "box-to-0-position", 50, 75); + }); + return { committed, trackGsapSaveFailure }; +} + describe("useGsapKeyframeOps — resizeKeyframedTween", () => { it("issues a resize-keyframed-tween mutation with the remap + window", async () => { - const commitMutation = vi.fn<(...args: unknown[]) => Promise>(async () => ({ - ok: true, - })); + const commitMutation = successfulCommitMutation(); const trackGsapSaveFailure = vi.fn<(...args: unknown[]) => void>(); const api = renderKeyframeOps({ commitMutation, trackGsapSaveFailure }); @@ -61,8 +81,9 @@ describe("useGsapKeyframeOps — resizeKeyframedTween", () => { { from: 0, to: 0 }, { from: 100, to: 100 }, ]; + let committed = false; await act(async () => { - api.resizeKeyframedTween(selection, "box-to-0-opacity", 0.2, 2, pctRemap); + committed = await api.resizeKeyframedTween(selection, "box-to-0-opacity", 0.2, 2, pctRemap); }); expect(commitMutation).toHaveBeenCalledTimes(1); @@ -76,6 +97,7 @@ describe("useGsapKeyframeOps — resizeKeyframedTween", () => { pctRemap, }); expect(trackGsapSaveFailure).not.toHaveBeenCalled(); + expect(committed).toBe(true); }); it("routes a rejected commit to trackGsapSaveFailure (no unhandled rejection)", async () => { @@ -86,10 +108,11 @@ describe("useGsapKeyframeOps — resizeKeyframedTween", () => { const trackGsapSaveFailure = vi.fn<(...args: unknown[]) => void>(); const api = renderKeyframeOps({ commitMutation, trackGsapSaveFailure }); + let committed = true; await act(async () => { - api.resizeKeyframedTween(selection, "box-to-0-opacity", 0.2, 2, [{ from: 100, to: 100 }]); - // let the rejected commit promise settle inside act - await Promise.resolve(); + committed = await api.resizeKeyframedTween(selection, "box-to-0-opacity", 0.2, 2, [ + { from: 100, to: 100 }, + ]); }); expect(trackGsapSaveFailure).toHaveBeenCalledTimes(1); @@ -98,14 +121,72 @@ describe("useGsapKeyframeOps — resizeKeyframedTween", () => { expect(selArg).toBe(selection); expect((mutationArg as { type: string }).type).toBe("resize-keyframed-tween"); expect(labelArg).toBe("Retime keyframe (resize tween)"); + expect(committed).toBe(false); + }); +}); + +describe("useGsapKeyframeOps — moveKeyframe settlement", () => { + it("returns false when the commit settles without a durable writer result", async () => { + const { committed, trackGsapSaveFailure } = await moveKeyframeWith(vi.fn(async () => {})); + + expect(committed).toBe(false); + expect(trackGsapSaveFailure).not.toHaveBeenCalled(); + }); + + it("returns false when the writer accepts but does not change the keyframe", async () => { + const commitMutation = vi.fn(async (...args: unknown[]) => { + const options = args[2] as { onResult?: (result: { ok: boolean; changed: boolean }) => void }; + options.onResult?.({ ok: true, changed: false }); + }); + const { committed, trackGsapSaveFailure } = await moveKeyframeWith(commitMutation); + + expect(committed).toBe(false); + expect(trackGsapSaveFailure).not.toHaveBeenCalled(); + }); + + it("returns false and tracks a rejected move", async () => { + const error = new Error("write failed"); + const commitMutation = vi.fn().mockRejectedValue(error); + const { committed, trackGsapSaveFailure } = await moveKeyframeWith(commitMutation); + + expect(committed).toBe(false); + expect(trackGsapSaveFailure).toHaveBeenCalledExactlyOnceWith( + error, + selection, + { + type: "move-keyframe", + animationId: "box-to-0-position", + fromPercentage: 50, + toPercentage: 75, + }, + "Move keyframe to 75%", + ); }); }); describe("useGsapKeyframeOps — keyframe transaction options", () => { + it("routes a flat-lane add through the add-keyframe writer mutation", async () => { + const commitMutation = successfulCommitMutation(); + const api = renderKeyframeOps({ commitMutation, trackGsapSaveFailure: vi.fn() }); + + await act(async () => { + await api.addKeyframeBatch(selection, "box-to-0-position", 50, { x: 210 }); + }); + + expect(commitMutation).toHaveBeenCalledWith( + selection, + { + type: "add-keyframe", + animationId: "box-to-0-position", + percentage: 50, + properties: { x: 210 }, + }, + { label: "Add keyframe at 50%", softReload: true }, + ); + }); + it("soft-reloads a standalone convert when the SDK path is unavailable", async () => { - const commitMutation = vi.fn<(...args: unknown[]) => Promise>(async () => ({ - ok: true, - })); + const commitMutation = successfulCommitMutation(); const api = renderKeyframeOps({ commitMutation, trackGsapSaveFailure: vi.fn() }); await act(async () => { @@ -123,9 +204,7 @@ describe("useGsapKeyframeOps — keyframe transaction options", () => { }); it("threads one coalesce key through skipped convert reload and terminal batch edit", async () => { - const commitMutation = vi.fn<(...args: unknown[]) => Promise>(async () => ({ - ok: true, - })); + const commitMutation = successfulCommitMutation(); const api = renderKeyframeOps({ commitMutation, trackGsapSaveFailure: vi.fn() }); const coalesceKey = "enable-keyframes:box-to-0-opacity:1"; diff --git a/packages/studio/src/hooks/useGsapKeyframeOps.ts b/packages/studio/src/hooks/useGsapKeyframeOps.ts index 69107c64bd..b2a9ee3ba9 100644 --- a/packages/studio/src/hooks/useGsapKeyframeOps.ts +++ b/packages/studio/src/hooks/useGsapKeyframeOps.ts @@ -236,7 +236,7 @@ export function useGsapKeyframeOps({ ); const moveKeyframe = useCallback( - ( + async ( selection: DomEditSelection, animationId: string, fromPercentage: number, @@ -247,18 +247,26 @@ export function useGsapKeyframeOps({ // updateKeyframeCacheFromParsed re-keys the diamond from the fresh parse, so no // optimistic cache write is needed (mapping the tween-% to clip-% here would // duplicate that math). softReload mirrors remove-keyframe. - void commitMutation(selection, mutation, { - label: `Move keyframe to ${toPercentage}%`, - softReload: true, - }).catch((error) => { + try { + let changed = false; + await commitMutation(selection, mutation, { + label: `Move keyframe to ${toPercentage}%`, + softReload: true, + onResult: (result) => { + changed = result.changed !== false; + }, + }); + return changed; + } catch (error) { trackGsapSaveFailure(error, selection, mutation, `Move keyframe to ${toPercentage}%`); - }); + return false; + } }, [commitMutation, trackGsapSaveFailure], ); const resizeKeyframedTween = useCallback( - ( + async ( selection: DomEditSelection, animationId: string, position: number, @@ -275,12 +283,20 @@ export function useGsapKeyframeOps({ // Boundary drag-to-retime: the server re-keys keyframes in place + grows the // tween window, preserving _auto / per-keyframe ease / easeEach / outer ease. // softReload re-keys the diamonds from the fresh parse (mirrors moveKeyframe). - void commitMutation(selection, mutation, { - label: "Retime keyframe (resize tween)", - softReload: true, - }).catch((error) => { + try { + let changed = false; + await commitMutation(selection, mutation, { + label: "Retime keyframe (resize tween)", + softReload: true, + onResult: (result) => { + changed = result.changed !== false; + }, + }); + return changed; + } catch (error) { trackGsapSaveFailure(error, selection, mutation, "Retime keyframe (resize tween)"); - }); + return false; + } }, [commitMutation, trackGsapSaveFailure], ); diff --git a/packages/studio/src/hooks/useGsapScriptCommits.test.tsx b/packages/studio/src/hooks/useGsapScriptCommits.test.tsx index 869807eb8a..6236d032ab 100644 --- a/packages/studio/src/hooks/useGsapScriptCommits.test.tsx +++ b/packages/studio/src/hooks/useGsapScriptCommits.test.tsx @@ -298,6 +298,27 @@ describe("runCommit — instantPatch wiring", () => { expect(deps.showToast).toHaveBeenCalledWith("A keyframe already exists at that time", "info"); }); + it("publishes the server mutation outcome to callers", async () => { + mockFetchResult({ changed: false }); + const deps = renderCommitHook(); + let commitResult: MutationResult | undefined; + + await act(async () => { + await deps.api.commitMutation( + selection, + { type: "move-keyframe", fromPercentage: 50, toPercentage: 75 }, + { + label: "Move keyframe", + onResult: (result) => { + commitResult = result; + }, + }, + ); + }); + + expect(commitResult).toEqual(expect.objectContaining({ ok: true, changed: false })); + }); + it("no-op commit with an instantPatch still patches the runtime (paired x/y commits)", async () => { patchRuntimeTweenInPlace.mockReturnValue(true); mockFetchResult({ changed: false }); diff --git a/packages/studio/src/hooks/useGsapScriptCommits.ts b/packages/studio/src/hooks/useGsapScriptCommits.ts index f43d42e91b..566d2bc538 100644 --- a/packages/studio/src/hooks/useGsapScriptCommits.ts +++ b/packages/studio/src/hooks/useGsapScriptCommits.ts @@ -338,6 +338,7 @@ export function useGsapScriptCommits({ projectIdRef, activeCompPath, previewIfra mutateGsapScript(pid, targetPath, mutation), ); if (!result) return; + options.onResult?.(result); await finalizeSuccessfulMutation(pid, compositionPath, selection, mutation, targetPath, result, options); }, [showToast, finalizeSuccessfulMutation]); @@ -350,6 +351,7 @@ export function useGsapScriptCommits({ projectIdRef, activeCompPath, previewIfra mutateGsapScriptBatch(pid, targetPath, mutations), ); if (!result) return; + options.onResult?.(result); await finalizeSuccessfulMutation(pid, compositionPath, last.selection, last.mutation, targetPath, result, options); }, [showToast, finalizeSuccessfulMutation]); diff --git a/packages/studio/src/hooks/useGsapSelectionHandlers.test.tsx b/packages/studio/src/hooks/useGsapSelectionHandlers.test.tsx index f1ae419ec9..3e4c8ea72a 100644 --- a/packages/studio/src/hooks/useGsapSelectionHandlers.test.tsx +++ b/packages/studio/src/hooks/useGsapSelectionHandlers.test.tsx @@ -37,8 +37,8 @@ function makeParams(overrides: Partial = {}): Params { addKeyframe: vi.fn(), addKeyframeBatch: resolved(), removeKeyframe: vi.fn(), - moveKeyframe: vi.fn(), - resizeKeyframedTween: vi.fn(), + moveKeyframe: vi.fn().mockResolvedValue(true), + resizeKeyframedTween: vi.fn().mockResolvedValue(true), convertToKeyframes: resolved(), removeAllKeyframes: resolved(), handleDomManualEditsReset: vi.fn(), @@ -114,3 +114,22 @@ describe("useGsapSelectionHandlers save failures", () => { rendered.unmount(); }); }); + +describe("useGsapSelectionHandlers retime settlement", () => { + it("returns false without a selection and forwards the mutation result with one", async () => { + const moveKeyframe = vi.fn().mockResolvedValue(true); + const withoutSelection = renderHandlers(makeParams({ domEditSelection: null, moveKeyframe })); + await expect( + withoutSelection.handlers().handleGsapMoveKeyframe("anim-1", 50, 75), + ).resolves.toBe(false); + expect(moveKeyframe).not.toHaveBeenCalled(); + withoutSelection.unmount(); + + const withSelection = renderHandlers(makeParams({ moveKeyframe })); + await expect(withSelection.handlers().handleGsapMoveKeyframe("anim-1", 50, 75)).resolves.toBe( + true, + ); + expect(moveKeyframe).toHaveBeenCalledOnce(); + withSelection.unmount(); + }); +}); diff --git a/packages/studio/src/hooks/useGsapSelectionHandlers.ts b/packages/studio/src/hooks/useGsapSelectionHandlers.ts index 0b11d760de..ca261cb11c 100644 --- a/packages/studio/src/hooks/useGsapSelectionHandlers.ts +++ b/packages/studio/src/hooks/useGsapSelectionHandlers.ts @@ -94,14 +94,14 @@ export function useGsapSelectionHandlers({ animId: string, fromPercentage: number, toPercentage: number, - ) => void; + ) => Promise; resizeKeyframedTween: ( sel: DomEditSelection, animId: string, position: number, duration: number, pctRemap: Array<{ from: number; to: number }>, - ) => void; + ) => Promise; convertToKeyframes: ( sel: DomEditSelection, animId: string, @@ -173,8 +173,8 @@ export function useGsapSelectionHandlers({ ); const handleGsapDeleteAnimation = useCallback( - (animId: string) => { - const sel = domEditSelection ?? lastSelectionRef.current; + (animId: string, selectionOverride?: DomEditSelection | null) => { + const sel = selectionOverride ?? domEditSelection ?? lastSelectionRef.current; if (!sel) return; observeGsapMutation(deleteGsapAnimation(sel, animId), sel, "delete", "Delete GSAP animation"); }, @@ -298,17 +298,15 @@ export function useGsapSelectionHandlers({ percentage: number, properties: Record, commitOverrides?: Partial, + selectionOverride?: DomEditSelection | null, ) => { - if (!domEditSelection) return Promise.resolve(); - return addKeyframeBatch( - domEditSelection, - animId, - percentage, - properties, - commitOverrides, - ).catch((error) => { - trackGsapHandlerFailure(error, domEditSelection, "add-keyframe", "Add keyframe"); - }); + const sel = selectionOverride ?? domEditSelection ?? lastSelectionRef.current; + if (!sel) return Promise.resolve(); + return addKeyframeBatch(sel, animId, percentage, properties, commitOverrides).catch( + (error) => { + trackGsapHandlerFailure(error, sel, "add-keyframe", "Add keyframe"); + }, + ); }, [domEditSelection, addKeyframeBatch, trackGsapHandlerFailure], ); @@ -328,15 +326,20 @@ export function useGsapSelectionHandlers({ ); const handleGsapMoveKeyframeToPlayhead = useCallback( - (animId: string, fromPercentage: number, selectionOverride?: DomEditSelection | null) => { + ( + animId: string, + fromPercentage: number, + selectionOverride?: DomEditSelection | null, + animationOverride?: GsapAnimation, + ) => { const sel = selectionOverride ?? domEditSelection ?? lastSelectionRef.current; if (!sel) return; // Retime the keyframe to the playhead, preserving its value + ease. The // playhead's tween-relative percentage is the move target. - const anim = selectedGsapAnimations.find((a) => a.id === animId); + const anim = animationOverride ?? selectedGsapAnimations.find((a) => a.id === animId); const toPercentage = computeCurrentPercentage(sel, anim); trackStudioEvent("keyframe", { action: "move_to_playhead" }); - moveKeyframe(sel, animId, fromPercentage, toPercentage); + void moveKeyframe(sel, animId, fromPercentage, toPercentage); }, [domEditSelection, selectedGsapAnimations, moveKeyframe], ); @@ -349,13 +352,13 @@ export function useGsapSelectionHandlers({ selectionOverride?: DomEditSelection | null, ) => { const sel = selectionOverride ?? domEditSelection ?? lastSelectionRef.current; - if (!sel) return; + if (!sel) return Promise.resolve(false); // Atomic retime: preserves the keyframe's value + per-keyframe ease. Both // percentages are tween-relative (the drag handler converts the drop // position before calling). No optimistic runtime hold — the soft-reload // re-keys the diamond from source. trackStudioEvent("keyframe", { action: "retime" }); - moveKeyframe(sel, animId, fromPercentage, toPercentage); + return moveKeyframe(sel, animId, fromPercentage, toPercentage); }, [domEditSelection, moveKeyframe], ); @@ -369,11 +372,11 @@ export function useGsapSelectionHandlers({ selectionOverride?: DomEditSelection | null, ) => { const sel = selectionOverride ?? domEditSelection ?? lastSelectionRef.current; - if (!sel) return; + if (!sel) return Promise.resolve(false); // Boundary drag-to-retime: grows/shifts the tween window + re-keys keyframes // in place. Distinct telemetry action so resize is separable from in-window move. trackStudioEvent("keyframe", { action: "retime_resize" }); - resizeKeyframedTween(sel, animId, position, duration, pctRemap); + return resizeKeyframedTween(sel, animId, position, duration, pctRemap); }, [domEditSelection, resizeKeyframedTween], ); @@ -405,11 +408,12 @@ export function useGsapSelectionHandlers({ ); const handleGsapRemoveAllKeyframes = useCallback( - (animId: string) => { - if (!domEditSelection) return; + (animId: string, selectionOverride?: DomEditSelection | null) => { + const selection = selectionOverride ?? domEditSelection ?? lastSelectionRef.current; + if (!selection) return; observeGsapMutation( - removeAllKeyframes(domEditSelection, animId), - domEditSelection, + removeAllKeyframes(selection, animId), + selection, "remove-all-keyframes", "Remove all keyframes", ); diff --git a/packages/studio/src/hooks/useGsapTweenCache.ts b/packages/studio/src/hooks/useGsapTweenCache.ts index 226ec4c194..6a8e9d5481 100644 --- a/packages/studio/src/hooks/useGsapTweenCache.ts +++ b/packages/studio/src/hooks/useGsapTweenCache.ts @@ -6,6 +6,7 @@ import { readRuntimeKeyframes, scanAllRuntimeKeyframes } from "./gsapRuntimeBrid import { clearKeyframeCacheForElement, clearKeyframeCacheForFile, + writeGsapAnimationsForElement, } from "./gsapKeyframeCacheHelpers"; import { toAbsoluteTime } from "./gsapShared"; import { deduplicateKeyframes, synthesizeFlatTweenKeyframes } from "./gsapTweenSynth"; @@ -328,6 +329,12 @@ export function useGsapAnimationsForElement( // fallow-ignore-next-line complexity useEffect(() => { if (!elementId) return; + const sourceAnimations = animations.filter( + (animation) => + animation.propertyGroup && (animation.keyframes || synthesizeFlatTweenKeyframes(animation)), + ); + if (sourceAnimations.length > 0) + writeGsapAnimationsForElement(sourceFile, elementId, sourceAnimations); // Resolve the element's time range from the player store so we can // convert tween-relative keyframe percentages to clip-relative ones. @@ -340,7 +347,11 @@ export function useGsapAnimationsForElement( ); const allKeyframes: Array< - GsapKeyframesData["keyframes"][0] & { tweenPercentage?: number; propertyGroup?: string } + GsapKeyframesData["keyframes"][0] & { + tweenPercentage?: number; + propertyGroup?: string; + animationId?: string; + } > = []; let format: GsapKeyframesData["format"] = "percentage"; let ease: string | undefined; @@ -378,6 +389,7 @@ export function useGsapAnimationsForElement( percentage: clipPct, tweenPercentage: k.percentage, propertyGroup: anim.propertyGroup, + animationId: anim.id, }); } format = kf.format; @@ -459,6 +471,7 @@ export function usePopulateKeyframeCacheForFile( const { elements, domClipChildren } = usePlayerStore.getState(); const doc = iframeRef?.current?.contentDocument; const mergedByElement = new Map(); + const sourceByElement = new Map(); for (const anim of parsed.animations) { if (anim.hasUnresolvedKeyframes) continue; // Position-only static holds are not keyframed animations — skip them so @@ -479,12 +492,16 @@ export function usePopulateKeyframeCacheForFile( // Attribute the tween to every element it animates (handles class / // group / descendant selectors, not just `#id`). for (const id of resolveSelectorElementIds(anim.targetSelector, doc)) { + // kfData is already resolved (real keyframes OR a synthesized flat + // tween), so a grouped flat tween joins the store like a keyframed one. + if (anim.propertyGroup) { + sourceByElement.set(id, [...(sourceByElement.get(id) ?? []), anim]); + } const { elStart, elDuration } = resolveClipTimingBasis(id, sf, elements, domClipChildren); const clipKeyframes = kfData.keyframes.map((kf) => { const absTime = toAbsoluteTime(tweenPos, tweenDur, kf.percentage); - // 0.001% precision (matching useGsapAnimationsForElement above) so a - // beat-snapped keyframe centers exactly on the beat dot and the two - // caches agree on a keyframe's percentage. + // 0.001% precision (see useGsapAnimationsForElement) so a beat-snapped + // keyframe centers on the beat dot and both caches agree. const clipPct = elDuration > 0 ? Math.round(((absTime - elStart) / elDuration) * 100000) / 1000 @@ -494,6 +511,7 @@ export function usePopulateKeyframeCacheForFile( percentage: clipPct, tweenPercentage: kf.percentage, propertyGroup: anim.propertyGroup, + animationId: anim.id, // parity with other cache writers; inline ease needs it }; }); const existing = mergedByElement.get(id); @@ -508,6 +526,7 @@ export function usePopulateKeyframeCacheForFile( setKeyframeCache(`${sf}#${id}`, kfData); setKeyframeCache(id, kfData); if (sf !== "index.html") setKeyframeCache(`index.html#${id}`, kfData); + writeGsapAnimationsForElement(sf, id, sourceByElement.get(id)); } astFetchDoneRef.current = fetchKey; }); diff --git a/packages/studio/src/hooks/useStudioContextValue.test.ts b/packages/studio/src/hooks/useStudioContextValue.test.ts new file mode 100644 index 0000000000..01228d92ed --- /dev/null +++ b/packages/studio/src/hooks/useStudioContextValue.test.ts @@ -0,0 +1,93 @@ +// @vitest-environment happy-dom + +import React from "react"; +import { renderToStaticMarkup } from "react-dom/server"; +import { describe, expect, it } from "vitest"; +import type { DomEditSelection } from "../components/editor/domEditing"; +import type { RightInspectorPanes } from "../utils/studioHelpers"; +import { makeSelection } from "./domSelectionTestHarness"; +import { useInspectorState, type InspectorState } from "./useStudioContextValue"; + +interface HarnessProps { + rightPanelTab: string; + rightInspectorPanes: RightInspectorPanes; + rightCollapsed: boolean; + isPlaying: boolean; + isGestureRecording: boolean; + domEditSelection: DomEditSelection | null; +} + +function renderInspectorState(props: HarnessProps): InspectorState { + let state: InspectorState | null = null; + + function Harness() { + state = useInspectorState( + props.rightPanelTab, + props.rightInspectorPanes, + props.rightCollapsed, + props.isPlaying, + props.domEditSelection, + props.isGestureRecording, + ); + return null; + } + + renderToStaticMarkup(React.createElement(Harness)); + if (!state) throw new Error("Expected inspector state"); + return state; +} + +function selectedProps( + overrides: Partial = {}, +): HarnessProps & { domEditSelection: DomEditSelection } { + const element = document.createElement("div"); + return { + rightPanelTab: "renders", + rightInspectorPanes: { layers: false, design: false }, + rightCollapsed: true, + isPlaying: false, + isGestureRecording: false, + domEditSelection: makeSelection("Selected", element), + ...overrides, + }; +} + +describe("useInspectorState", () => { + it("shows the motion path for pure selection with the inspector collapsed", () => { + expect(renderInspectorState(selectedProps()).shouldShowMotionPath).toBe(true); + }); + + it("hides the motion path without a selection", () => { + expect( + renderInspectorState({ ...selectedProps(), domEditSelection: null }).shouldShowMotionPath, + ).toBe(false); + }); + + it("hides the motion path during playback", () => { + expect(renderInspectorState(selectedProps({ isPlaying: true })).shouldShowMotionPath).toBe( + false, + ); + }); + + it("hides the motion path during gesture recording", () => { + expect( + renderInspectorState(selectedProps({ isGestureRecording: true })).shouldShowMotionPath, + ).toBe(false); + }); + + it("keeps selected DOM bounds coupled to the inspector or variables panel", () => { + expect(renderInspectorState(selectedProps()).shouldShowSelectedDomBounds).toBe(false); + expect( + renderInspectorState( + selectedProps({ + rightPanelTab: "design", + rightInspectorPanes: { layers: false, design: true }, + }), + ).shouldShowSelectedDomBounds, + ).toBe(true); + expect( + renderInspectorState(selectedProps({ rightPanelTab: "variables" })) + .shouldShowSelectedDomBounds, + ).toBe(true); + }); +}); diff --git a/packages/studio/src/hooks/useStudioContextValue.ts b/packages/studio/src/hooks/useStudioContextValue.ts index 460028bdfb..21ba371f73 100644 --- a/packages/studio/src/hooks/useStudioContextValue.ts +++ b/packages/studio/src/hooks/useStudioContextValue.ts @@ -1,5 +1,6 @@ import { useCallback, useMemo, useRef, useState, type DragEvent } from "react"; import { STUDIO_INSPECTOR_PANELS_ENABLED } from "../components/editor/manualEditingAvailability"; +import type { DomEditSelection } from "../components/editor/domEditing"; import type { StudioContextValue } from "../contexts/StudioContext"; import type { RightInspectorPanes } from "../utils/studioHelpers"; import type { TimelineFileDropHandler } from "./useTimelineEditingTypes"; @@ -69,6 +70,7 @@ export interface InspectorState { designPanelActive: boolean; inspectorPanelActive: boolean; inspectorButtonActive: boolean; + shouldShowMotionPath: boolean; shouldShowSelectedDomBounds: boolean; } @@ -77,6 +79,7 @@ export function useInspectorState( rightInspectorPanes: RightInspectorPanes, rightCollapsed: boolean, isPlaying: boolean, + domEditSelection: DomEditSelection | null, isGestureRecording?: boolean, ): InspectorState { // fallow-ignore-next-line complexity @@ -93,8 +96,9 @@ export function useInspectorState( inspectorPanelActive, inspectorButtonActive: STUDIO_INSPECTOR_PANELS_ENABLED && !rightCollapsed && inspectorPanelActive, - // Keep the selection box + motion path drawn even when the Inspector is - // collapsed — closing the panel shouldn't visually deselect the element. + shouldShowMotionPath: !!domEditSelection && !isPlaying && !isGestureRecording, + // Keep the selection box drawn even when the Inspector is collapsed — + // closing the panel shouldn't visually deselect the element. // The Variables tab also works against the canvas selection (bind card), // so the selection outline stays visible there too. shouldShowSelectedDomBounds: @@ -102,7 +106,14 @@ export function useInspectorState( !isPlaying && !isGestureRecording, }; - }, [rightPanelTab, rightInspectorPanes, rightCollapsed, isPlaying, isGestureRecording]); + }, [ + rightPanelTab, + rightInspectorPanes, + rightCollapsed, + isPlaying, + isGestureRecording, + domEditSelection, + ]); } // fallow-ignore-next-line complexity diff --git a/packages/studio/src/hooks/useStudioTestHooks.ts b/packages/studio/src/hooks/useStudioTestHooks.ts new file mode 100644 index 0000000000..2e0023e550 --- /dev/null +++ b/packages/studio/src/hooks/useStudioTestHooks.ts @@ -0,0 +1,61 @@ +import { useEffect } from "react"; +import type { DomEditSelection } from "../components/editor/domEditing"; + +interface StudioTestHookDeps { + previewIframeRef: React.MutableRefObject; + buildDomSelectionFromTarget: (target: HTMLElement) => Promise; + applyDomSelection: ( + selection: DomEditSelection | null, + options?: { revealPanel?: boolean }, + ) => void; +} + +interface StudioTestApi { + selectByDomId: (id: string) => Promise; +} + +declare global { + interface Window { + __studioTest?: StudioTestApi; + } +} + +/** + * Dev-only headless-QA shortcut. Selecting an element normally requires a + * pixel-precise click inside the preview iframe, which automated verification + * can't reliably land. `window.__studioTest.selectByDomId(id)` resolves the + * DomEditSelection for a preview element by id and reveals the inspector — + * exactly what a click does — so a driver can open the property/ease panels and + * then focus a segment via `__playerStore.getState().setFocusedEaseSegment`. + * No-op in production builds. + */ +export function useStudioTestHooks({ + previewIframeRef, + buildDomSelectionFromTarget, + applyDomSelection, +}: StudioTestHookDeps): void { + // eslint-disable-next-line no-restricted-syntax + useEffect(() => { + let isDev = false; + try { + isDev = import.meta.env.DEV === true; + } catch { + isDev = false; + } + if (!isDev || typeof window === "undefined") return; + const api: StudioTestApi = { + selectByDomId: async (id: string): Promise => { + const element = previewIframeRef.current?.contentDocument?.getElementById(id) ?? null; + if (!element) return false; + const selection = await buildDomSelectionFromTarget(element); + if (!selection) return false; + applyDomSelection(selection, { revealPanel: true }); + return true; + }, + }; + window.__studioTest = api; + return () => { + window.__studioTest = undefined; + }; + }, [applyDomSelection, buildDomSelectionFromTarget, previewIframeRef]); +} diff --git a/packages/studio/src/hooks/useTimelineEditing.test.tsx b/packages/studio/src/hooks/useTimelineEditing.test.tsx index bc88aca67d..0426dc4b13 100644 --- a/packages/studio/src/hooks/useTimelineEditing.test.tsx +++ b/packages/studio/src/hooks/useTimelineEditing.test.tsx @@ -10,6 +10,17 @@ import { jsonResponse, requestUrl } from "./fetchStubTestUtils"; import { useElementLifecycleOps } from "./useElementLifecycleOps"; import { useTimelineEditing } from "./useTimelineEditing"; +vi.mock("../components/editor/manualEditingAvailability", async (importOriginal) => { + const actual = + await importOriginal(); + return { + ...actual, + STUDIO_SDK_CUTOVER_ENABLED: true, + STUDIO_SDK_CUTOVER_FAMILIES: new Set(["timing"]), + STUDIO_SDK_RESOLVER_SHADOW_ENABLED: false, + }; +}); + (globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; type ZIndexEntry = { @@ -108,7 +119,9 @@ function renderTimelineEditingHook(input: { }) => Promise; reloadPreview?: () => void; sdkSession?: Awaited> | null; + publishSdkSession?: NonNullable[0]["publishSdkSession"]>; forceReloadSdkSession?: () => void; + invalidateGsapCache?: () => void; showToast?: (message: string, kind?: string) => void; }): { move: ReturnType["handleTimelineElementMove"]; @@ -140,7 +153,9 @@ function renderTimelineEditingHook(input: { pendingTimelineEditPathRef: { current: new Set() }, uploadProjectFiles: vi.fn(), sdkSession: input.sdkSession, + publishSdkSession: input.publishSdkSession, forceReloadSdkSession: input.forceReloadSdkSession, + invalidateGsapCache: input.invalidateGsapCache, handleDomZIndexReorderCommitRef: commitRef, }); move = hook.handleTimelineElementMove; @@ -163,6 +178,9 @@ function renderTimelineEditingHook(input: { type TimelineRecordEdit = NonNullable< Parameters[0]["recordEdit"] >; +type TimelinePublishSdkSession = NonNullable< + Parameters[0]["publishSdkSession"] +>; function renderTimelineEditingHookWithLifecycle(input: { timelineElements: TimelineElement[]; @@ -227,28 +245,32 @@ async function flushAsyncWork(): Promise { * with `gsapBody`. Returns the mock for call inspection. */ function stubProjectFetch(files: string | Record, gsapBody?: unknown) { - // Keep this test server's capability, file-read, and mutation routes together; - // splitting the fixture would obscure the request sequence asserted by callers. - // fallow-ignore-next-line complexity - const fetchMock = vi.fn(async (input: Parameters[0]): Promise => { - const url = requestUrl(input); - if (url.includes("/api/projects/p1/gsap-mutation-capabilities")) { - return jsonResponse({ atomicOwnershipPairs: true }); - } - if (url.includes("/api/projects/p1/files/")) { - if (typeof files === "string") return jsonResponse({ content: files }); - const path = decodeURIComponent(url.split("/files/")[1] ?? "index.html"); - return jsonResponse({ content: files[path] }); - } - if (url.includes("/api/projects/p1/gsap-mutations/")) { - const path = decodeURIComponent(url.split("/gsap-mutations/")[1] ?? "index.html"); - const content = typeof files === "string" ? files : (files[path] ?? ""); - return jsonResponse( - gsapBody ?? { mutated: false, scriptText: null, before: content, after: content }, - ); - } - throw new Error(`Unexpected fetch: ${url}`); - }); + const contentAt = (url: string, route: string): string | undefined => { + if (typeof files === "string") return files; + const path = decodeURIComponent(url.split(route)[1] ?? "index.html"); + return files[path]; + }; + const fetchMock = vi.fn( + async ( + input: Parameters[0], + _init?: Parameters[1], + ): Promise => { + const url = requestUrl(input); + if (url.includes("/api/projects/p1/gsap-mutation-capabilities")) { + return jsonResponse({ atomicOwnershipPairs: true }); + } + if (url.includes("/api/projects/p1/files/")) { + return jsonResponse({ content: contentAt(url, "/files/") }); + } + if (url.includes("/api/projects/p1/gsap-mutations/")) { + const content = contentAt(url, "/gsap-mutations/") ?? ""; + return jsonResponse( + gsapBody ?? { mutated: false, scriptText: null, before: content, after: content }, + ); + } + throw new Error(`Unexpected fetch: ${url}`); + }, + ); vi.stubGlobal("fetch", fetchMock); return fetchMock; } @@ -285,6 +307,39 @@ function setupSingleClipHarness(options?: { return { iframe, clip, commit, writeProjectFile, reloadPreview, fetchMock, ...hook }; } +const SDK_KEYFRAMED_SOURCE = [ + `
`, + `
`, + `
`, + ``, +].join("\n"); + +async function setupSdkKeyframedClipHarness() { + const iframe = createPreviewIframe([{ id: "clip", track: 0 }]); + const clip = timelineElement({ id: "clip", track: 0, zIndex: 0, start: 1 }); + const sdkSession = await openComposition(SDK_KEYFRAMED_SOURCE); + const writeProjectFile = vi.fn<(...args: unknown[]) => Promise>(async () => {}); + const invalidateGsapCache = vi.fn(); + const fetchMock = stubProjectFetch(SDK_KEYFRAMED_SOURCE); + usePlayerStore.getState().setDuration(10); + const hook = renderTimelineEditingHook({ + timelineElements: [clip], + iframe, + onZIndexCommit: vi.fn().mockResolvedValue(undefined), + projectId: "p1", + writeProjectFile, + recordEdit: vi.fn(async () => {}), + sdkSession, + publishSdkSession: vi.fn(() => "published"), + invalidateGsapCache, + }); + return { clip, fetchMock, hook, invalidateGsapCache, writeProjectFile }; +} + /** Assert a lane write landed in both the live iframe DOM and the persisted file. */ function expectLanePersisted( iframe: HTMLIFrameElement, @@ -710,6 +765,58 @@ describe("useTimelineEditing timeline z-index reorder", () => { h.unmount(); }); + it("shifts authored GSAP positions after an SDK-backed clip move commits", async () => { + const { clip, fetchMock, hook, invalidateGsapCache, writeProjectFile } = + await setupSdkKeyframedClipHarness(); + + await act(async () => { + await hook.move(clip, { start: 2.25, track: clip.track }); + }); + + expect(writeProjectFile.mock.calls[0]?.[1]).toContain('data-start="2.25"'); + const mutationCall = fetchMock.mock.calls.find((call) => + requestUrl(call[0]).includes("/gsap-mutations/"), + ); + expect(mutationCall).toBeDefined(); + const init = mutationCall?.[1] as RequestInit | undefined; + expect(JSON.parse(String(init?.body))).toEqual({ + type: "shift-positions", + targetSelector: "#clip", + delta: 1.25, + }); + expect(invalidateGsapCache).toHaveBeenCalledTimes(1); + + hook.unmount(); + }); + + it("scales authored GSAP positions after an SDK-backed clip resize commits", async () => { + const { clip, fetchMock, hook, invalidateGsapCache, writeProjectFile } = + await setupSdkKeyframedClipHarness(); + + await act(async () => { + await hook.resize(clip, { start: 2, duration: 4, playbackStart: undefined }); + }); + + expect(writeProjectFile.mock.calls[0]?.[1]).toContain('data-start="2"'); + expect(writeProjectFile.mock.calls[0]?.[1]).toContain('data-duration="4"'); + const mutationCall = fetchMock.mock.calls.find((call) => + requestUrl(call[0]).includes("/gsap-mutations/"), + ); + expect(mutationCall).toBeDefined(); + const init = mutationCall?.[1] as RequestInit | undefined; + expect(JSON.parse(String(init?.body))).toEqual({ + type: "scale-positions", + targetSelector: "#clip", + oldStart: 1, + oldDuration: 2, + newStart: 2, + newDuration: 4, + }); + expect(invalidateGsapCache).toHaveBeenCalledTimes(1); + + hook.unmount(); + }); + it("persists a vertical-only lane move (start unchanged) through the single-element fallback", async () => { // Regression: `if (!startChanged) return` ran BEFORE the file persist, so a // pure lane change routed through onMoveElement (no onMoveElements wired) @@ -821,6 +928,55 @@ describe("useTimelineEditing timeline z-index reorder", () => { unmount(); }); + it("shifts every keyed clip and invalidates the cache after an SDK-backed group move", async () => { + const source = [ + `
`, + `
`, + `
`, + `
`, + ``, + ].join("\n"); + const { iframe, a, b } = makeTwoClipPair(); + const sdkSession = await openComposition(source); + const fetchMock = stubProjectFetch(source); + const invalidateGsapCache = vi.fn(); + usePlayerStore.getState().setDuration(10); + const hook = renderTimelineEditingHook({ + timelineElements: [a, b], + iframe, + onZIndexCommit: vi.fn().mockResolvedValue(undefined), + projectId: "p1", + writeProjectFile: vi.fn<(...args: unknown[]) => Promise>(async () => {}), + recordEdit: vi.fn(async () => {}), + sdkSession, + publishSdkSession: vi.fn(() => "published"), + invalidateGsapCache, + }); + + await act(async () => { + await hook.groupMove([ + { element: a, start: 1 }, + { element: b, start: 2 }, + ]); + }); + + const mutations = fetchMock.mock.calls + .filter((call) => requestUrl(call[0]).includes("/gsap-mutations/")) + .map((call) => JSON.parse(String((call[1] as RequestInit | undefined)?.body))); + expect(mutations).toEqual([ + { type: "shift-positions", targetSelector: "#a", delta: 1 }, + { type: "shift-positions", targetSelector: "#b", delta: 1 }, + ]); + expect(invalidateGsapCache).toHaveBeenCalledTimes(1); + + hook.unmount(); + }); + it("partitions a group move by source file while keeping one undo entry", async () => { const files: Record = { "index.html": '
', diff --git a/packages/studio/src/hooks/useTimelineEditing.ts b/packages/studio/src/hooks/useTimelineEditing.ts index 2c53299a20..bf846f06fe 100644 --- a/packages/studio/src/hooks/useTimelineEditing.ts +++ b/packages/studio/src/hooks/useTimelineEditing.ts @@ -58,6 +58,7 @@ export function useTimelineEditing({ sdkSession, publishSdkSession, forceReloadSdkSession, + invalidateGsapCache, handleDomZIndexReorderCommitRef, }: UseTimelineEditingOptions) { const projectIdRef = useRef(projectId); @@ -118,6 +119,7 @@ export function useTimelineEditing({ domEditSaveTimestampRef, editQueueRef, forceReloadSdkSession, + invalidateGsapCache, isRecordingRef, pendingTimelineEditPathRef, previewIframeRef, @@ -184,21 +186,24 @@ export function useTimelineEditing({ ); }; const coalesceKey = `timeline-move:${element.hfId ?? element.id}`; + const finishMoveGsapSync = () => + // Every timing writer converges the same GSAP positions after its + // durable clip-start commit. The SDK owns the attribute write; this + // sync owns only the dependent animation rewrite and preview refresh. + finishClipTimingFallback({ + iframe: previewIframeRef.current, + reloadPreview, + projectId: projectIdRef.current, + targetPath, + domId: element.domId, + label: "Move timeline clip", + coalesceKey, + recordEdit, + edit: { kind: "shift", delta: updates.start - element.start }, + }).finally(() => invalidateGsapCache?.()); const moveFallback = () => - enqueueEdit(element, "Move timeline clip", buildMovePatches, coalesceKey).then(() => - // Soft-reload with the server's rewritten GSAP script — the timing-only move already patched - // DOM + store, so swapping the script avoids the all-clips flash; falls back to reloadPreview(). - finishClipTimingFallback({ - iframe: previewIframeRef.current, - reloadPreview, - projectId: projectIdRef.current, - targetPath, - domId: element.domId, - label: "Move timeline clip", - coalesceKey, - recordEdit, - edit: { kind: "shift", delta: updates.start - element.start }, - }), + enqueueEdit(element, "Move timeline clip", buildMovePatches, coalesceKey).then( + finishMoveGsapSync, ); return reorderDone .then(() => { @@ -221,9 +226,10 @@ export function useTimelineEditing({ readProjectFile: (path) => readFileContent(projectIdRef.current ?? "", path), publishSession: publishSdkSession, }, - { label: "Move timeline clip", coalesceKey }, + { label: "Move timeline clip", coalesceKey, skipRefresh: true }, ).then((result) => { if (!cutoverCommittedOrThrow(result)) return moveFallback(); + return finishMoveGsapSync(); }); } return moveFallback(); @@ -250,6 +256,7 @@ export function useTimelineEditing({ timelineElements, handleDomZIndexReorderCommitRef, showToast, + invalidateGsapCache, ], ); @@ -287,23 +294,25 @@ export function useTimelineEditing({ // script (timing-only resize) — same no-flash path as move; full reload is // the fallback. const coalesceKey = `timeline-resize:${element.hfId ?? element.id}`; + const finishResizeGsapSync = () => + finishClipTimingFallback({ + iframe: previewIframeRef.current, + reloadPreview, + projectId: projectIdRef.current, + targetPath, + domId: element.domId, + label: "Resize timeline clip", + coalesceKey, + recordEdit, + edit: { + kind: "scale", + from: { start: element.start, duration: element.duration }, + to: { start: updates.start, duration: updates.duration }, + }, + }).finally(() => invalidateGsapCache?.()); const resizeFallback = () => - enqueueEdit(element, "Resize timeline clip", buildResizePatches, coalesceKey).then(() => - finishClipTimingFallback({ - iframe: previewIframeRef.current, - reloadPreview, - projectId: projectIdRef.current, - targetPath, - domId: element.domId, - label: "Resize timeline clip", - coalesceKey, - recordEdit, - edit: { - kind: "scale", - from: { start: element.start, duration: element.duration }, - to: { start: updates.start, duration: updates.duration }, - }, - }), + enqueueEdit(element, "Resize timeline clip", buildResizePatches, coalesceKey).then( + finishResizeGsapSync, ); const persistDone = sdkSession && element.hfId && !hasPbsAdjustment && !needsExtension @@ -323,9 +332,10 @@ export function useTimelineEditing({ readProjectFile: (path) => readFileContent(projectIdRef.current ?? "", path), publishSession: publishSdkSession, }, - { label: "Resize timeline clip", coalesceKey }, + { label: "Resize timeline clip", coalesceKey, skipRefresh: true }, ).then((result) => { if (!cutoverCommittedOrThrow(result)) return resizeFallback(); + return finishResizeGsapSync(); }) : resizeFallback(); return persistDone.catch((error) => { @@ -346,6 +356,7 @@ export function useTimelineEditing({ reloadPreview, domEditSaveTimestampRef, showToast, + invalidateGsapCache, ], ); diff --git a/packages/studio/src/hooks/useTimelineEditingTypes.ts b/packages/studio/src/hooks/useTimelineEditingTypes.ts index a391177064..bd3df209d8 100644 --- a/packages/studio/src/hooks/useTimelineEditingTypes.ts +++ b/packages/studio/src/hooks/useTimelineEditingTypes.ts @@ -46,6 +46,8 @@ export interface UseTimelineEditingOptions { publishSdkSession?: PublishSdkSession; /** Resync the SDK session after a server-authoritative timeline write. */ forceReloadSdkSession?: () => void; + /** Reparse authored animations after a timing rewrite changes their positions. */ + invalidateGsapCache?: () => void; handleDomZIndexReorderCommitRef?: MutableRefObject; } diff --git a/packages/studio/src/hooks/useTimelineGroupEditing.ts b/packages/studio/src/hooks/useTimelineGroupEditing.ts index 8a3fe83a81..2b6ac46e70 100644 --- a/packages/studio/src/hooks/useTimelineGroupEditing.ts +++ b/packages/studio/src/hooks/useTimelineGroupEditing.ts @@ -54,6 +54,7 @@ interface UseTimelineGroupEditingOptions { domEditSaveTimestampRef: MutableRefObject; editQueueRef: MutableRefObject>; forceReloadSdkSession?: () => void; + invalidateGsapCache?: () => void; isRecordingRef?: RefObject; pendingTimelineEditPathRef: MutableRefObject>; previewIframeRef: RefObject; @@ -110,6 +111,7 @@ export function useTimelineGroupEditing({ domEditSaveTimestampRef, editQueueRef, forceReloadSdkSession, + invalidateGsapCache, isRecordingRef, pendingTimelineEditPathRef, previewIframeRef, @@ -212,7 +214,12 @@ export function useTimelineGroupEditing({ readProjectFile: (path) => readFileContent(projectIdRef.current ?? "", path), publishSession: publishSdkSession, }, - { label: input.label, coalesceKey: input.coalesceKey, coalesceMs: input.coalesceMs }, + { + label: input.label, + coalesceKey: input.coalesceKey, + coalesceMs: input.coalesceMs, + skipRefresh: true, + }, ); return cutoverCommittedOrThrow(result); }, @@ -282,25 +289,25 @@ export function useTimelineGroupEditing({ coalesceKey, coalesceMs, }); - if (handledBySdk) return; - - await persistServerBatch( - projectId, - "Move timeline clips", - changes.map((change) => ({ - element: change.element, - buildPatches: (original, target) => - buildTimelineMoveTimingPatch( - original, - target, - change.start, - change.element.duration, - change.track, - ), - })), - coalesceKey, - coalesceMs, - ); + if (!handledBySdk) { + await persistServerBatch( + projectId, + "Move timeline clips", + changes.map((change) => ({ + element: change.element, + buildPatches: (original, target) => + buildTimelineMoveTimingPatch( + original, + target, + change.start, + change.element.duration, + change.track, + ), + })), + coalesceKey, + coalesceMs, + ); + } // Track-only: no timing delta → no GSAP positions to shift and no // reload (see the trackOnly doc above). Mixed batches (any start // change) keep the full fallback below. @@ -323,6 +330,7 @@ export function useTimelineGroupEditing({ return shiftGsapPositions(projectId, changePath, domId, delta); }, }); + invalidateGsapCache?.(); }).catch((error) => { // Failed persist: revert the optimistic duration readout + live root // alongside the gesture owner's store rollback. @@ -340,6 +348,7 @@ export function useTimelineGroupEditing({ reloadPreview, trySdkBatchPersist, showToast, + invalidateGsapCache, ], ); @@ -384,23 +393,23 @@ export function useTimelineGroupEditing({ coalesceKey, coalesceMs, }); - if (handledBySdk) return; - - await persistServerBatch( - projectId, - "Resize timeline clips", - changes.map((change) => ({ - element: change.element, - buildPatches: (original, target) => - buildTimelineResizeTimingPatch(original, target, change.element, { - start: change.start, - duration: change.duration, - playbackStart: change.playbackStart, - }), - })), - coalesceKey, - coalesceMs, - ); + if (!handledBySdk) { + await persistServerBatch( + projectId, + "Resize timeline clips", + changes.map((change) => ({ + element: change.element, + buildPatches: (original, target) => + buildTimelineResizeTimingPatch(original, target, change.element, { + start: change.start, + duration: change.duration, + playbackStart: change.playbackStart, + }), + })), + coalesceKey, + coalesceMs, + ); + } await finishGroupTimingGsapFallback({ projectId, iframe: previewIframeRef.current, @@ -428,6 +437,7 @@ export function useTimelineGroupEditing({ ); }, }); + invalidateGsapCache?.(); }).catch((error) => { // Failed persist: revert the optimistic duration readout + live root // alongside the gesture owner's store rollback. @@ -445,6 +455,7 @@ export function useTimelineGroupEditing({ reloadPreview, trySdkBatchPersist, showToast, + invalidateGsapCache, ], ); diff --git a/packages/studio/src/player/components/KeyframeDiamondContextMenu.tsx b/packages/studio/src/player/components/KeyframeDiamondContextMenu.tsx index 34a1cc41ff..1e8275511b 100644 --- a/packages/studio/src/player/components/KeyframeDiamondContextMenu.tsx +++ b/packages/studio/src/player/components/KeyframeDiamondContextMenu.tsx @@ -1,25 +1,41 @@ import { memo } from "react"; import { createPortal } from "react-dom"; import { useContextMenuDismiss } from "../../hooks/useContextMenuDismiss"; +import type { TimelineElement } from "../store/playerStore"; export interface KeyframeDiamondContextMenuState { x: number; y: number; + element: TimelineElement; elementId: string; percentage: number; tweenPercentage?: number; + propertyGroup?: string; + animationId?: string; currentEase?: string; } interface KeyframeDiamondContextMenuProps { state: KeyframeDiamondContextMenuState; onClose: () => void; - onDelete: (elementId: string, percentage: number) => void; - onDeleteAll: (elementId: string) => void; + onDelete: ( + elementId: string, + percentage: number, + propertyGroup?: string, + tweenPercentage?: number, + animationId?: string, + ) => void; + onDeleteAll: (element: TimelineElement) => void; onChangeEase?: (elementId: string, percentage: number, ease: string) => void; onCopyProperties?: (elementId: string, percentage: number) => void; /** Retime the keyframe to the current playhead, preserving its value + ease. */ - onMoveToPlayhead?: (elementId: string, fromPercentage: number) => void; + onMoveToPlayhead?: ( + element: TimelineElement, + fromPercentage: number, + propertyGroup?: string, + tweenPercentage?: number, + animationId?: string, + ) => void; } export const KeyframeDiamondContextMenu = memo(function KeyframeDiamondContextMenu({ @@ -51,7 +67,13 @@ export const KeyframeDiamondContextMenu = memo(function KeyframeDiamondContextMe // Pass clip-% — resolveKeyframeTarget keys the cache lookup on clip-% // and returns the tween-% for the mutation. Passing tween-% here would // miss the lookup on any tween whose window is shorter than the clip. - onMoveToPlayhead(state.elementId, state.percentage); + onMoveToPlayhead( + state.element, + state.percentage, + state.propertyGroup, + state.tweenPercentage, + state.animationId, + ); onClose(); }} > @@ -64,7 +86,13 @@ export const KeyframeDiamondContextMenu = memo(function KeyframeDiamondContextMe type="button" className="w-full flex items-center gap-2 px-3 py-1.5 text-xs text-red-400 hover:bg-neutral-800 cursor-pointer text-left" onClick={() => { - onDelete(state.elementId, state.percentage); + onDelete( + state.elementId, + state.percentage, + state.propertyGroup, + state.tweenPercentage, + state.animationId, + ); onClose(); }} > @@ -75,7 +103,7 @@ export const KeyframeDiamondContextMenu = memo(function KeyframeDiamondContextMe type="button" className="w-full flex items-center gap-2 px-3 py-1.5 text-xs text-red-400 hover:bg-neutral-800 cursor-pointer text-left" onClick={() => { - onDeleteAll(state.elementId); + onDeleteAll(state.element); onClose(); }} > diff --git a/packages/studio/src/player/components/LayerDisclosureRow.tsx b/packages/studio/src/player/components/LayerDisclosureRow.tsx new file mode 100644 index 0000000000..b630482d69 --- /dev/null +++ b/packages/studio/src/player/components/LayerDisclosureRow.tsx @@ -0,0 +1,56 @@ +import { CaretRight } from "@phosphor-icons/react"; +import type { TimelineElement } from "../store/playerStore"; +import { LABEL_COL_W, TRACK_H } from "./timelineLayout"; + +// Layer row (Figma order: disclosure ▸/▾, diamond, name) — the disclosure lives +// here, not on the clip bar, and re-expands a collapsed layer. +export function LayerDisclosureRow({ + keyframeClip, + isExpanded, + gutterBackground, + onToggleClipExpanded, +}: { + keyframeClip: TimelineElement; + isExpanded: boolean; + gutterBackground: string; + onToggleClipExpanded: () => void; +}) { + const name = keyframeClip.label ?? keyframeClip.domId ?? keyframeClip.id; + return ( +
+ + + ◇ + + {name} +
+ ); +} diff --git a/packages/studio/src/player/components/Timeline.tsx b/packages/studio/src/player/components/Timeline.tsx index 0e847a3fab..037b0bac1c 100644 --- a/packages/studio/src/player/components/Timeline.tsx +++ b/packages/studio/src/player/components/Timeline.tsx @@ -435,6 +435,9 @@ export const Timeline = memo(function Timeline({ onDragLeave={() => clearDropPreview()} onDrop={handleAssetDrop} onPointerDown={(e) => { + // Let interactive controls (keyframe nav/toggle, caret, inputs) handle + // their own clicks — scrubbing here would preventDefault and eat them. + if (e.target instanceof Element && e.target.closest("button, input, select, a")) return; if (activeTool === "razor" && e.shiftKey && e.button === 0 && scrollRef.current) { const rect = scrollRef.current.getBoundingClientRect(); const x = @@ -512,15 +515,15 @@ export const Timeline = memo(function Timeline({ onMoveKeyframe={onMoveKeyframe} onContextMenuKeyframe={(e, elId, pct) => { const el = expandedElements.find((x) => (x.key ?? x.id) === elId); - if (el) { - setSelectedElementId(elId); - onSelectElement?.(el); - } + if (!el) return; + setSelectedElementId(elId); + onSelectElement?.(el); const kfData = keyframeCache.get(elId); const kf = kfData?.keyframes.find((k) => Math.abs(k.percentage - pct) < 0.2); setKfContextMenu({ x: e.clientX + 4, y: e.clientY + 2, + element: el, elementId: elId, percentage: pct, tweenPercentage: kf?.tweenPercentage, diff --git a/packages/studio/src/player/components/TimelineClipDiamonds.test.tsx b/packages/studio/src/player/components/TimelineClipDiamonds.test.tsx index 254e5d6086..2eff6f0828 100644 --- a/packages/studio/src/player/components/TimelineClipDiamonds.test.tsx +++ b/packages/studio/src/player/components/TimelineClipDiamonds.test.tsx @@ -3,7 +3,7 @@ import React, { act } from "react"; import { createRoot } from "react-dom/client"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { TimelineClipDiamonds } from "./TimelineClipDiamonds"; +import { TimelineClipDiamonds, TimelineDiamondLane } from "./TimelineClipDiamonds"; (globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; @@ -45,6 +45,42 @@ function renderDiamonds(onClickKeyframe = vi.fn()) { } describe("TimelineClipDiamonds", () => { + it("keeps dense keyframe hit regions and visuals from overlapping", () => { + const host = document.createElement("div"); + document.body.append(host); + const root = createRoot(host); + act(() => { + root.render( + ({ + percentage, + propertyGroup: "position", + properties: { x: percentage }, + })), + }} + clipWidthPx={36} + clipHeightPx={48} + accentColor="#4ba3d2" + isSelected + currentPercentage={0} + elementId="clip-1" + selectedKeyframes={new Set()} + groupAware + />, + ); + }); + + const diamonds = Array.from(host.querySelectorAll("button[title]")); + expect(diamonds).toHaveLength(3); + for (const diamond of diamonds) { + expect(Number.parseFloat(diamond.style.width)).toBeCloseTo(10.8); + expect(Number(diamond.querySelector("svg")?.getAttribute("width"))).toBeCloseTo(8.8); + } + act(() => root.unmount()); + }); + it("treats primary pointerup without drag as a keyframe click", () => { const { host, root, onClickKeyframe } = renderDiamonds(); const diamond = host.querySelector('button[title="50%"]'); @@ -84,12 +120,24 @@ describe("TimelineClipDiamonds", () => { const root = createRoot(host); act(() => { root.render( - { selectedKeyframes={new Set()} onClickKeyframe={onClickKeyframe} onMoveKeyframe={onMoveKeyframe} + groupAware />, ); }); @@ -117,7 +166,12 @@ describe("TimelineClipDiamonds", () => { diamond!.dispatchEvent(pointerEvent("pointerup", { bubbles: true, button: 0, clientX: 104 })); }); - expect(onClickKeyframe).toHaveBeenCalledWith(50); + expect(onClickKeyframe).toHaveBeenCalledWith({ + percentage: 50, + tweenPercentage: 100, + propertyGroup: "position", + animationId: "anim-1", + }); expect(onMoveKeyframe).not.toHaveBeenCalled(); act(() => root.unmount()); }); @@ -126,20 +180,39 @@ describe("TimelineClipDiamonds", () => { // keyframe) committed the move but never selected/parked on the result — // the diamond it was just dragged looked exactly like one nothing happened // to. Select it at its NEW position too. - it("selects the keyframe at its new position after a real drag-retime", () => { + it("reselects a retimed keyframe with its post-move tween percentage", () => { const onClickKeyframe = vi.fn(); - const onMoveKeyframe = vi.fn(); + const onMoveKeyframe = vi.fn().mockResolvedValue(true); const host = document.createElement("div"); document.body.append(host); const root = createRoot(host); act(() => { root.render( - { selectedKeyframes={new Set()} onClickKeyframe={onClickKeyframe} onMoveKeyframe={onMoveKeyframe} + groupAware + />, + ); + }); + const diamond = host.querySelector('button[title="40%"]'); + expect(diamond).not.toBeNull(); + + act(() => { + diamond!.dispatchEvent( + pointerEvent("pointerdown", { bubbles: true, button: 0, clientX: 80 }), + ); + diamond!.dispatchEvent(pointerEvent("pointerup", { bubbles: true, button: 0, clientX: 100 })); + }); + + expect(onMoveKeyframe).toHaveBeenCalledWith( + { + percentage: 40, + tweenPercentage: 50, + propertyGroup: "position", + animationId: "anim-1", + }, + 50, + ); + expect(onClickKeyframe).toHaveBeenCalledWith({ + percentage: 50, + tweenPercentage: 75, + propertyGroup: "position", + animationId: "anim-1", + }); + act(() => root.unmount()); + }); + + it("composes a rapid second retime from the pending position", () => { + const onMoveKeyframe = vi.fn().mockResolvedValue(true); + const host = document.createElement("div"); + document.body.append(host); + const root = createRoot(host); + act(() => { + root.render( + , ); }); @@ -161,13 +309,109 @@ describe("TimelineClipDiamonds", () => { diamond!.dispatchEvent( pointerEvent("pointerdown", { bubbles: true, button: 0, clientX: 100 }), ); - // 4px at a 200px clip width is 2 clip-% — well past the no-op epsilon, - // a real retime. - diamond!.dispatchEvent(pointerEvent("pointerup", { bubbles: true, button: 0, clientX: 104 })); + diamond!.dispatchEvent(pointerEvent("pointerup", { bubbles: true, button: 0, clientX: 150 })); + + // The cache still exposes 50%, but this second +10% drag starts at the + // pending 75% destination and must therefore land at 85%, not 60%. + diamond!.dispatchEvent( + pointerEvent("pointerdown", { bubbles: true, button: 0, clientX: 150 }), + ); + diamond!.dispatchEvent(pointerEvent("pointerup", { bubbles: true, button: 0, clientX: 170 })); + }); + + // The second move must identify the FROM keyframe by the pending (already- + // moved) position 75%, not the stale rendered 50%; otherwise the serialized + // mutation can't locate the keyframe the first move relocated. + expect(onMoveKeyframe).toHaveBeenNthCalledWith( + 2, + { + percentage: 75, + tweenPercentage: 75, + propertyGroup: "position", + animationId: "anim-1", + }, + 85, + ); + act(() => root.unmount()); + }); + + it.each([ + ["returns false", () => Promise.resolve(false)], + ["rejects", () => Promise.reject(new Error("retime failed"))], + ])("clears a failed pending retime when the callback %s", async (_label, settle) => { + const onMoveKeyframe = vi.fn().mockImplementationOnce(settle).mockResolvedValue(true); + const host = document.createElement("div"); + document.body.append(host); + const root = createRoot(host); + act(() => { + root.render( + , + ); + }); + const diamond = host.querySelector('button[title="50%"]'); + expect(diamond).not.toBeNull(); + + await act(async () => { + diamond!.dispatchEvent( + pointerEvent("pointerdown", { bubbles: true, button: 0, clientX: 100 }), + ); + diamond!.dispatchEvent(pointerEvent("pointerup", { bubbles: true, button: 0, clientX: 150 })); + await Promise.resolve(); }); - expect(onMoveKeyframe).toHaveBeenCalledWith("clip-1", 50, 52); - expect(onClickKeyframe).toHaveBeenCalledWith(52); + act(() => { + diamond!.dispatchEvent( + pointerEvent("pointerdown", { bubbles: true, button: 0, clientX: 100 }), + ); + diamond!.dispatchEvent(pointerEvent("pointerup", { bubbles: true, button: 0, clientX: 120 })); + }); + + expect(onMoveKeyframe).toHaveBeenNthCalledWith( + 2, + { + percentage: 50, + tweenPercentage: 50, + propertyGroup: "position", + animationId: "anim-1", + }, + 60, + ); act(() => root.unmount()); }); @@ -212,4 +456,100 @@ describe("TimelineClipDiamonds", () => { expect(suppressClickRef.current).toBe(true); act(() => root.unmount()); }); + + const renderSegmentLane = (lastAmbiguous: boolean) => { + const host = document.createElement("div"); + document.body.append(host); + const root = createRoot(host); + const kf = (percentage: number, extra: Record = {}) => ({ + percentage, + tweenPercentage: percentage, + propertyGroup: "position", + animationId: "anim-1", + properties: { x: percentage }, + ...extra, + }); + act(() => { + root.render( + , + ); + }); + return { host, root }; + }; + + it("hides the inline ease button on an ambiguous merged segment", () => { + // Segments 0->50 and 50->100; the 50->100 segment ends on the ambiguous + // keyframe, so its hover/ease-button area is not rendered. + const { host, root } = renderSegmentLane(true); + expect(host.querySelectorAll("[data-keyframe-ease-segment]").length).toBe(1); + act(() => root.unmount()); + }); + + it("keeps the inline ease button on unambiguous merged segments", () => { + const { host, root } = renderSegmentLane(false); + expect(host.querySelectorAll("[data-keyframe-ease-segment]").length).toBe(2); + act(() => root.unmount()); + }); + + it("keeps the ease button above nearby diamonds without blocking the segment", () => { + const { host, root } = renderSegmentLane(false); + const segment = host.querySelector("[data-keyframe-ease-segment]"); + const ease = segment?.querySelector("[data-keyframe-ease-button]"); + const diamond = host.querySelector('button[title="50%"]'); + + expect(segment?.style.pointerEvents).toBe("none"); + expect(ease?.style.pointerEvents).toBe("auto"); + expect(Number(segment?.style.zIndex)).toBeGreaterThan(Number(diamond?.style.zIndex)); + act(() => root.unmount()); + }); + + it("hides the inline ease button on a segment with no source animation id", () => { + // A runtime-scanned keyframe has no animationId, so there is no tween to + // target; the segment ending on it must not render a (dead) ease button. + const host = document.createElement("div"); + document.body.append(host); + const root = createRoot(host); + const kf = (percentage: number, animationId?: string) => ({ + percentage, + tweenPercentage: percentage, + propertyGroup: "position", + ...(animationId ? { animationId } : {}), + properties: { x: percentage }, + }); + act(() => { + root.render( + , + ); + }); + expect(host.querySelectorAll("[data-keyframe-ease-segment]").length).toBe(1); + act(() => root.unmount()); + }); }); diff --git a/packages/studio/src/player/components/TimelineClipDiamonds.tsx b/packages/studio/src/player/components/TimelineClipDiamonds.tsx index 129104dfb8..e9a1abac53 100644 --- a/packages/studio/src/player/components/TimelineClipDiamonds.tsx +++ b/packages/studio/src/player/components/TimelineClipDiamonds.tsx @@ -1,22 +1,33 @@ -import { memo, useRef, useState } from "react"; +import { Fragment, memo, useEffect, useRef, useState } from "react"; import { BEAT_BAND_H } from "./BeatStrip"; import { KEYFRAME_DRAG_THRESHOLD_PX, previewClipPct, resolveKeyframeDrag, } from "../../components/editor/keyframeDrag"; - -interface KeyframeEntry { +import { MiniCurveSvg } from "../../components/editor/EaseCurveSection"; +import { clipToTweenPercentage } from "../../components/editor/KeyframeNavigation"; +import { LANE_H } from "./timelineLayout"; +import { + timelineKeyframeSelectionKey, + type TimelineKeyframeTarget, +} from "./timelineKeyframeIdentity"; +export interface TimelineDiamondKeyframe { percentage: number; /** Tween-relative percentage (the retime mutation keys on this, not clip %). */ tweenPercentage?: number; + propertyGroup?: string; + animationId?: string; properties: Record; ease?: string; + /** Set when 2+ source animations collide at this percentage (a single inline + * ease button can't target one): the collapsed row hides the button here. */ + easeAmbiguous?: boolean; } interface KeyframeCacheEntry { format: string; - keyframes: KeyframeEntry[]; + keyframes: TimelineDiamondKeyframe[]; ease?: string; easeEach?: string; } @@ -32,7 +43,7 @@ interface TimelineClipDiamondsProps { isSelected: boolean; currentPercentage: number; elementId: string; - selectedKeyframes: Set; + selectedKeyframes: ReadonlySet; onClickKeyframe?: (percentage: number) => void; onShiftClickKeyframe?: (elementId: string, percentage: number) => void; onContextMenuKeyframe?: (e: React.MouseEvent, elementId: string, percentage: number) => void; @@ -44,13 +55,33 @@ interface TimelineClipDiamondsProps { elementId: string, fromClipPercentage: number, toClipPercentage: number, - ) => void; + ) => Promise; + /** Open the segment ease editor for the hovered mid-point button — available on + * the inline clip row too, not just the expanded lanes. */ + onSelectSegment?: (elementId: string, target: TimelineKeyframeTarget) => void; /** Set while resolving a diamond press so the ancestor clip's onClick (which * toggles selection off when already selected) ignores the native "click" * the browser auto-synthesizes after this button's pointerdown+pointerup. */ suppressClickRef?: React.RefObject; } +interface TimelineDiamondLaneProps extends Omit< + TimelineClipDiamondsProps, + | "onClickKeyframe" + | "onShiftClickKeyframe" + | "onContextMenuKeyframe" + | "onMoveKeyframe" + | "onSelectSegment" +> { + groupAware?: boolean; + globalEase?: string; + onSelectSegment?: (target: TimelineKeyframeTarget) => void; + onClickKeyframe?: (target: TimelineKeyframeTarget) => void; + onShiftClickKeyframe?: (target: TimelineKeyframeTarget) => void; + onContextMenuKeyframe?: (e: React.MouseEvent, target: TimelineKeyframeTarget) => void; + onMoveKeyframe?: (target: TimelineKeyframeTarget, toClipPercentage: number) => Promise; +} + const DIAMOND_RATIO = 0.8; // Percentage tolerance for rendering keyframes near clip boundaries. Keyframes // slightly outside [0, 100] (from rounding or stale cache during the async @@ -66,7 +97,21 @@ type DragState = { moved: boolean; }; -export const TimelineClipDiamonds = memo(function TimelineClipDiamonds({ +function keyframeTarget( + keyframe: TimelineDiamondKeyframe, + groupAware: boolean, +): TimelineKeyframeTarget { + return groupAware + ? { + percentage: keyframe.percentage, + tweenPercentage: keyframe.tweenPercentage, + propertyGroup: keyframe.propertyGroup, + animationId: keyframe.animationId, + } + : { percentage: keyframe.percentage }; +} + +export const TimelineDiamondLane = memo(function TimelineDiamondLane({ keyframesData, clipWidthPx, clipHeightPx, @@ -80,10 +125,27 @@ export const TimelineClipDiamonds = memo(function TimelineClipDiamonds({ onShiftClickKeyframe, onContextMenuKeyframe, onMoveKeyframe, + onSelectSegment, suppressClickRef, -}: TimelineClipDiamondsProps) { + groupAware = false, + globalEase = "none", +}: TimelineDiamondLaneProps) { // Hooks must run before the early return below. const dragRef = useRef(null); + // Pending retime destination (clip + tween %) per keyframe key, so a rapid + // second drag composes from where the first move left the keyframe (whose + // cache entry has not rebuilt yet) instead of the stale rendered value. + const pendingRetimeRef = useRef(new Map()); + useEffect(() => { + // Clear a pending entry once the authoritative cache reflects a keyframe at + // ~its destination. Match by tolerance, not equality: cache writers round + // clip %s, so an exact check would leak an entry after every successful retime. + for (const [key, pending] of pendingRetimeRef.current) { + if (keyframesData.keyframes.some((k) => Math.abs(k.percentage - pending.clipPct) < 0.2)) { + pendingRetimeRef.current.delete(key); + } + } + }, [keyframesData.keyframes]); // Visual-only preview of the dragged diamond's clip-% — no runtime/GSAP hold // (that optimistic hold was the #1763 flake). The atomic move-keyframe commit // on drop re-keys the diamond from source. @@ -108,8 +170,12 @@ export const TimelineClipDiamonds = memo(function TimelineClipDiamonds({ // When the beat strip occupies the top band, shrink the diamonds and center // them in the remaining bottom region so they don't collide with it. - const diamondSize = Math.round(clipHeightPx * (beatsActive ? 0.45 : DIAMOND_RATIO)); - const half = diamondSize / 2; + // One consistent keyframe-diamond size everywhere (clip bars + property lanes), + // matching the property-lane size (LANE_H · ratio). Beat-strip tracks still + // shrink to fit under the strip. + const diamondSize = beatsActive + ? Math.round(clipHeightPx * 0.45) + : Math.round(LANE_H * DIAMOND_RATIO); const centerY = beatsActive ? BEAT_BAND_H + (clipHeightPx - BEAT_BAND_H) / 2 : clipHeightPx / 2; const sorted = keyframesData.keyframes .filter((kf) => kf.percentage >= KF_MIN_PCT && kf.percentage <= KF_MAX_PCT) @@ -117,6 +183,20 @@ export const TimelineClipDiamonds = memo(function TimelineClipDiamonds({ // Clip-%s of the sorted keyframes — the neighbour clamp (preview + drop) needs // the whole row to bound the dragged diamond between its immediate siblings. const sortedClipPcts = sorted.map((k) => k.percentage); + const sortedCenterXs = sorted.map((keyframe) => + Math.max(0, Math.min(clipWidthPx, (keyframe.percentage / 100) * clipWidthPx)), + ); + const markerMetrics = sortedCenterXs.map((centerX, index) => { + const previousGap = index > 0 ? centerX - sortedCenterXs[index - 1]! : Infinity; + const nextGap = + index < sortedCenterXs.length - 1 ? sortedCenterXs[index + 1]! - centerX : Infinity; + const nearestGap = Math.max(1, Math.min(previousGap, nextGap)); + const hitWidth = Math.min(diamondSize, nearestGap); + return { + hitWidth, + visualSize: hitWidth === diamondSize ? diamondSize : Math.max(2, hitWidth - 2), + }; + }); const baseColor = isSelected ? accentColor : "#a3a3a3"; const baseOpacity = isSelected ? 0.4 : 0.25; const canDrag = isSelected && !!onMoveKeyframe; @@ -138,36 +218,101 @@ export const TimelineClipDiamonds = memo(function TimelineClipDiamonds({ {sorted.map((kf, i) => { if (i === 0) return null; const prev = sorted[i - 1]!; - const x1 = Math.max(0, Math.min(clipWidthPx, (prev.percentage / 100) * clipWidthPx)); - const x2 = Math.max(0, Math.min(clipWidthPx, (kf.percentage / 100) * clipWidthPx)); + const x1 = sortedCenterXs[i - 1]!; + const x2 = sortedCenterXs[i]!; if (x2 - x1 < 1) return null; + const connectorLeft = x1 + markerMetrics[i - 1]!.visualSize / 2; + const connectorWidth = + x2 - x1 - markerMetrics[i - 1]!.visualSize / 2 - markerMetrics[i]!.visualSize / 2; + // Group-aware target for the ease button: the segment ease is + // per-keyframe (each keyframe carries its own animationId/tweenPercentage). + // On a merged inline row the button is hidden where the segment is + // ambiguous (two source animations collide at this % with different + // eases; see easeAmbiguous) or the keyframe has no source animation id + // (runtime-scanned) so there is no tween to target. + const target = keyframeTarget(kf, true); + const ease = kf.ease ?? globalEase; return ( -
+ +
+ {onSelectSegment && !kf.easeAmbiguous && kf.animationId !== undefined && ( +
+ +
+ )} + ); })} {sorted.map((kf, i) => { - const kfKey = `${elementId}:${kf.percentage}`; + const target = keyframeTarget(kf, groupAware); + const kfKey = timelineKeyframeSelectionKey(elementId, target); // While dragging this diamond, render it at the live preview clip-%. const renderPct = preview?.kfKey === kfKey ? preview.clipPct : kf.percentage; - // Center the diamond ON its keyframe %: left = (% · width) − half so the - // diamond's midpoint sits exactly at the percentage. At 0% the midpoint - // is the clip's left edge (the left half overflows, which the - // overflow-visible clip shows) — NOT shifted fully inside. - const leftPx = (renderPct / 100) * clipWidthPx - half; + // Center the marker's non-overlapping hit region ON its keyframe %, so + // the diamond's midpoint sits exactly on the playhead/ruler x for that time. + // The 0% diamond's left half lands in the reserved left gutter (the + // content origin is inset past the label column, Figma-style) so it stays + // fully visible instead of being clipped by the sticky label column. + const marker = markerMetrics[i]!; + const leftPx = (renderPct / 100) * clipWidthPx - marker.hitWidth / 2; const isKfSelected = selectedKeyframes.has(kfKey); const atPlayhead = isSelected && Math.abs(kf.percentage - currentPercentage) < 0.5; const isHighlighted = isKfSelected || atPlayhead; @@ -181,7 +326,7 @@ export const TimelineClipDiamonds = memo(function TimelineClipDiamonds({ dragRef.current = { kfKey, startX: e.clientX, - fromClipPct: kf.percentage, + fromClipPct: pendingRetimeRef.current.get(kfKey)?.clipPct ?? kf.percentage, moved: false, }; } @@ -212,8 +357,8 @@ export const TimelineClipDiamonds = memo(function TimelineClipDiamonds({ if (!d || d.kfKey !== kfKey) { if (e.button !== 0) return; suppressNextClick(); - if (e.shiftKey) onShiftClickKeyframe?.(elementId, kf.percentage); - else onClickKeyframe?.(kf.percentage); + if (e.shiftKey) onShiftClickKeyframe?.(target); + else onClickKeyframe?.(target); return; } e.stopPropagation(); @@ -235,14 +380,54 @@ export const TimelineClipDiamonds = memo(function TimelineClipDiamonds({ // back onto ~the same position — no real retime, so treat it as the // click it was. Otherwise a normal click with a few px of mouse/ // trackpad drift silently does nothing: no selection, no move. - if (e.shiftKey) onShiftClickKeyframe?.(elementId, kf.percentage); - else onClickKeyframe?.(kf.percentage); + if (e.shiftKey) onShiftClickKeyframe?.(target); + else onClickKeyframe?.(target); } else if (res.kind === "move" && res.toClipPct != null) { - onMoveKeyframe?.(elementId, d.fromClipPct, res.toClipPct); + const animKfs = + target.animationId === undefined + ? keyframesData.keyframes + : keyframesData.keyframes.filter((k) => k.animationId === target.animationId); + // Clamp to the mapped tween range: clipToTweenPercentage extrapolates + // linearly, so a boundary drag past the range would otherwise reselect + // an out-of-range tween % (e.g. 150%) even though the mutation clamps + // the moved endpoint back to the boundary. + const tweenPcts = animKfs + .map((k) => k.tweenPercentage) + .filter((v): v is number => typeof v === "number"); + const clampTween = (v: number) => + tweenPcts.length + ? Math.max(Math.min(...tweenPcts), Math.min(Math.max(...tweenPcts), v)) + : v; + const newTweenPct = clampTween(clipToTweenPercentage(animKfs, res.toClipPct)); + // For a rapid second retime the diamond still renders the stale cache + // position, so identify the FROM keyframe by the pending (already-moved) + // position; the mutation locates the source keyframe by this identity. + const pendingBefore = pendingRetimeRef.current.get(kfKey); + const fromTarget = pendingBefore + ? { + ...target, + percentage: pendingBefore.clipPct, + tweenPercentage: pendingBefore.tweenPct, + } + : target; + const pending = { clipPct: res.toClipPct, tweenPct: newTweenPct }; + pendingRetimeRef.current.set(kfKey, pending); + const clearPending = () => { + if (pendingRetimeRef.current.get(kfKey) === pending) { + pendingRetimeRef.current.delete(kfKey); + } + }; + void onMoveKeyframe?.(fromTarget, res.toClipPct).then((committed) => { + if (!committed) clearPending(); + }, clearPending); // A retime still targeted this exact diamond — park/select it at its // new position, same as a plain click, or a drag that actually moved // something looks identical to one that silently did nothing. - onClickKeyframe?.(res.toClipPct); + onClickKeyframe?.({ + ...target, + percentage: res.toClipPct, + tweenPercentage: newTweenPct, + }); } }; @@ -251,11 +436,15 @@ export const TimelineClipDiamonds = memo(function TimelineClipDiamonds({ key={`${i}-${kf.percentage}`} type="button" className="absolute" + data-keyframe-group={groupAware ? kf.propertyGroup : undefined} + data-keyframe-percentage={ + groupAware ? (kf.tweenPercentage ?? kf.percentage) : undefined + } style={{ left: leftPx, top: centerY, transform: "translateY(-50%)", - width: diamondSize, + width: marker.hitWidth, height: diamondSize, zIndex: isHighlighted ? 2 : 1, pointerEvents: "auto", @@ -264,18 +453,36 @@ export const TimelineClipDiamonds = memo(function TimelineClipDiamonds({ cursor: canDrag ? "ew-resize" : "pointer", padding: 0, touchAction: "none", + display: "flex", + alignItems: "center", + justifyContent: "center", + overflow: "visible", }} onPointerDown={onPointerDown} onPointerMove={onPointerMove} onPointerUp={onPointerUp} + onPointerCancel={(e) => { + // Browser/OS cancellation (or lost capture) ends the drag without a + // pointerup, so clear the armed drag and preview or a ghost diamond + // stays stuck at the last previewed position. + if (dragRef.current?.kfKey !== kfKey) return; + dragRef.current = null; + setPreview(null); + e.currentTarget.releasePointerCapture?.(e.pointerId); + }} onContextMenu={(e) => { e.preventDefault(); e.stopPropagation(); - onContextMenuKeyframe?.(e, elementId, kf.percentage); + onContextMenuKeyframe?.(e, target); }} title={`${kf.percentage}%`} > - + {isKfSelected && ( ); }); + +export const TimelineClipDiamonds = memo(function TimelineClipDiamonds( + props: TimelineClipDiamondsProps, +) { + return ( + props.onClickKeyframe?.(target.percentage)} + onShiftClickKeyframe={(target) => + props.onShiftClickKeyframe?.(props.elementId, target.percentage) + } + onContextMenuKeyframe={(e, target) => + props.onContextMenuKeyframe?.(e, props.elementId, target.percentage) + } + onMoveKeyframe={ + props.onMoveKeyframe + ? (target, toClipPercentage) => + props.onMoveKeyframe?.(props.elementId, target.percentage, toClipPercentage) ?? + Promise.resolve(false) + : undefined + } + onSelectSegment={ + props.onSelectSegment + ? (target) => props.onSelectSegment?.(props.elementId, target) + : undefined + } + /> + ); +}); diff --git a/packages/studio/src/player/components/TimelineLanes.tsx b/packages/studio/src/player/components/TimelineLanes.tsx index 75069c1a0b..13707c05c7 100644 --- a/packages/studio/src/player/components/TimelineLanes.tsx +++ b/packages/studio/src/player/components/TimelineLanes.tsx @@ -78,7 +78,7 @@ export interface TimelineLaneBaseProps { elementId: string, fromClipPercentage: number, toClipPercentage: number, - ) => void; + ) => Promise; onContextMenuClip?: (e: React.MouseEvent, element: TimelineElement) => void; /** * Right-click on EMPTY lane space (not on a clip — those preventDefault diff --git a/packages/studio/src/player/components/TimelinePropertyLanes.test.tsx b/packages/studio/src/player/components/TimelinePropertyLanes.test.tsx new file mode 100644 index 0000000000..200f25d8c1 --- /dev/null +++ b/packages/studio/src/player/components/TimelinePropertyLanes.test.tsx @@ -0,0 +1,430 @@ +// @vitest-environment happy-dom + +import React, { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import type { GsapAnimation, PropertyGroupName } from "@hyperframes/core/gsap-parser"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { TimelineClipDiamonds } from "./TimelineClipDiamonds"; +import { + getTimelinePropertyLanes, + TimelinePropertyLanes, + type TimelinePropertyLanesProps, +} from "./TimelinePropertyLanes"; +import { timelineKeyframeSelectionKey } from "./timelineKeyframeIdentity"; + +(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +afterEach(() => { + document.body.innerHTML = ""; +}); + +function animation( + id: string, + propertyGroup: PropertyGroupName, + keyframes: Array<{ + percentage: number; + properties: Record; + ease?: string; + }>, +): GsapAnimation { + return { + id, + targetSelector: "#clip-1", + method: "to", + position: 0, + duration: 1, + properties: {}, + propertyGroup, + keyframes: { format: "percentage", keyframes }, + }; +} + +function flatAnimation( + id: string, + propertyGroup: PropertyGroupName, + properties: Record, +): GsapAnimation { + return { + id, + targetSelector: "#clip-1", + method: "to", + position: 0, + duration: 1, + properties, + propertyGroup, + }; +} + +function renderPropertyLanes(overrides: Partial = {}): { + host: HTMLDivElement; + root: Root; +} { + const host = document.createElement("div"); + document.body.append(host); + const root = createRoot(host); + act(() => { + root.render( + , + ); + }); + return { host, root }; +} + +function laneDiamonds(host: HTMLElement, group: string): HTMLButtonElement[] { + return Array.from( + host.querySelectorAll( + `[data-property-group="${group}"] button[data-keyframe-percentage]`, + ), + ); +} + +function expectLanePercentages(host: HTMLElement, group: string, percentages: string[]) { + expect(laneDiamonds(host, group).map((diamond) => diamond.dataset.keyframePercentage)).toEqual( + percentages, + ); +} + +function laneEaseButtons(host: HTMLElement, group: string): HTMLButtonElement[] { + return Array.from( + host.querySelectorAll( + `[data-property-group="${group}"] button[data-keyframe-ease-button]`, + ), + ); +} + +function laneEaseSegments(host: HTMLElement, group: string): HTMLElement[] { + return Array.from( + host.querySelectorAll( + `[data-property-group="${group}"] [data-keyframe-ease-segment]`, + ), + ); +} + +function revealEaseButton(segment: HTMLElement): HTMLButtonElement | null { + return segment.querySelector("button[data-keyframe-ease-button]"); +} + +const POSITION_SEGMENT_ANIMATION = animation("position-tween", "position", [ + { percentage: 0, properties: { x: 0 } }, + { percentage: 50, properties: { x: 50 } }, +]); + +describe("TimelinePropertyLanes", () => { + it("returns a position lane with synthesized endpoints for a flat tween", () => { + const lanes = getTimelinePropertyLanes( + [flatAnimation("position-tween", "position", { x: 420 })], + 0, + 1, + ); + + expect(lanes).toHaveLength(1); + expect(lanes[0]?.group).toBe("position"); + expect(lanes[0]?.keyframes).toEqual([ + { + percentage: 0, + tweenPercentage: 0, + properties: { x: 0 }, + propertyGroup: "position", + animationId: "position-tween", + }, + { + percentage: 100, + tweenPercentage: 100, + properties: { x: 420 }, + propertyGroup: "position", + animationId: "position-tween", + }, + ]); + }); + + it("returns both flat and authored keyframe property groups", () => { + const lanes = getTimelinePropertyLanes( + [ + flatAnimation("position-tween", "position", { x: 420 }), + animation("visual-tween", "visual", [ + { percentage: 0, properties: { opacity: 0 } }, + { percentage: 100, properties: { opacity: 1 } }, + ]), + ], + 0, + 1, + ); + + expect(lanes.map((lane) => lane.group)).toEqual(["position", "visual"]); + expect(lanes.map((lane) => lane.keyframes.map((keyframe) => keyframe.percentage))).toEqual([ + [0, 100], + [0, 100], + ]); + }); + + it("renders each source property group at its independent keyframe positions", () => { + const animations = [ + animation("position-tween", "position", [ + { percentage: 0, properties: { x: 0, y: 0 } }, + { percentage: 50, properties: { x: 100, y: 20 } }, + { percentage: 100, properties: { x: 200, y: 40 } }, + ]), + animation("visual-tween", "visual", [{ percentage: 25, properties: { opacity: 0.5 } }]), + ]; + + const { host, root } = renderPropertyLanes({ animations }); + const position = laneDiamonds(host, "position"); + const visual = laneDiamonds(host, "visual"); + + expect(position).toHaveLength(3); + expect(visual).toHaveLength(1); + // Diamonds are centered on their true keyframe time (0% at -half); the + // reserved left gutter (content origin inset, tested at the Timeline level) + // keeps the overflowing left half visible rather than clamping it inward. + expect(position.map((diamond) => diamond.style.left)).toEqual(["-11px", "89px", "189px"]); + expect(visual[0]?.style.left).toBe("39px"); + expect( + host.querySelectorAll('[data-property-group="position"] [data-keyframe-connector]'), + ).toHaveLength(2); + act(() => root.unmount()); + }); + + it("keeps both groups' diamonds when their source keyframes share 0% and 100%", () => { + const animations = [ + animation("position-tween", "position", [ + { percentage: 0, properties: { x: 0 } }, + { percentage: 100, properties: { x: 100 } }, + ]), + animation("visual-tween", "visual", [ + { percentage: 0, properties: { opacity: 0 } }, + { percentage: 100, properties: { opacity: 1 } }, + ]), + ]; + + const { host, root } = renderPropertyLanes({ animations }); + + expectLanePercentages(host, "position", ["0", "100"]); + expectLanePercentages(host, "visual", ["0", "100"]); + act(() => root.unmount()); + }); + + it("renders an authored hold keyframe whose value equals its predecessor", () => { + const animations = [ + animation("position-tween", "position", [ + { percentage: 0, properties: { x: 10 } }, + { percentage: 50, properties: { x: 10 } }, + { percentage: 100, properties: { x: 20 } }, + ]), + ]; + + const { host, root } = renderPropertyLanes({ animations }); + + expectLanePercentages(host, "position", ["0", "50", "100"]); + act(() => root.unmount()); + }); + + it("keeps Position@50% selection distinct from Opacity@50%", () => { + const onClickKeyframe = vi.fn(); + const animations = [ + animation("position-tween", "position", [{ percentage: 50, properties: { x: 50 } }]), + animation("visual-tween", "visual", [{ percentage: 50, properties: { opacity: 0.5 } }]), + ]; + const { host, root } = renderPropertyLanes({ animations, onClickKeyframe }); + const position = laneDiamonds(host, "position")[0]!; + + act(() => { + position.dispatchEvent(new MouseEvent("pointerup", { bubbles: true, button: 0 })); + }); + + const target = onClickKeyframe.mock.calls[0]?.[0]; + expect(target).toEqual({ + animationId: "position-tween", + percentage: 50, + propertyGroup: "position", + tweenPercentage: 50, + }); + + act(() => { + root.render( + , + ); + }); + + const positionFill = laneDiamonds(host, "position")[0]?.querySelector("path:last-child"); + const visualFill = laneDiamonds(host, "visual")[0]?.querySelector("path:last-child"); + expect(positionFill?.getAttribute("fill")).toBe("#4ba3d2"); + expect(visualFill?.getAttribute("fill")).toBe("#a3a3a3"); + act(() => root.unmount()); + }); + + it("keeps one accessible midpoint ease button per segment, regardless of selection", () => { + const animations = [ + animation("position-tween", "position", [ + { percentage: 0, properties: { x: 0 } }, + { percentage: 50, properties: { x: 50 } }, + { percentage: 100, properties: { x: 100 } }, + ]), + ]; + const { host, root } = renderPropertyLanes({ animations, onSelectSegment: vi.fn() }); + + const segments = laneEaseSegments(host, "position"); + expect(segments).toHaveLength(2); + expect(segments.map((segment) => segment.style.left)).toEqual(["0px", "100px"]); + expect(laneDiamonds(host, "position")).toHaveLength(3); + const buttons = laneEaseButtons(host, "position"); + expect(buttons).toHaveLength(2); + expect(buttons.every((button) => button.classList.contains("opacity-0"))).toBe(true); + expect(buttons.every((button) => button.classList.contains("group-hover:opacity-100"))).toBe( + true, + ); + expect(buttons.every((button) => button.classList.contains("focus-visible:opacity-100"))).toBe( + true, + ); + + // The ease button is available on hover even when the element is NOT selected + // (a lane shows for the track's active/primary clip, not only the selected one). + act(() => { + root.render( + , + ); + }); + const unselectedSegments = laneEaseSegments(host, "position"); + expect(unselectedSegments).toHaveLength(2); + expect(revealEaseButton(unselectedSegments[0]!)).not.toBeNull(); + act(() => root.unmount()); + }); + + it("reveals each segment's button with its destination keyframe ease curve", () => { + const animations = [ + animation("position-tween", "position", [ + { percentage: 0, properties: { x: 0 } }, + { percentage: 33, properties: { x: 33 }, ease: "none" }, + { percentage: 66, properties: { x: 66 }, ease: "power2.out" }, + { + percentage: 100, + properties: { x: 100 }, + ease: "custom(M0,0 C0.1,0.2 0.3,0.9 1,1)", + }, + ]), + ]; + const { host, root } = renderPropertyLanes({ animations, onSelectSegment: vi.fn() }); + + const segments = laneEaseSegments(host, "position"); + expect(segments).toHaveLength(3); + const paths = segments.map((segment) => + revealEaseButton(segment)?.querySelector("path")?.getAttribute("d"), + ); + expect(paths).toHaveLength(3); + expect(new Set(paths).size).toBe(3); + act(() => root.unmount()); + }); + + it("selects the destination keyframe when a hovered segment's ease button is clicked", () => { + const onSelectSegment = vi.fn(); + const { host, root } = renderPropertyLanes({ + animations: [POSITION_SEGMENT_ANIMATION], + onSelectSegment, + }); + + const button = revealEaseButton(laneEaseSegments(host, "position")[0]!); + act(() => button?.click()); + + expect(onSelectSegment).toHaveBeenCalledWith({ + animationId: "position-tween", + percentage: 50, + propertyGroup: "position", + tweenPercentage: 50, + }); + act(() => root.unmount()); + }); + + it("routes a colliding Position segment to the Position animation", () => { + const onSelectSegment = vi.fn(); + const animations = [ + POSITION_SEGMENT_ANIMATION, + animation("visual-tween", "visual", [ + { percentage: 0, properties: { opacity: 0 } }, + { percentage: 50, properties: { opacity: 0.5 } }, + ]), + ]; + const { host, root } = renderPropertyLanes({ animations, onSelectSegment }); + + const button = revealEaseButton(laneEaseSegments(host, "position")[0]!); + act(() => button?.click()); + + expect(onSelectSegment.mock.calls[0]?.[0]).toMatchObject({ + animationId: "position-tween", + propertyGroup: "position", + }); + act(() => root.unmount()); + }); + + it("keeps the collapsed TimelineClipDiamonds positions and callback contract unchanged", () => { + const onClickKeyframe = vi.fn(); + const host = document.createElement("div"); + document.body.append(host); + const root = createRoot(host); + act(() => { + root.render( + , + ); + }); + const diamonds = Array.from(host.querySelectorAll("button")); + + // Unified keyframe-diamond size (LANE_H·ratio ≈ 22px, half 11) on collapsed + // clips too, so 0% sits at -11px regardless of clip-bar height. + expect(diamonds.map((diamond) => diamond.style.left)).toEqual(["-11px", "89px"]); + expect(diamonds[1]?.querySelector("path:last-child")?.getAttribute("fill")).toBe("#4ba3d2"); + act(() => { + diamonds[1]?.dispatchEvent(new MouseEvent("pointerup", { bubbles: true, button: 0 })); + }); + expect(onClickKeyframe).toHaveBeenCalledWith(50); + act(() => root.unmount()); + }); +}); diff --git a/packages/studio/src/player/components/TimelinePropertyLanes.tsx b/packages/studio/src/player/components/TimelinePropertyLanes.tsx new file mode 100644 index 0000000000..bd518e7727 --- /dev/null +++ b/packages/studio/src/player/components/TimelinePropertyLanes.tsx @@ -0,0 +1,163 @@ +import type { MouseEvent as ReactMouseEvent, RefObject } from "react"; +import { + classifyPropertyGroup, + type GsapAnimation, + type PropertyGroupName, +} from "@hyperframes/core/gsap-parser"; +import { toAbsoluteTime } from "../../hooks/gsapShared"; +import { synthesizeFlatTweenKeyframes } from "../../hooks/gsapTweenSynth"; +import { TimelineDiamondLane, type TimelineDiamondKeyframe } from "./TimelineClipDiamonds"; +import { LANE_H, getTimelineLaneTop } from "./timelineLayout"; +import type { TimelineKeyframeTarget } from "./timelineKeyframeIdentity"; + +export interface TimelinePropertyLanesProps { + animations: readonly GsapAnimation[]; + clipStart: number; + clipDuration: number; + clipLeftPx: number; + clipWidthPx: number; + accentColor: string; + isSelected: boolean; + currentPercentage: number; + elementId: string; + selectedKeyframes: ReadonlySet; + onSelectSegment?: (target: TimelineKeyframeTarget) => void; + onClickKeyframe?: (target: TimelineKeyframeTarget) => void; + onShiftClickKeyframe?: (target: TimelineKeyframeTarget) => void; + onContextMenuKeyframe?: (e: ReactMouseEvent, target: TimelineKeyframeTarget) => void; + onMoveKeyframe?: (target: TimelineKeyframeTarget, toClipPercentage: number) => Promise; + suppressClickRef?: RefObject; +} + +function hasGroupProperty( + properties: Record, + group: PropertyGroupName, +): boolean { + return Object.keys(properties).some((property) => classifyPropertyGroup(property) === group); +} + +/** The tween's editable keyframes: its real keyframes, or the start→end pair + * synthesized for a flat tween. Empty for a tween that animates nothing. */ +function animationKeyframes(animation: GsapAnimation) { + return animation.keyframes?.keyframes ?? synthesizeFlatTweenKeyframes(animation)?.keyframes ?? []; +} + +/** A tween contributes a property lane when it has a group and at least one + * editable keyframe (real or synthesized). */ +export function animationContributesLane(animation: GsapAnimation): boolean { + return !!animation.propertyGroup && animationKeyframes(animation).length > 0; +} + +function sourceGroups(animations: readonly GsapAnimation[]) { + const groups = new Map(); + for (const animation of animations) { + if (!animation.propertyGroup || !animationContributesLane(animation)) continue; + const groupAnimations = groups.get(animation.propertyGroup) ?? []; + groupAnimations.push(animation); + groups.set(animation.propertyGroup, groupAnimations); + } + return groups; +} + +function groupKeyframes( + animations: readonly GsapAnimation[], + group: PropertyGroupName, + clipStart: number, + clipDuration: number, +): TimelineDiamondKeyframe[] { + const keyframes: TimelineDiamondKeyframe[] = []; + for (const animation of animations) { + const tweenStart = + animation.resolvedStart ?? (typeof animation.position === "number" ? animation.position : 0); + const tweenDuration = animation.duration ?? clipDuration; + for (const keyframe of animationKeyframes(animation)) { + if (!hasGroupProperty(keyframe.properties, group)) continue; + const absoluteTime = toAbsoluteTime(tweenStart, tweenDuration, keyframe.percentage); + keyframes.push({ + ...keyframe, + percentage: ((absoluteTime - clipStart) / clipDuration) * 100, + tweenPercentage: keyframe.percentage, + propertyGroup: group, + animationId: animation.id, + }); + } + } + return keyframes; +} + +export function getTimelinePropertyLanes( + animations: readonly GsapAnimation[], + clipStart: number, + clipDuration: number, +) { + if (clipDuration <= 0) return []; + return Array.from(sourceGroups(animations), ([group, groupAnimations]) => ({ + group, + animations: groupAnimations, + keyframes: groupKeyframes(groupAnimations, group, clipStart, clipDuration), + })).filter((lane) => lane.keyframes.length > 0); +} + +export function TimelinePropertyLanes({ + animations, + clipStart, + clipDuration, + clipLeftPx, + clipWidthPx, + accentColor, + isSelected, + currentPercentage, + elementId, + selectedKeyframes, + onSelectSegment, + onClickKeyframe, + onShiftClickKeyframe, + onContextMenuKeyframe, + onMoveKeyframe, + suppressClickRef, +}: TimelinePropertyLanesProps) { + if (clipWidthPx < 20 || clipDuration <= 0) return null; + const lanes = getTimelinePropertyLanes(animations, clipStart, clipDuration); + + if (lanes.length === 0) return null; + return ( + <> + {lanes.map(({ group, animations: groupAnimations, keyframes }, laneIndex) => ( +
+ +
+ ))} + + ); +} diff --git a/packages/studio/src/player/components/TimelineTrackHeader.test.tsx b/packages/studio/src/player/components/TimelineTrackHeader.test.tsx new file mode 100644 index 0000000000..57d6fb127c --- /dev/null +++ b/packages/studio/src/player/components/TimelineTrackHeader.test.tsx @@ -0,0 +1,262 @@ +// @vitest-environment happy-dom + +import React, { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import type { GsapAnimation, PropertyGroupName } from "@hyperframes/core/gsap-parser"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { TimelinePropertyLanes } from "./TimelinePropertyLanes"; +import { TimelineTrackHeader } from "./TimelineTrackHeader"; +import { defaultTimelineTheme } from "./timelineTheme"; +import type { TimelineElement } from "../store/playerStore"; +import type { TimelineEditCallbacks } from "./timelineCallbacks"; +import { LABEL_COL_W } from "./timelineLayout"; + +(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +afterEach(() => { + document.body.innerHTML = ""; +}); + +const ELEMENT: TimelineElement = { + id: "clip-1", + label: "Hero card", + tag: "div", + start: 0, + duration: 2, + track: 0, +}; + +function animation( + id: string, + propertyGroup: PropertyGroupName, + keyframes: Array<{ + percentage: number; + properties: Record; + }>, +): GsapAnimation { + return { + id, + targetSelector: "#clip-1", + method: "to", + position: 0, + duration: 2, + properties: {}, + propertyGroup, + keyframes: { format: "percentage", keyframes }, + }; +} + +const POSITION = animation("position-tween", "position", [ + { percentage: 0, properties: { x: 0, y: 0 } }, + { percentage: 50, properties: { x: 100, y: 50 } }, + { percentage: 100, properties: { x: 200, y: 100 } }, +]); + +const OPACITY = animation("opacity-tween", "visual", [ + { percentage: 0, properties: { opacity: 0 } }, + { percentage: 50, properties: { opacity: 0.5 } }, + { percentage: 100, properties: { opacity: 1 } }, +]); + +interface RenderHeaderOptions { + animations?: GsapAnimation[]; + currentTime?: number; + expanded?: boolean; + onSeek?: (time: number) => void; + onTogglePropertyGroupKeyframe?: TimelineEditCallbacks["onTogglePropertyGroupKeyframe"]; +} + +function renderHeader(options: RenderHeaderOptions = {}): { + host: HTMLDivElement; + root: Root; + rerender: (next: RenderHeaderOptions) => void; +} { + const host = document.createElement("div"); + document.body.append(host); + const root = createRoot(host); + const render = (next: RenderHeaderOptions) => { + act(() => { + root.render( + , + ); + }); + }; + render(options); + return { host, root, rerender: render }; +} + +function click(host: HTMLElement, label: string) { + const button = host.querySelector(`button[aria-label="${label}"]`); + expect(button).not.toBeNull(); + act(() => button?.click()); +} + +describe("TimelineTrackHeader", () => { + it("adds and removes a keyframe on the explicitly targeted property-group tween", () => { + const onTogglePropertyGroupKeyframe = vi.fn(); + const view = renderHeader({ currentTime: 0.5, onTogglePropertyGroupKeyframe }); + + click(view.host, "Toggle Opacity keyframe"); + expect(onTogglePropertyGroupKeyframe).toHaveBeenLastCalledWith( + ELEMENT, + expect.objectContaining({ + animationId: "opacity-tween", + propertyGroup: "visual", + tweenPercentage: 25, + properties: { opacity: 0.25 }, + remove: false, + }), + ); + + view.rerender({ currentTime: 1, onTogglePropertyGroupKeyframe }); + click(view.host, "Toggle Opacity keyframe"); + expect(onTogglePropertyGroupKeyframe).toHaveBeenLastCalledWith( + ELEMENT, + expect.objectContaining({ + animationId: "opacity-tween", + propertyGroup: "visual", + tweenPercentage: 50, + properties: { opacity: 0.5 }, + remove: true, + }), + ); + expect(onTogglePropertyGroupKeyframe).not.toHaveBeenCalledWith( + ELEMENT, + expect.objectContaining({ animationId: "position-tween" }), + ); + act(() => view.root.unmount()); + }); + + it("seeks only to the selected group's adjacent keyframes", () => { + const onSeek = vi.fn(); + const view = renderHeader({ + currentTime: 1, + animations: [ + POSITION, + animation("opacity-tween", "visual", [ + { percentage: 25, properties: { opacity: 0.25 } }, + { percentage: 50, properties: { opacity: 0.5 } }, + { percentage: 75, properties: { opacity: 0.75 } }, + ]), + ], + onSeek, + }); + + click(view.host, "Next Position keyframe"); + expect(onSeek).toHaveBeenLastCalledWith(2); + click(view.host, "Previous Position keyframe"); + expect(onSeek).toHaveBeenLastCalledWith(0); + expect(onSeek).not.toHaveBeenCalledWith(1.5); + act(() => view.root.unmount()); + }); + + it("fills the toggle diamond exactly at that group's keyframe", () => { + const view = renderHeader({ currentTime: 0.5 }); + const positionToggle = view.host.querySelector( + 'button[aria-label="Toggle Position keyframe"]', + ); + expect(positionToggle?.textContent).toBe("◇"); + + view.rerender({ currentTime: 1 }); + expect( + view.host.querySelector('button[aria-label="Toggle Position keyframe"]') + ?.textContent, + ).toBe("◆"); + act(() => view.root.unmount()); + }); + + it("updates formatted group values when the playhead moves", () => { + const view = renderHeader({ currentTime: 0.5 }); + expect(view.host.querySelector('[data-property-group="position"]')?.textContent).toContain( + "50, 25", + ); + expect(view.host.querySelector('[data-property-group="visual"]')?.textContent).toContain("25%"); + + view.rerender({ currentTime: 1.5 }); + expect(view.host.querySelector('[data-property-group="position"]')?.textContent).toContain( + "150, 75", + ); + expect(view.host.querySelector('[data-property-group="visual"]')?.textContent).toContain("75%"); + act(() => view.root.unmount()); + }); + + it("disables the previous chevron at or before the group's first keyframe", () => { + const view = renderHeader({ currentTime: 0 }); + const prevAt0 = view.host.querySelector( + 'button[aria-label="Previous Position keyframe"]', + ); + expect(prevAt0).not.toBeNull(); + expect(prevAt0?.disabled).toBe(true); + + view.rerender({ currentTime: 1 }); + const prevAt1 = view.host.querySelector( + 'button[aria-label="Previous Position keyframe"]', + ); + expect(prevAt1?.disabled).toBe(false); + act(() => view.root.unmount()); + }); + + it("uses the same lane row offsets when collapsed, expanded once, and expanded multiple times", () => { + const view = renderHeader({ expanded: false }); + expect(view.host.querySelectorAll("[data-timeline-lane-top]")).toHaveLength(0); + + const assertAligned = (animations: GsapAnimation[]) => { + view.rerender({ animations }); + const lanesHost = document.createElement("div"); + document.body.append(lanesHost); + const lanesRoot = createRoot(lanesHost); + act(() => { + lanesRoot.render( + , + ); + }); + expect( + Array.from(view.host.querySelectorAll("[data-timeline-lane-top]")).map( + (row) => row.style.top, + ), + ).toEqual( + Array.from(lanesHost.querySelectorAll("[data-timeline-lane-top]")).map( + (row) => row.style.top, + ), + ); + expect( + Array.from(lanesHost.querySelectorAll("[data-timeline-property-lane]")).map( + (row) => row.style.left, + ), + ).toEqual(animations.map(() => "120px")); + act(() => lanesRoot.unmount()); + }; + + assertAligned([POSITION]); + assertAligned([POSITION, OPACITY]); + act(() => view.root.unmount()); + }); +}); diff --git a/packages/studio/src/player/components/TimelineTrackHeader.tsx b/packages/studio/src/player/components/TimelineTrackHeader.tsx new file mode 100644 index 0000000000..e27812aab9 --- /dev/null +++ b/packages/studio/src/player/components/TimelineTrackHeader.tsx @@ -0,0 +1,552 @@ +import { useState } from "react"; +import { Eye, EyeSlash } from "@phosphor-icons/react"; +import { + classifyPropertyGroup, + type GsapAnimation, + type PropertyGroupName, +} from "@hyperframes/core/gsap-parser"; +import { + clipToTweenPercentage, + getKeyframeNavigationState, +} from "../../components/editor/KeyframeNavigation"; +import { Music } from "../../icons/SystemIcons"; +import { + absoluteToPercentageForAnimation, + isTimeWithinTween, + resolveTweenDuration, + resolveTweenStart, +} from "../../utils/globalTimeCompiler"; +import type { TimelineElement } from "../store/playerStore"; +import type { + TimelineEditCallbacks, + TimelinePropertyGroupKeyframeToggle, +} from "./timelineCallbacks"; +import { getTimelinePropertyLanes } from "./TimelinePropertyLanes"; +import { LayerDisclosureRow } from "./LayerDisclosureRow"; +import { LABEL_COL_W, LANE_H, getTimelineLaneTop } from "./timelineLayout"; +import type { TimelineTheme } from "./timelineTheme"; + +interface TimelineTrackHeaderProps { + trackNumber: number; + trackLabel: string; + contentOrigin: number; + /** The track's active keyframe clip (selected, else primary) — the one whose + * disclosure + property rows this header shows, whether expanded or not. */ + keyframeClip: TimelineElement | null; + isExpanded: boolean; + animations: readonly GsapAnimation[]; + currentTime: number; + isTrackHidden: boolean; + isAudioTrack: boolean; + isActive: boolean; + isHovered: boolean; + theme: TimelineTheme; + onToggleClipExpanded: () => void; + onToggleTrackHidden: TimelineEditCallbacks["onToggleTrackHidden"]; + onTogglePropertyGroupKeyframe?: TimelineEditCallbacks["onTogglePropertyGroupKeyframe"]; + onSeek?: (time: number) => void; +} + +function roundValue(value: number): string { + return String(Math.round(value * 100) / 100); +} + +function propertyValueAt( + animation: GsapAnimation, + property: string, + tweenPercentage: number, +): number | string | undefined { + const keyframes = animation.keyframes?.keyframes ?? []; + const values = keyframes + .filter((keyframe) => property in keyframe.properties) + .map((keyframe) => ({ + percentage: keyframe.percentage, + value: keyframe.properties[property], + })); + const before = values.filter((value) => value.percentage <= tweenPercentage).at(-1); + const after = values.find((value) => value.percentage >= tweenPercentage); + if (!before) return after?.value; + if (!after) return before.value; + if ( + typeof before.value !== "number" || + typeof after.value !== "number" || + before.percentage === after.percentage + ) { + return before.value; + } + const progress = (tweenPercentage - before.percentage) / (after.percentage - before.percentage); + return before.value + (after.value - before.value) * progress; +} + +function valuesAt( + animation: GsapAnimation, + group: PropertyGroupName, + tweenPercentage: number, +): Record { + const propertyNames = new Set(); + for (const keyframe of animation.keyframes?.keyframes ?? []) { + for (const property of Object.keys(keyframe.properties)) { + if (classifyPropertyGroup(property) === group) propertyNames.add(property); + } + } + const values: Record = {}; + for (const property of propertyNames) { + const value = propertyValueAt(animation, property, tweenPercentage); + if (value !== undefined) values[property] = value; + } + return values; +} + +function groupLabel(group: PropertyGroupName, properties: Record): string { + if (group === "visual" && ("opacity" in properties || "autoAlpha" in properties)) { + return "Opacity"; + } + if (group !== "other") return `${group[0]?.toUpperCase() ?? ""}${group.slice(1)}`; + const property = Object.keys(properties)[0]; + return property ? `${property[0]?.toUpperCase() ?? ""}${property.slice(1)}` : "Other"; +} + +type LaneValues = Record; + +function defaultValueReadout(values: LaneValues): string { + return Object.values(values) + .map((value) => (typeof value === "number" ? roundValue(value) : value)) + .join(", "); +} + +function positionValueReadout(values: LaneValues): string | null { + const x = values.x; + const y = values.y; + return typeof x === "number" && typeof y === "number" + ? `${roundValue(x)}, ${roundValue(y)}` + : null; +} + +function rotationValueReadout(values: LaneValues): string | null { + return typeof values.rotation === "number" ? `${roundValue(values.rotation)}°` : null; +} + +function visualValueReadout(values: LaneValues): string | null { + const opacity = values.opacity ?? values.autoAlpha; + return typeof opacity === "number" + ? `${roundValue(Math.abs(opacity) <= 1 ? opacity * 100 : opacity)}%` + : null; +} + +const GROUP_VALUE_READOUTS: Partial< + Record string | null> +> = { + position: positionValueReadout, + rotation: rotationValueReadout, + visual: visualValueReadout, +}; + +function valueReadout(group: PropertyGroupName, values: Record): string { + return GROUP_VALUE_READOUTS[group]?.(values) ?? defaultValueReadout(values); +} + +function VisibilityButton({ + hidden, + trackNumber, + visible, + onToggle, +}: { + hidden: boolean; + trackNumber: number; + visible: boolean; + onToggle: TimelineEditCallbacks["onToggleTrackHidden"]; +}) { + if (!visible) return