mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-19 19:36:04 +00:00
Merge pull request #2695 from heygen-com/codex/studio-timeline-c-ease-mode-switch-v2
fix(studio): switch keyframe ease modes optimistically
This commit is contained in:
@@ -110,6 +110,12 @@
|
||||
"types": "./dist/runtime/clipTree.d.ts",
|
||||
"environments": ["browser", "bun", "node"]
|
||||
},
|
||||
"./runtime/custom-ease": {
|
||||
"source": "./src/runtime/customEase.ts",
|
||||
"runtime": "./dist/runtime/customEase.js",
|
||||
"types": "./dist/runtime/customEase.d.ts",
|
||||
"environments": ["browser", "bun", "node"]
|
||||
},
|
||||
"./runtime/start-expression": {
|
||||
"source": "./src/runtime/startExpression.ts",
|
||||
"runtime": "./dist/runtime/startExpression.js",
|
||||
|
||||
@@ -119,6 +119,12 @@
|
||||
"import": "./src/runtime/clipTree.ts",
|
||||
"types": "./src/runtime/clipTree.ts"
|
||||
},
|
||||
"./runtime/custom-ease": {
|
||||
"bun": "./src/runtime/customEase.ts",
|
||||
"node": "./dist/runtime/customEase.js",
|
||||
"import": "./src/runtime/customEase.ts",
|
||||
"types": "./src/runtime/customEase.ts"
|
||||
},
|
||||
"./runtime/start-expression": {
|
||||
"bun": "./src/runtime/startExpression.ts",
|
||||
"node": "./dist/runtime/startExpression.js",
|
||||
@@ -353,6 +359,10 @@
|
||||
"import": "./dist/runtime/clipTree.js",
|
||||
"types": "./dist/runtime/clipTree.d.ts"
|
||||
},
|
||||
"./runtime/custom-ease": {
|
||||
"import": "./dist/runtime/customEase.js",
|
||||
"types": "./dist/runtime/customEase.d.ts"
|
||||
},
|
||||
"./runtime/start-expression": {
|
||||
"import": "./dist/runtime/startExpression.js",
|
||||
"types": "./dist/runtime/startExpression.d.ts"
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
},
|
||||
"files": [
|
||||
"src/runtime/clipTree.ts",
|
||||
"src/runtime/customEase.ts",
|
||||
"src/runtime/mediaVolumeEnvelope.ts",
|
||||
"src/runtime/positionEdits.ts",
|
||||
"src/runtime/protocol.ts",
|
||||
|
||||
@@ -19,7 +19,6 @@ import type { EditHistoryKind } from "../utils/editHistory";
|
||||
import { useSlideshowPersist, type UseSlideshowPersistParams } from "../hooks/useSlideshowPersist";
|
||||
import { useSlideshowTabState } from "../hooks/useSlideshowTabState";
|
||||
import { DesignPanelPromoteProvider } from "./DesignPanelPromoteProvider";
|
||||
|
||||
import { useStudioPlaybackContext, useStudioShellContext } from "../contexts/StudioContext";
|
||||
import { usePanelLayoutContext } from "../contexts/PanelLayoutContext";
|
||||
import { useFileManagerContext } from "../contexts/FileManagerContext";
|
||||
@@ -156,6 +155,7 @@ export function StudioRightPanel({
|
||||
handleUpdateArcSegment,
|
||||
handleUnroll,
|
||||
handleUpdateKeyframeEase,
|
||||
handleUpdateSegmentEase,
|
||||
handleSetAllKeyframeEases,
|
||||
handleGsapAddKeyframe,
|
||||
handleGsapRemoveKeyframe,
|
||||
@@ -406,6 +406,7 @@ export function StudioRightPanel({
|
||||
onUnroll={handleUnroll}
|
||||
onUpdateKeyframeEase={handleUpdateKeyframeEase}
|
||||
onSetAllKeyframeEases={handleSetAllKeyframeEases}
|
||||
onUpdateSegmentEase={handleUpdateSegmentEase}
|
||||
recordingState={recordingState}
|
||||
recordingDuration={recordingDuration}
|
||||
onToggleRecording={onToggleRecording}
|
||||
|
||||
@@ -2,39 +2,98 @@
|
||||
|
||||
import React, { act } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import type { GsapAnimation } from "@hyperframes/core/gsap-parser";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { AnimationCard } from "./AnimationCard";
|
||||
import type { GsapAnimation } from "@hyperframes/core/gsap-parser";
|
||||
import { EASE_PRESETS } from "./easePresetLibrary";
|
||||
import type { AnimationKeyframeTarget } from "../../hooks/gsapTweenSynth";
|
||||
|
||||
const trackStudioSegmentEaseEdit = vi.hoisted(() => vi.fn());
|
||||
vi.mock("../../telemetry/events", () => ({ trackStudioSegmentEaseEdit }));
|
||||
|
||||
(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
const ANIMATION: GsapAnimation = {
|
||||
id: "position-tween",
|
||||
targetSelector: "#clip-1",
|
||||
method: "to",
|
||||
position: 0,
|
||||
duration: 2,
|
||||
ease: "power1.out",
|
||||
properties: { x: 200 },
|
||||
keyframes: {
|
||||
format: "percentage",
|
||||
keyframes: [
|
||||
{ percentage: 0, properties: { x: 0 } },
|
||||
{ percentage: 50, properties: { x: 100 } },
|
||||
{ percentage: 100, properties: { x: 200 } },
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const FLAT_ANIMATION: GsapAnimation = {
|
||||
...ANIMATION,
|
||||
id: "flat-position-tween",
|
||||
keyframes: undefined,
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = "";
|
||||
trackStudioSegmentEaseEdit.mockClear();
|
||||
});
|
||||
|
||||
function baseAnimation(overrides: Partial<GsapAnimation> = {}): GsapAnimation {
|
||||
return {
|
||||
id: "anim-1",
|
||||
method: "to",
|
||||
position: 0.8,
|
||||
duration: 1.2,
|
||||
ease: "power2.out",
|
||||
properties: { opacity: 1 },
|
||||
...overrides,
|
||||
} as GsapAnimation;
|
||||
function renderFocusCard(
|
||||
focusedSegment: {
|
||||
tweenPercentage: number;
|
||||
collidingAnimationTargets?: AnimationKeyframeTarget[];
|
||||
} | null,
|
||||
onEaseCommit = vi.fn(),
|
||||
defaultExpanded = false,
|
||||
animation = ANIMATION,
|
||||
onUpdateMeta = vi.fn(),
|
||||
onUpdateSegmentEase = vi.fn(),
|
||||
) {
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const root = createRoot(host);
|
||||
const render = (nextFocusedSegment: { tweenPercentage: number } | null) => {
|
||||
act(() => {
|
||||
root.render(
|
||||
<AnimationCard
|
||||
animation={animation}
|
||||
defaultExpanded={defaultExpanded}
|
||||
focusedSegment={nextFocusedSegment}
|
||||
onFocusSegmentConsumed={vi.fn()}
|
||||
onUpdateProperty={vi.fn()}
|
||||
onUpdateMeta={onUpdateMeta}
|
||||
onDeleteAnimation={vi.fn()}
|
||||
onAddProperty={vi.fn()}
|
||||
onRemoveProperty={vi.fn()}
|
||||
onUpdateKeyframeEase={onEaseCommit}
|
||||
onUpdateSegmentEase={onUpdateSegmentEase}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
};
|
||||
render(focusedSegment);
|
||||
return { host, root, render };
|
||||
}
|
||||
|
||||
const noop = () => {};
|
||||
function findButton(host: HTMLElement, text: string): HTMLButtonElement | undefined {
|
||||
return Array.from(host.querySelectorAll("button")).find((button) =>
|
||||
button.textContent?.includes(text),
|
||||
);
|
||||
}
|
||||
|
||||
function openSegment(host: HTMLElement, label: string): void {
|
||||
const segment = findButton(host, label);
|
||||
expect(segment).toBeDefined();
|
||||
act(() => segment?.click());
|
||||
}
|
||||
|
||||
function selectPreset(host: HTMLElement, presetId: string): string {
|
||||
const presetConfig = EASE_PRESETS.find((candidate) => candidate.id === presetId);
|
||||
if (!presetConfig) throw new Error(`Missing ease preset: ${presetId}`);
|
||||
|
||||
const dropdown = host.querySelector<HTMLButtonElement>("[data-ease-type-dropdown]");
|
||||
expect(dropdown).not.toBeNull();
|
||||
act(() => dropdown?.click());
|
||||
@@ -45,6 +104,8 @@ function selectPreset(host: HTMLElement, presetId: string): string {
|
||||
return presetConfig.ease;
|
||||
}
|
||||
|
||||
const noop = () => {};
|
||||
|
||||
/** Every test mounts the same card; only expansion, flat mode, and the spies differ. */
|
||||
function renderCard({
|
||||
animation = baseAnimation(),
|
||||
@@ -82,7 +143,157 @@ function renderCard({
|
||||
return { host, root };
|
||||
}
|
||||
|
||||
function restoreScrollIntoView(descriptor: PropertyDescriptor | undefined): void {
|
||||
if (descriptor) Object.defineProperty(HTMLElement.prototype, "scrollIntoView", descriptor);
|
||||
else Reflect.deleteProperty(HTMLElement.prototype, "scrollIntoView");
|
||||
}
|
||||
|
||||
describe("AnimationCard", () => {
|
||||
it("scrolls a focused segment into view but not a manually toggled segment", () => {
|
||||
const originalScrollIntoView = Object.getOwnPropertyDescriptor(
|
||||
HTMLElement.prototype,
|
||||
"scrollIntoView",
|
||||
);
|
||||
const scrollIntoView = vi.fn();
|
||||
Object.defineProperty(HTMLElement.prototype, "scrollIntoView", {
|
||||
configurable: true,
|
||||
value: scrollIntoView,
|
||||
});
|
||||
|
||||
const view = renderFocusCard({ tweenPercentage: 50 });
|
||||
try {
|
||||
expect(scrollIntoView).toHaveBeenCalledOnce();
|
||||
expect(scrollIntoView).toHaveBeenCalledWith({ block: "nearest", behavior: "smooth" });
|
||||
|
||||
view.render(null);
|
||||
const manualToggle = findButton(view.host, "50% → 100%");
|
||||
expect(manualToggle).toBeDefined();
|
||||
act(() => manualToggle?.click());
|
||||
expect(scrollIntoView).toHaveBeenCalledOnce();
|
||||
} finally {
|
||||
act(() => view.root.unmount());
|
||||
restoreScrollIntoView(originalScrollIntoView);
|
||||
}
|
||||
});
|
||||
|
||||
it("tracks a committed segment ease alongside the existing update", () => {
|
||||
const onEaseCommit = vi.fn();
|
||||
const view = renderFocusCard(null, onEaseCommit, true);
|
||||
openSegment(view.host, "0% → 50%");
|
||||
const ease = selectPreset(view.host, "quad-out");
|
||||
|
||||
expect(onEaseCommit).toHaveBeenCalledWith(ANIMATION.id, 50, ease);
|
||||
expect(trackStudioSegmentEaseEdit).toHaveBeenCalledWith({ action: "commit", ease });
|
||||
act(() => view.root.unmount());
|
||||
});
|
||||
|
||||
it("commits a focused multi-id segment ease through the bulk callback", () => {
|
||||
const onUpdateKeyframeEase = vi.fn();
|
||||
const onUpdateSegmentEase = vi.fn();
|
||||
const collidingAnimationTargets = [
|
||||
{ animationId: ANIMATION.id, tweenPercentage: 50 },
|
||||
{ animationId: "scale-tween", tweenPercentage: 75 },
|
||||
{ animationId: "opacity-tween", tweenPercentage: 25 },
|
||||
];
|
||||
const view = renderFocusCard(
|
||||
{ tweenPercentage: 50, collidingAnimationTargets },
|
||||
onUpdateKeyframeEase,
|
||||
false,
|
||||
ANIMATION,
|
||||
vi.fn(),
|
||||
onUpdateSegmentEase,
|
||||
);
|
||||
const ease = selectPreset(view.host, "quad-out");
|
||||
|
||||
expect(onUpdateSegmentEase).toHaveBeenCalledExactlyOnceWith(collidingAnimationTargets, ease);
|
||||
expect(onUpdateKeyframeEase).not.toHaveBeenCalled();
|
||||
act(() => view.root.unmount());
|
||||
});
|
||||
|
||||
it("keeps a focused single-id segment ease on the single callback", () => {
|
||||
const onUpdateKeyframeEase = vi.fn();
|
||||
const onUpdateSegmentEase = vi.fn();
|
||||
const view = renderFocusCard(
|
||||
{
|
||||
tweenPercentage: 50,
|
||||
collidingAnimationTargets: [{ animationId: ANIMATION.id, tweenPercentage: 50 }],
|
||||
},
|
||||
onUpdateKeyframeEase,
|
||||
false,
|
||||
ANIMATION,
|
||||
vi.fn(),
|
||||
onUpdateSegmentEase,
|
||||
);
|
||||
const ease = selectPreset(view.host, "quad-out");
|
||||
|
||||
expect(onUpdateKeyframeEase).toHaveBeenCalledExactlyOnceWith(ANIMATION.id, 50, ease);
|
||||
expect(onUpdateSegmentEase).not.toHaveBeenCalled();
|
||||
act(() => view.root.unmount());
|
||||
});
|
||||
|
||||
it("commits a focused flat tween segment ease through tween metadata", () => {
|
||||
const onUpdateMeta = vi.fn();
|
||||
const onUpdateKeyframeEase = vi.fn();
|
||||
const view = renderFocusCard(
|
||||
{ tweenPercentage: 100 },
|
||||
onUpdateKeyframeEase,
|
||||
false,
|
||||
FLAT_ANIMATION,
|
||||
onUpdateMeta,
|
||||
);
|
||||
const ease = selectPreset(view.host, "quad-out");
|
||||
|
||||
expect(onUpdateMeta).toHaveBeenCalledExactlyOnceWith(FLAT_ANIMATION.id, { ease });
|
||||
expect(onUpdateKeyframeEase).not.toHaveBeenCalled();
|
||||
act(() => view.root.unmount());
|
||||
});
|
||||
});
|
||||
|
||||
function baseAnimation(overrides: Partial<GsapAnimation> = {}): GsapAnimation {
|
||||
return {
|
||||
id: "anim-1",
|
||||
method: "to",
|
||||
position: 0.8,
|
||||
duration: 1.2,
|
||||
ease: "power2.out",
|
||||
properties: { opacity: 1 },
|
||||
...overrides,
|
||||
} as GsapAnimation;
|
||||
}
|
||||
|
||||
describe("AnimationCard ease editing", () => {
|
||||
it.each([
|
||||
["spring", "power2.out", "spring(0.42)", "Spring bounce"],
|
||||
["wiggle", "power2.out", "wiggle(3,easeInOut,0.12)", "Wiggle count"],
|
||||
["curve", "spring(0.6)", "custom(M0,0 C0.16,1 0.3,1 1,1)", "Cubic bezier control points"],
|
||||
] as const)(
|
||||
"commits and immediately displays the %s default when a keyframe segment switches mode",
|
||||
(mode, currentEase, ease, fieldLabel) => {
|
||||
const onUpdateKeyframeEase = vi.fn();
|
||||
const animation = baseAnimation({
|
||||
keyframes: {
|
||||
format: "percentage",
|
||||
keyframes: [
|
||||
{ percentage: 0, properties: { opacity: 0 } },
|
||||
{ percentage: 50, properties: { opacity: 0.5 }, ease: currentEase },
|
||||
{ percentage: 100, properties: { opacity: 1 } },
|
||||
],
|
||||
},
|
||||
});
|
||||
const view = renderFocusCard(null, onUpdateKeyframeEase, true, animation);
|
||||
|
||||
openSegment(view.host, "0% → 50%");
|
||||
const modeButton = view.host.querySelector<HTMLButtonElement>(`[data-ease-mode="${mode}"]`);
|
||||
expect(modeButton).not.toBeNull();
|
||||
act(() => modeButton?.click());
|
||||
|
||||
expect(onUpdateKeyframeEase).toHaveBeenCalledExactlyOnceWith(animation.id, 50, ease);
|
||||
expect(modeButton?.getAttribute("aria-checked")).toBe("true");
|
||||
expect(view.host.querySelector(`[aria-label="${fieldLabel}"]`)).not.toBeNull();
|
||||
act(() => view.root.unmount());
|
||||
},
|
||||
);
|
||||
|
||||
it("commits one preset change to the selected keyframe segment", () => {
|
||||
const onUpdateKeyframeEase = vi.fn();
|
||||
const animation = baseAnimation({
|
||||
@@ -97,11 +308,7 @@ describe("AnimationCard ease editing", () => {
|
||||
});
|
||||
const view = renderCard({ animation, onUpdateKeyframeEase });
|
||||
|
||||
const segment = Array.from(view.host.querySelectorAll("button")).find((button) =>
|
||||
button.textContent?.includes("0% → 50%"),
|
||||
);
|
||||
expect(segment).toBeDefined();
|
||||
act(() => segment?.click());
|
||||
openSegment(view.host, "0% → 50%");
|
||||
const ease = selectPreset(view.host, "quad-out");
|
||||
|
||||
expect(onUpdateKeyframeEase).toHaveBeenCalledExactlyOnceWith(animation.id, 50, ease);
|
||||
|
||||
@@ -18,12 +18,16 @@ import {
|
||||
parseNumericOrString,
|
||||
BOOLEAN_PROPS,
|
||||
} from "./AnimationCardParts";
|
||||
import type { AnimationKeyframeTarget } from "../../hooks/gsapTweenSynth";
|
||||
|
||||
interface AnimationCardProps extends GsapAnimationEditCallbacks {
|
||||
animation: GsapAnimation;
|
||||
defaultExpanded: boolean;
|
||||
flat?: boolean;
|
||||
focusedSegment?: { tweenPercentage: number } | null;
|
||||
focusedSegment?: {
|
||||
tweenPercentage: number;
|
||||
collidingAnimationTargets?: AnimationKeyframeTarget[];
|
||||
} | null;
|
||||
onFocusSegmentConsumed?: () => void;
|
||||
}
|
||||
|
||||
@@ -47,6 +51,7 @@ export const AnimationCard = memo(function AnimationCard({
|
||||
onSetArcPath,
|
||||
onUpdateArcSegment,
|
||||
onUpdateKeyframeEase,
|
||||
onUpdateSegmentEase,
|
||||
onSetAllKeyframeEases,
|
||||
onUnroll,
|
||||
}: AnimationCardProps) {
|
||||
@@ -54,6 +59,9 @@ export const AnimationCard = memo(function AnimationCard({
|
||||
const [addingProp, setAddingProp] = useState(false);
|
||||
const [addingFromProp, setAddingFromProp] = useState(false);
|
||||
const [expandedKfPct, setExpandedKfPct] = useState<number | null>(null);
|
||||
const [focusedCollidingAnimationTargets, setFocusedCollidingAnimationTargets] = useState<
|
||||
AnimationKeyframeTarget[] | undefined
|
||||
>();
|
||||
const cardRef = useRef<HTMLDivElement>(null);
|
||||
const pendingAutoScrollRef = useRef(false);
|
||||
|
||||
@@ -62,6 +70,7 @@ export const AnimationCard = memo(function AnimationCard({
|
||||
setExpanded(true);
|
||||
pendingAutoScrollRef.current = true;
|
||||
setExpandedKfPct(focusedSegment.tweenPercentage);
|
||||
setFocusedCollidingAnimationTargets(focusedSegment.collidingAnimationTargets);
|
||||
onFocusSegmentConsumed?.();
|
||||
}, [focusedSegment, onFocusSegmentConsumed]);
|
||||
|
||||
@@ -288,9 +297,21 @@ export const AnimationCard = memo(function AnimationCard({
|
||||
keyframes={animation.keyframes.keyframes}
|
||||
globalEase={animation.keyframes.easeEach ?? animation.ease ?? "none"}
|
||||
expandedPct={expandedKfPct}
|
||||
onToggle={setExpandedKfPct}
|
||||
collidingAnimationTargets={focusedCollidingAnimationTargets}
|
||||
onToggle={(pct) => {
|
||||
setExpandedKfPct(pct);
|
||||
setFocusedCollidingAnimationTargets(undefined);
|
||||
}}
|
||||
onEaseCommit={(pct, ease) => {
|
||||
onUpdateKeyframeEase(animation.id, pct, ease);
|
||||
if (
|
||||
focusedCollidingAnimationTargets &&
|
||||
focusedCollidingAnimationTargets.length > 1 &&
|
||||
onUpdateSegmentEase
|
||||
) {
|
||||
onUpdateSegmentEase(focusedCollidingAnimationTargets, ease);
|
||||
} else {
|
||||
onUpdateKeyframeEase(animation.id, pct, ease);
|
||||
}
|
||||
trackStudioSegmentEaseEdit({ action: "commit", ease });
|
||||
}}
|
||||
onApplyAll={
|
||||
|
||||
@@ -3,7 +3,11 @@
|
||||
import React, { act, useState } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { parseSpringBounce } from "@hyperframes/core/spring-ease";
|
||||
import { parseWiggleEase } from "@hyperframes/core/wiggle-ease";
|
||||
import { EaseCurveSection, MiniCurveSvg } from "./EaseCurveSection";
|
||||
import { resolveEaseCurveTuple } from "./gsapAnimationConstants";
|
||||
import type { AnimationKeyframeTarget } from "../../hooks/gsapTweenSynth";
|
||||
|
||||
(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
@@ -11,12 +15,22 @@ afterEach(() => {
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
function renderSection(ease = "none", onCustomEaseCommit = vi.fn()) {
|
||||
function renderSection(
|
||||
ease = "none",
|
||||
onCustomEaseCommit = vi.fn(),
|
||||
collidingAnimationTargets?: AnimationKeyframeTarget[],
|
||||
) {
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const root = createRoot(host);
|
||||
act(() => {
|
||||
root.render(<EaseCurveSection ease={ease} onCustomEaseCommit={onCustomEaseCommit} />);
|
||||
root.render(
|
||||
<EaseCurveSection
|
||||
ease={ease}
|
||||
onCustomEaseCommit={onCustomEaseCommit}
|
||||
collidingAnimationTargets={collidingAnimationTargets}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
return { host, root, onCustomEaseCommit };
|
||||
}
|
||||
@@ -65,6 +79,19 @@ function renderStatefulSection(initialEase = "none", onCustomEaseCommit = vi.fn(
|
||||
return { host, root, onCustomEaseCommit };
|
||||
}
|
||||
|
||||
function renderControlledSection(initialEase = "none", onCustomEaseCommit = vi.fn()) {
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const root = createRoot(host);
|
||||
const renderEase = (ease: string) => {
|
||||
act(() =>
|
||||
root.render(<EaseCurveSection ease={ease} onCustomEaseCommit={onCustomEaseCommit} />),
|
||||
);
|
||||
};
|
||||
renderEase(initialEase);
|
||||
return { host, root, onCustomEaseCommit, renderEase };
|
||||
}
|
||||
|
||||
function clickMode(host: HTMLElement, mode: "curve" | "spring" | "wiggle"): void {
|
||||
const toggle = host.querySelector<HTMLButtonElement>(`[data-ease-mode="${mode}"]`);
|
||||
expect(toggle).not.toBeNull();
|
||||
@@ -82,6 +109,29 @@ function editorLabel(host: HTMLElement): string | null {
|
||||
}
|
||||
|
||||
describe("EaseCurveSection preset grid", () => {
|
||||
it("shows the number of animations for a multi-id segment", () => {
|
||||
const { host, root } = renderSection("power2.out", vi.fn(), [
|
||||
{ animationId: "move-x", tweenPercentage: 20 },
|
||||
{ animationId: "move-y", tweenPercentage: 50 },
|
||||
{ animationId: "fade", tweenPercentage: 80 },
|
||||
]);
|
||||
|
||||
expect(host.textContent).toContain("Applies to 3 animations");
|
||||
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
it.each([undefined, [{ animationId: "move-x", tweenPercentage: 20 }]])(
|
||||
"does not show a property count for a non-colliding segment",
|
||||
(collidingAnimationTargets) => {
|
||||
const { host, root } = renderSection("power2.out", vi.fn(), collidingAnimationTargets);
|
||||
|
||||
expect(host.textContent).not.toContain("Applies to");
|
||||
|
||||
act(() => root.unmount());
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
["curve", "none", "linear", ["flow-7", "spring-bouncy"]],
|
||||
["spring", "spring(0.42)", "spring-bouncy", ["linear", "flow-7"]],
|
||||
@@ -257,12 +307,107 @@ describe("EaseCurveSection preset grid", () => {
|
||||
|
||||
clickMode(host, "spring");
|
||||
expect(onCustomEaseCommit).toHaveBeenLastCalledWith("spring(0.42)");
|
||||
expect(parseSpringBounce(onCustomEaseCommit.mock.lastCall![0])).toBe(0.42);
|
||||
|
||||
clickMode(host, "curve");
|
||||
expect(onCustomEaseCommit).toHaveBeenLastCalledWith("custom(M0,0 C0.16,1 0.3,1 1,1)");
|
||||
expect(resolveEaseCurveTuple(onCustomEaseCommit.mock.lastCall![0])).toEqual([0.16, 1, 0.3, 1]);
|
||||
|
||||
clickMode(host, "wiggle");
|
||||
expect(onCustomEaseCommit).toHaveBeenLastCalledWith("wiggle(3,easeInOut,0.12)");
|
||||
expect(parseWiggleEase(onCustomEaseCommit.mock.lastCall![0])).toEqual({
|
||||
wiggles: 3,
|
||||
type: "easeInOut",
|
||||
amplitude: 0.12,
|
||||
});
|
||||
expect(onCustomEaseCommit).toHaveBeenCalledTimes(3);
|
||||
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
it("keeps an optimistic mode visible through its canonical prop round-trip", () => {
|
||||
const { host, root, onCustomEaseCommit, renderEase } = renderControlledSection();
|
||||
|
||||
clickMode(host, "spring");
|
||||
expect(host.querySelector('[data-ease-mode="spring"]')?.getAttribute("aria-checked")).toBe(
|
||||
"true",
|
||||
);
|
||||
expect(host.querySelector('[aria-label="Spring bounce"]')).not.toBeNull();
|
||||
|
||||
renderEase("spring(0.42)");
|
||||
expect(host.querySelector('[data-ease-mode="spring"]')?.getAttribute("aria-checked")).toBe(
|
||||
"true",
|
||||
);
|
||||
expect(host.querySelector('[aria-label="Spring bounce"]')).not.toBeNull();
|
||||
expect(onCustomEaseCommit).toHaveBeenCalledExactlyOnceWith("spring(0.42)");
|
||||
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
// Two switches before the first commit round-trips: the commits serialize, so
|
||||
// the older value arrives while the newer one is still in flight. Repainting
|
||||
// it would flash wiggle, spring, wiggle in the panel.
|
||||
it("ignores an older in-flight commit arriving after a newer switch", () => {
|
||||
const { host, root, renderEase } = renderControlledSection();
|
||||
|
||||
clickMode(host, "spring");
|
||||
clickMode(host, "wiggle");
|
||||
renderEase("spring(0.42)");
|
||||
|
||||
expect(host.querySelector('[data-ease-mode="wiggle"]')?.getAttribute("aria-checked")).toBe(
|
||||
"true",
|
||||
);
|
||||
|
||||
renderEase("wiggle(3,easeInOut,0.12)");
|
||||
expect(host.querySelector('[data-ease-mode="wiggle"]')?.getAttribute("aria-checked")).toBe(
|
||||
"true",
|
||||
);
|
||||
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
// The commit is fire-and-forget: a rejected write or one that lands as a
|
||||
// no-op never changes `ease`, so nothing else can retire the optimistic
|
||||
// value and the panel would keep claiming a curve that was never saved.
|
||||
it("falls back to the committed ease when the commit never round-trips", () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const { host, root } = renderControlledSection("power2.out");
|
||||
|
||||
clickMode(host, "spring");
|
||||
expect(host.querySelector('[data-ease-mode="spring"]')?.getAttribute("aria-checked")).toBe(
|
||||
"true",
|
||||
);
|
||||
|
||||
act(() => vi.advanceTimersByTime(2000));
|
||||
|
||||
expect(host.querySelector('[data-ease-mode="spring"]')?.getAttribute("aria-checked")).toBe(
|
||||
"false",
|
||||
);
|
||||
expect(host.querySelector('[data-ease-mode="curve"]')?.getAttribute("aria-checked")).toBe(
|
||||
"true",
|
||||
);
|
||||
|
||||
act(() => root.unmount());
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("replaces an optimistic mode when the canonical prop changes externally", () => {
|
||||
const { host, root, renderEase } = renderControlledSection();
|
||||
|
||||
clickMode(host, "spring");
|
||||
renderEase("wiggle(2,uniform,0.3)");
|
||||
|
||||
expect(host.querySelector('[data-ease-mode="spring"]')?.getAttribute("aria-checked")).toBe(
|
||||
"false",
|
||||
);
|
||||
expect(host.querySelector('[data-ease-mode="wiggle"]')?.getAttribute("aria-checked")).toBe(
|
||||
"true",
|
||||
);
|
||||
expect(host.querySelector('[aria-label="Wiggle count"]')).not.toBeNull();
|
||||
expect(host.querySelector('[aria-label="Spring bounce"]')).toBeNull();
|
||||
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
@@ -10,6 +10,7 @@ import { holdCurvePath, MiniCurveSvg, sampledPath } from "./easeCurveSvg";
|
||||
import { EaseBezierField, SpringBounceField, WiggleField } from "./EaseParamFields";
|
||||
import { EASE_CURVES, EASE_LABELS, resolveEaseCurveTuple } from "./gsapAnimationConstants";
|
||||
import { roundToCenti } from "../../utils/rounding";
|
||||
import type { AnimationKeyframeTarget } from "../../hooks/gsapTweenSynth";
|
||||
|
||||
export { MiniCurveSvg } from "./easeCurveSvg";
|
||||
|
||||
@@ -320,19 +321,36 @@ function EaseParameterField({
|
||||
return <EaseBezierField tuple={tuple} onCommit={onCommit} />;
|
||||
}
|
||||
|
||||
/**
|
||||
* How long an optimistically painted ease may outlive its commit. Long enough
|
||||
* for a normal write-reparse-rerender round trip, short enough that a dropped
|
||||
* write self-corrects while the author is still looking at the panel.
|
||||
*/
|
||||
const PENDING_EASE_TIMEOUT_MS = 2000;
|
||||
|
||||
export function EaseCurveSection({
|
||||
ease,
|
||||
onCustomEaseCommit,
|
||||
collidingAnimationTargets,
|
||||
}: {
|
||||
ease: string;
|
||||
onCustomEaseCommit: (ease: string) => void;
|
||||
collidingAnimationTargets?: AnimationKeyframeTarget[];
|
||||
}) {
|
||||
const springBounce = parseSpringBounce(ease);
|
||||
// The ease this section painted optimistically, still waiting for its commit
|
||||
// to round-trip back through the `ease` prop.
|
||||
const [pendingEase, setPendingEase] = useState<string | null>(null);
|
||||
// Every value committed and not yet seen coming back, oldest first. It takes
|
||||
// the whole queue, not just the latest, to tell an older commit echoing back
|
||||
// apart from an edit made somewhere else.
|
||||
const inFlightEasesRef = useRef<string[]>([]);
|
||||
const displayedEase = pendingEase ?? ease;
|
||||
const springBounce = parseSpringBounce(displayedEase);
|
||||
const isSpring = springBounce !== null;
|
||||
const wiggleConfig = parseWiggleEase(ease);
|
||||
const wiggleConfig = parseWiggleEase(displayedEase);
|
||||
const isWiggle = wiggleConfig !== null;
|
||||
const mode: EaseMode = isSpring ? "spring" : isWiggle ? "wiggle" : "curve";
|
||||
const curve = resolveEditableCurve(ease, springBounce);
|
||||
const curve = resolveEditableCurve(displayedEase, springBounce);
|
||||
|
||||
const [draft, setDraft] = useState<Pts | null>(null);
|
||||
const [hover, setHover] = useState<"p1" | "p2" | null>(null);
|
||||
@@ -346,8 +364,43 @@ export function EaseCurveSection({
|
||||
// `ease` changes, `curve` already equals the draft, so the handoff is seamless.
|
||||
useEffect(() => {
|
||||
setDraft(null);
|
||||
const inFlight = inFlightEasesRef.current;
|
||||
const landed = inFlight.indexOf(ease);
|
||||
if (landed < 0) {
|
||||
// A value this section never sent: someone else edited the ease, so the
|
||||
// real value wins over anything optimistic still on screen.
|
||||
inFlight.length = 0;
|
||||
setPendingEase(null);
|
||||
return;
|
||||
}
|
||||
// One of this section's own commits came back. Everything sent before it
|
||||
// is settled with it, but a NEWER commit may still be in flight, and
|
||||
// repainting this older value while waiting for that one is the
|
||||
// wiggle-then-spring-then-wiggle flicker of a fast double switch.
|
||||
inFlight.splice(0, landed + 1);
|
||||
if (inFlight.length === 0) setPendingEase(null);
|
||||
}, [ease]);
|
||||
|
||||
// A commit is fire-and-forget, so a write that is rejected or lands as a
|
||||
// no-op never changes `ease`, and the optimistic value would sit on screen
|
||||
// claiming a curve the composition does not have. Nothing downstream reports
|
||||
// that failure, so the display is time-bounded instead: fall back to the
|
||||
// committed truth when the round trip does not arrive.
|
||||
useEffect(() => {
|
||||
if (pendingEase === null) return;
|
||||
const timer = setTimeout(() => {
|
||||
inFlightEasesRef.current.length = 0;
|
||||
setPendingEase(null);
|
||||
}, PENDING_EASE_TIMEOUT_MS);
|
||||
return () => clearTimeout(timer);
|
||||
}, [pendingEase]);
|
||||
|
||||
const commitEase = (nextEase: string) => {
|
||||
inFlightEasesRef.current.push(nextEase);
|
||||
setPendingEase(nextEase);
|
||||
onCustomEaseCommit(nextEase);
|
||||
};
|
||||
|
||||
const activeTuple = draft ?? curve;
|
||||
const displayTuple = activeTuple ?? DEFAULT_CURVE;
|
||||
const [x1, y1, x2, y2] = displayTuple;
|
||||
@@ -358,8 +411,12 @@ export function EaseCurveSection({
|
||||
const a1 = { x: xToSvg(1), y: yToSvg(1) };
|
||||
const p1 = { x: xToSvg(x1), y: yToSvg(clampView(y1)) };
|
||||
const p2 = { x: xToSvg(x2), y: yToSvg(clampView(y2)) };
|
||||
const curvePath = curvePathFor(ease, springBounce, wiggleConfig, displayTuple);
|
||||
const showGraph = activeTuple !== null || isWiggle || ease === "hold";
|
||||
// Read the OPTIMISTIC ease everywhere the graph is derived, so a mode switch
|
||||
// paints immediately instead of waiting for the committed prop to come back.
|
||||
const curvePath = curvePathFor(displayedEase, springBounce, wiggleConfig, displayTuple);
|
||||
const showGraph = activeTuple !== null || isWiggle || displayedEase === "hold";
|
||||
// `curve !== null` is what keeps Hold handle-free: it draws a graph (a flat
|
||||
// step) but has no editable control points to drag.
|
||||
const showHandles = curve !== null && !isSpring && !isWiggle;
|
||||
|
||||
const handlePointerDown = (handle: "p1" | "p2", e: React.PointerEvent) => {
|
||||
@@ -394,10 +451,9 @@ export function EaseCurveSection({
|
||||
if (!draggingRef.current || !draft) return;
|
||||
draggingRef.current = null;
|
||||
const path = `M0,0 C${draft[0]},${draft[1]} ${draft[2]},${draft[3]} 1,1`;
|
||||
// Clear after the synchronous parent commit settles. This also clears a
|
||||
// same-string commit, where the `ease` dependency effect would not run.
|
||||
onCustomEaseCommit(`custom(${path})`);
|
||||
queueMicrotask(() => setDraft(null));
|
||||
// Commit only — the draft stays on screen and is cleared by the effect above
|
||||
// once the committed `ease` prop comes back, so the curve never flickers.
|
||||
commitEase(`custom(${path})`);
|
||||
};
|
||||
|
||||
const handleKeyDown = (handle: "p1" | "p2", event: React.KeyboardEvent<SVGCircleElement>) => {
|
||||
@@ -406,20 +462,26 @@ export function EaseCurveSection({
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
setDraft(next);
|
||||
onCustomEaseCommit(`custom(M0,0 C${next[0]},${next[1]} ${next[2]},${next[3]} 1,1)`);
|
||||
queueMicrotask(() => setDraft(null));
|
||||
// Same no-flicker contract as the pointer path: commit and let the effect
|
||||
// clear the draft, rather than dropping it on the next microtask.
|
||||
commitEase(`custom(M0,0 C${next[0]},${next[1]} ${next[2]},${next[3]} 1,1)`);
|
||||
};
|
||||
|
||||
const top = yToSvg(1);
|
||||
const bottom = yToSvg(0);
|
||||
const left = xToSvg(0);
|
||||
const right = xToSvg(1);
|
||||
const label = resolveEditorLabel(ease, springBounce, isWiggle);
|
||||
const label = resolveEditorLabel(displayedEase, springBounce, isWiggle);
|
||||
|
||||
return (
|
||||
<div className="rounded-lg bg-neutral-900/50 p-2">
|
||||
<EaseTypeDropdown kind={mode} ease={ease} label={label} onSelect={onCustomEaseCommit} />
|
||||
<EaseModeToggle mode={mode} onCommit={onCustomEaseCommit} />
|
||||
<EaseTypeDropdown kind={mode} ease={displayedEase} label={label} onSelect={commitEase} />
|
||||
{collidingAnimationTargets && collidingAnimationTargets.length > 1 && (
|
||||
<p className="mb-1 text-[9px] text-neutral-500">
|
||||
Applies to {collidingAnimationTargets.length} animations
|
||||
</p>
|
||||
)}
|
||||
<EaseModeToggle mode={mode} onCommit={commitEase} />
|
||||
<span className="sr-only" aria-live="polite">
|
||||
{MODE_LABELS[mode]} ease editor selected
|
||||
</span>
|
||||
@@ -560,7 +622,7 @@ export function EaseCurveSection({
|
||||
springBounce={springBounce}
|
||||
wiggleConfig={wiggleConfig}
|
||||
tuple={displayTuple}
|
||||
onCommit={onCustomEaseCommit}
|
||||
onCommit={commitEase}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import React, { act } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type { GsapAnimation } from "@hyperframes/core/gsap-parser";
|
||||
import { DesignPanelInputProvider } from "../../contexts/DesignPanelInputContext";
|
||||
import { usePlayerStore } from "../../player";
|
||||
import { GsapAnimationSection } from "./GsapAnimationSection";
|
||||
|
||||
(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
vi.mock("./AnimationCard", () => ({
|
||||
AnimationCard: ({
|
||||
animation,
|
||||
focusedSegment,
|
||||
onFocusSegmentConsumed,
|
||||
}: {
|
||||
animation: GsapAnimation;
|
||||
focusedSegment: { tweenPercentage: number } | null;
|
||||
onFocusSegmentConsumed: () => void;
|
||||
}) => (
|
||||
<button
|
||||
type="button"
|
||||
data-testid={`animation-${animation.id}`}
|
||||
data-focused={focusedSegment ? String(focusedSegment.tweenPercentage) : ""}
|
||||
// Mirrors the real card: the consume callback only fires from the effect
|
||||
// that runs when this card actually received a focusedSegment.
|
||||
onClick={() => focusedSegment && onFocusSegmentConsumed()}
|
||||
/>
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock("./GsapAddAnimationControl", () => ({ GsapAddAnimationControl: () => null }));
|
||||
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = "";
|
||||
usePlayerStore.getState().reset();
|
||||
});
|
||||
|
||||
const sharedAnimation: GsapAnimation = {
|
||||
id: "shared-animation",
|
||||
targetSelector: ".shared",
|
||||
method: "to",
|
||||
position: 0,
|
||||
properties: { x: 100 },
|
||||
};
|
||||
|
||||
const requiredCallbacks = {
|
||||
onAddAnimation: vi.fn(),
|
||||
onUpdateProperty: vi.fn(),
|
||||
onUpdateMeta: vi.fn(),
|
||||
onDeleteAnimation: vi.fn(),
|
||||
onAddProperty: vi.fn(),
|
||||
onRemoveProperty: vi.fn(),
|
||||
};
|
||||
|
||||
function renderSection(elementId: string) {
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const root = createRoot(host);
|
||||
const render = (nextElementId: string) => {
|
||||
act(() => {
|
||||
root.render(
|
||||
<DesignPanelInputProvider section="test">
|
||||
<GsapAnimationSection
|
||||
{...requiredCallbacks}
|
||||
elementId={nextElementId}
|
||||
animations={[sharedAnimation]}
|
||||
/>
|
||||
</DesignPanelInputProvider>,
|
||||
);
|
||||
});
|
||||
};
|
||||
render(elementId);
|
||||
return { host, root, render };
|
||||
}
|
||||
|
||||
describe("GsapAnimationSection", () => {
|
||||
it("consumes a shared animation id only for the focused element", () => {
|
||||
usePlayerStore.getState().setFocusedEaseSegment({
|
||||
elementId: "index.html#second",
|
||||
animationId: sharedAnimation.id,
|
||||
tweenPercentage: 50,
|
||||
});
|
||||
const view = renderSection("index.html#first");
|
||||
const card = view.host.querySelector<HTMLButtonElement>(
|
||||
"[data-testid='animation-shared-animation']",
|
||||
);
|
||||
if (!card) throw new Error("expected animation card");
|
||||
|
||||
expect(card.dataset.focused).toBe("");
|
||||
act(() => card.click());
|
||||
expect(usePlayerStore.getState().focusedEaseSegment?.elementId).toBe("index.html#second");
|
||||
|
||||
view.render("index.html#second");
|
||||
expect(card.dataset.focused).toBe("50");
|
||||
act(() => card.click());
|
||||
expect(usePlayerStore.getState().focusedEaseSegment).toBeNull();
|
||||
act(() => view.root.unmount());
|
||||
});
|
||||
});
|
||||
@@ -13,6 +13,7 @@ import { usePlayerStore } from "../../player";
|
||||
import { GsapAddAnimationControl } from "./GsapAddAnimationControl";
|
||||
|
||||
interface GsapAnimationSectionProps extends GsapAnimationEditCallbacks {
|
||||
elementId: string;
|
||||
animations: GsapAnimation[];
|
||||
multipleTimelines?: boolean;
|
||||
unsupportedTimelinePattern?: boolean;
|
||||
@@ -21,6 +22,7 @@ interface GsapAnimationSectionProps extends GsapAnimationEditCallbacks {
|
||||
|
||||
export const GsapAnimationSection = memo(function GsapAnimationSection({
|
||||
animations,
|
||||
elementId,
|
||||
multipleTimelines,
|
||||
unsupportedTimelinePattern,
|
||||
onAddAnimation,
|
||||
@@ -55,7 +57,10 @@ export const GsapAnimationSection = memo(function GsapAnimationSection({
|
||||
animation={anim}
|
||||
defaultExpanded={index === 0}
|
||||
focusedSegment={
|
||||
focusedEaseSegment?.animationId === anim.id ? focusedEaseSegment : null
|
||||
focusedEaseSegment?.elementId === elementId &&
|
||||
focusedEaseSegment.animationId === anim.id
|
||||
? focusedEaseSegment
|
||||
: null
|
||||
}
|
||||
onFocusSegmentConsumed={clearFocusedEaseSegment}
|
||||
/>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { GsapPercentageKeyframe } from "@hyperframes/core/gsap-parser";
|
||||
import { EASE_LABELS } from "./gsapAnimationConstants";
|
||||
import { EaseCurveSection } from "./EaseCurveSection";
|
||||
import type { AnimationKeyframeTarget } from "../../hooks/gsapTweenSynth";
|
||||
|
||||
// The full GSAP easing vocabulary offered by the "Set all…" bulk control —
|
||||
// every standard family in in/out/inOut, so authors aren't limited to a curated
|
||||
@@ -44,6 +45,7 @@ export function KeyframeEaseList({
|
||||
keyframes,
|
||||
globalEase,
|
||||
expandedPct,
|
||||
collidingAnimationTargets,
|
||||
onToggle,
|
||||
onEaseCommit,
|
||||
onApplyAll,
|
||||
@@ -51,6 +53,7 @@ export function KeyframeEaseList({
|
||||
keyframes: GsapPercentageKeyframe[];
|
||||
globalEase: string;
|
||||
expandedPct: number | null;
|
||||
collidingAnimationTargets?: AnimationKeyframeTarget[];
|
||||
onToggle: (pct: number | null) => void;
|
||||
onEaseCommit: (pct: number, ease: string) => void;
|
||||
/** Apply one ease to every segment at once (clears per-segment overrides). */
|
||||
@@ -119,6 +122,7 @@ export function KeyframeEaseList({
|
||||
<div className="px-2 pb-2">
|
||||
<EaseCurveSection
|
||||
ease={segEase}
|
||||
collidingAnimationTargets={collidingAnimationTargets}
|
||||
onCustomEaseCommit={(ease) => onEaseCommit(kf.percentage, ease)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { scopedElementKey } from "../../hooks/gsapKeyframeCacheHelpers";
|
||||
import { memo, useEffect, useRef, useState, type RefObject } from "react";
|
||||
import type { DomEditSelection } from "./domEditing";
|
||||
import { useDomEditContext } from "../../contexts/DomEditContext";
|
||||
@@ -11,6 +12,7 @@ import {
|
||||
KeyframeDiamondContextMenu,
|
||||
type KeyframeDiamondContextMenuState,
|
||||
} from "../../player/components/KeyframeDiamondContextMenu";
|
||||
import type { TimelineKeyframeTarget } from "../../player/components/timelineKeyframeIdentity";
|
||||
import {
|
||||
commitAddKeyframe,
|
||||
commitAddWaypoint,
|
||||
@@ -95,15 +97,19 @@ export const MotionPathOverlay = memo(function MotionPathOverlay({
|
||||
const [draft, setDraft] = useState<Draft | null>(null);
|
||||
const [ghost, setGhost] = useState<{ x: number; y: number; segIndex: number } | null>(null);
|
||||
const [hoverNode, setHoverNode] = useState<number | null>(null);
|
||||
// Right-click context menu on a keyframe node — same delete actions as the
|
||||
// timeline keyframe diamond.
|
||||
const [kfMenu, setKfMenu] = useState<KeyframeDiamondContextMenuState | null>(null);
|
||||
// Right-click context menu on a path node — same delete actions as the
|
||||
// timeline keyframe diamond. The node it was opened on rides along, because
|
||||
// which entries apply depends on whether it is a keyframe or a waypoint.
|
||||
const [kfMenu, setKfMenu] = useState<{
|
||||
state: KeyframeDiamondContextMenuState;
|
||||
ref: MotionNodeRef;
|
||||
} | null>(null);
|
||||
// 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}`;
|
||||
const sourceScopedId = scopedElementKey(selection);
|
||||
return state.elements.find(
|
||||
(element) => (element.key ?? element.id) === sourceScopedId || element.id === selection.id,
|
||||
);
|
||||
@@ -435,21 +441,47 @@ export const MotionPathOverlay = memo(function MotionPathOverlay({
|
||||
};
|
||||
|
||||
const elementId = selection?.id ?? null;
|
||||
// Right-click a keyframe node → the timeline's keyframe context menu (delete
|
||||
// this keyframe / delete all), so motion-path keyframes are removable in place.
|
||||
// Right-click any path node → the timeline's keyframe context menu (delete this
|
||||
// one / delete all), so path nodes are removable in place. Waypoints open it
|
||||
// too: returning early for them let the browser's own context menu open over
|
||||
// the editor overlay, which is never what a right-click on a node should do.
|
||||
const onNodeContextMenu = (e: React.MouseEvent, ref: MotionNodeRef) => {
|
||||
if (ref.type !== "keyframe" || !animId || !elementId || !timelineElement) return;
|
||||
if (!animId || !elementId || !timelineElement) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setKfMenu({
|
||||
x: e.clientX,
|
||||
y: e.clientY,
|
||||
element: timelineElement,
|
||||
elementId,
|
||||
percentage: ref.pct,
|
||||
tweenPercentage: ref.pct,
|
||||
ref,
|
||||
state: {
|
||||
x: e.clientX,
|
||||
y: e.clientY,
|
||||
element: timelineElement,
|
||||
elementId,
|
||||
// A waypoint carries no percentage of its own: one tween-level ease owns
|
||||
// every segment, and its index is the identity the delete acts on. The
|
||||
// menu never reads this for a waypoint, because the only entry that
|
||||
// would (Move to Playhead) is hidden below.
|
||||
percentage: ref.type === "keyframe" ? ref.pct : 0,
|
||||
tweenPercentage: ref.type === "keyframe" ? ref.pct : 0,
|
||||
},
|
||||
});
|
||||
};
|
||||
const menuRef = kfMenu?.ref;
|
||||
// Deleting one node: by tween-% for a keyframe, by path index for a waypoint.
|
||||
// A waypoint delete is offered on the same condition as the hover x badge,
|
||||
// because removeMotionPathPointInScript refuses to drop an arc below two
|
||||
// anchors and the entry would silently do nothing.
|
||||
const onMenuDelete =
|
||||
menuRef === undefined || !animId
|
||||
? undefined
|
||||
: menuRef.type === "keyframe"
|
||||
? (_elId: string, keyframe: TimelineKeyframeTarget) => {
|
||||
handleGsapRemoveKeyframe(animId, keyframe.percentage);
|
||||
}
|
||||
: removable
|
||||
? () => {
|
||||
void commitRemoveWaypoint(animId, menuRef.index, commitMutation);
|
||||
}
|
||||
: undefined;
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -531,14 +563,17 @@ export const MotionPathOverlay = memo(function MotionPathOverlay({
|
||||
</svg>
|
||||
{kfMenu && (
|
||||
<KeyframeDiamondContextMenu
|
||||
state={kfMenu}
|
||||
state={kfMenu.state}
|
||||
onClose={() => setKfMenu(null)}
|
||||
onDelete={(_elId, keyframe) =>
|
||||
animId && handleGsapRemoveKeyframe(animId, keyframe.percentage)
|
||||
}
|
||||
onDelete={onMenuDelete}
|
||||
onDeleteAll={() => animId && handleGsapRemoveAllKeyframes(animId)}
|
||||
onMoveToPlayhead={(_element, keyframe) =>
|
||||
animId && handleGsapMoveKeyframeToPlayhead(animId, keyframe.percentage)
|
||||
// Retiming needs a percentage of this node's own, which a waypoint
|
||||
// does not have.
|
||||
onMoveToPlayhead={
|
||||
kfMenu.ref.type === "keyframe"
|
||||
? (_element, keyframe) =>
|
||||
animId && handleGsapMoveKeyframeToPlayhead(animId, keyframe.percentage)
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { scopedElementKey } from "../../hooks/gsapKeyframeCacheHelpers";
|
||||
import { memo, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Move } from "../../icons/SystemIcons";
|
||||
import { InspectorHeaderActions } from "./InspectorHeaderActions";
|
||||
@@ -101,6 +102,7 @@ export const PropertyPanel = memo(function PropertyPanel(props: PropertyPanelPro
|
||||
onUpdateArcSegment,
|
||||
onUnroll,
|
||||
onUpdateKeyframeEase,
|
||||
onUpdateSegmentEase,
|
||||
onSetAllKeyframeEases,
|
||||
onAddKeyframe,
|
||||
onRemoveKeyframe,
|
||||
@@ -556,6 +558,7 @@ export const PropertyPanel = memo(function PropertyPanel(props: PropertyPanelPro
|
||||
onAddGsapProperty &&
|
||||
onAddGsapAnimation && (
|
||||
<GsapAnimationSection
|
||||
elementId={scopedElementKey(element)}
|
||||
animations={gsapAnimations}
|
||||
multipleTimelines={gsapMultipleTimelines}
|
||||
unsupportedTimelinePattern={gsapUnsupportedTimelinePattern}
|
||||
@@ -573,6 +576,7 @@ export const PropertyPanel = memo(function PropertyPanel(props: PropertyPanelPro
|
||||
onUnroll={onUnroll}
|
||||
onUpdateKeyframeEase={onUpdateKeyframeEase}
|
||||
onSetAllKeyframeEases={onSetAllKeyframeEases}
|
||||
onUpdateSegmentEase={onUpdateSegmentEase}
|
||||
/>
|
||||
)}
|
||||
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import { scopedElementKey } from "../../hooks/gsapKeyframeCacheHelpers";
|
||||
import { type ReactNode, useEffect, useRef, useState } from "react";
|
||||
import { resolveEditingSections } from "@hyperframes/core/editing";
|
||||
import { DesignPanelInputProvider } from "../../contexts/DesignPanelInputContext";
|
||||
import { slugifyDesignInput } from "../../utils/designInputTracking";
|
||||
import type { DomEditSelection } from "./domEditing";
|
||||
import { isTextEditableSelection } from "./domEditing";
|
||||
import type { PropertyPanelProps } from "./propertyPanelHelpers";
|
||||
import type { PropertyPanelFlatProps } from "./propertyPanelFlatProps";
|
||||
import { formatPxMetricValue } from "./propertyPanelHelpers";
|
||||
import { PropertyPanelFlatHeader } from "./PropertyPanelFlatHeader";
|
||||
import { PropertyPanelFlatFooter } from "./PropertyPanelFlatFooter";
|
||||
@@ -34,8 +33,6 @@ import {
|
||||
FlatOverlaysSection,
|
||||
} from "./propertyPanelFlatOverlaysSection";
|
||||
|
||||
type EditingSections = ReturnType<typeof resolveEditingSections>;
|
||||
|
||||
type FlatGroupDescriptor = {
|
||||
id: string;
|
||||
title: string;
|
||||
@@ -135,92 +132,9 @@ export function PropertyPanelFlat({
|
||||
onUpdateArcSegment,
|
||||
onUnroll,
|
||||
onUpdateKeyframeEase,
|
||||
onUpdateSegmentEase,
|
||||
onSetAllKeyframeEases,
|
||||
}: Pick<
|
||||
PropertyPanelProps,
|
||||
| "projectId"
|
||||
| "projectDir"
|
||||
| "assets"
|
||||
| "previewIframeRef"
|
||||
| "onClearSelection"
|
||||
| "onUngroup"
|
||||
| "onSetStyle"
|
||||
| "onPreviewStyle"
|
||||
| "onSetAttribute"
|
||||
| "onSetAttributes"
|
||||
| "onSetAttributeLive"
|
||||
| "onApplyColorGradingScope"
|
||||
| "onSetHtmlAttribute"
|
||||
| "onRemoveBackground"
|
||||
| "onSetText"
|
||||
| "onSetTextFieldStyle"
|
||||
| "onPreviewTextFieldStyle"
|
||||
| "onAddTextField"
|
||||
| "onRemoveTextField"
|
||||
| "onAskAgent"
|
||||
| "onToggleElementHidden"
|
||||
| "onImportAssets"
|
||||
| "onAddMediaOverlay"
|
||||
| "onImportFonts"
|
||||
| "fontAssets"
|
||||
| "gsapAnimations"
|
||||
| "gsapMultipleTimelines"
|
||||
| "gsapUnsupportedTimelinePattern"
|
||||
| "onUpdateGsapProperty"
|
||||
| "onUpdateGsapMeta"
|
||||
| "onDeleteGsapAnimation"
|
||||
| "onAddGsapProperty"
|
||||
| "onRemoveGsapProperty"
|
||||
| "onUpdateGsapFromProperty"
|
||||
| "onAddGsapFromProperty"
|
||||
| "onRemoveGsapFromProperty"
|
||||
| "onAddGsapAnimation"
|
||||
| "onSetArcPath"
|
||||
| "onUpdateArcSegment"
|
||||
| "onUnroll"
|
||||
| "onUpdateKeyframeEase"
|
||||
| "onSetAllKeyframeEases"
|
||||
| "recordingState"
|
||||
| "recordingDuration"
|
||||
| "onToggleRecording"
|
||||
> &
|
||||
Pick<
|
||||
Parameters<typeof FlatLayoutSection>[0],
|
||||
| "displayX"
|
||||
| "displayY"
|
||||
| "displayW"
|
||||
| "displayH"
|
||||
| "displayR"
|
||||
| "manualOffsetEditingDisabled"
|
||||
| "manualSizeEditingDisabled"
|
||||
| "manualRotationEditingDisabled"
|
||||
| "commitManualOffset"
|
||||
| "commitManualSize"
|
||||
| "commitManualRotation"
|
||||
| "gsapAnimId"
|
||||
| "navKeyframes"
|
||||
| "animIdForProp"
|
||||
| "gsapRuntimeValues"
|
||||
| "elStart"
|
||||
| "elDuration"
|
||||
| "onCommitAnimatedProperty"
|
||||
| "onCommitAnimatedProperties"
|
||||
| "onSeekToTime"
|
||||
| "onRemoveKeyframe"
|
||||
| "onConvertToKeyframes"
|
||||
> & {
|
||||
element: DomEditSelection;
|
||||
styles: Record<string, string>;
|
||||
sections: EditingSections;
|
||||
sourceLabel: string;
|
||||
gsapBorderRadius: { tl: number; tr: number; br: number; bl: number } | null;
|
||||
showEditableSections: boolean;
|
||||
selectedElementHidden: boolean;
|
||||
selectedElementId: string | null;
|
||||
clipboardCopied: boolean;
|
||||
onCopyElementInfo: () => void;
|
||||
currentTime: number;
|
||||
}) {
|
||||
}: PropertyPanelFlatProps) {
|
||||
// PropertyPanel keys this component by selection, so the default is per element.
|
||||
const [openGroupId, setOpenGroupId] = useState<string>(() =>
|
||||
isTextEditableSelection(element)
|
||||
@@ -253,7 +167,7 @@ export function PropertyPanelFlat({
|
||||
// flips synchronously while the panel still renders its predecessor, so a
|
||||
// stale panel would consume a request meant for its successor whenever the
|
||||
// two share a class-selector animation id.
|
||||
const renderedElementId = `${element.sourceFile}#${element.id}`;
|
||||
const renderedElementId = scopedElementKey(element);
|
||||
// Adjusted during render (not an effect) so the card mounts on the same
|
||||
// commit the request lands on. Keyed on request identity: a group the user
|
||||
// closes afterwards stays closed.
|
||||
@@ -330,6 +244,7 @@ export function PropertyPanelFlat({
|
||||
onUpdateArcSegment,
|
||||
onUnroll,
|
||||
onUpdateKeyframeEase,
|
||||
onUpdateSegmentEase,
|
||||
onSetAllKeyframeEases,
|
||||
}
|
||||
: null;
|
||||
|
||||
@@ -26,7 +26,6 @@ describe("withTrackedGsapAnimationCallbacks", () => {
|
||||
const onLivePreviewEnd = vi.fn();
|
||||
callbacks.onLivePreview = onLivePreview;
|
||||
callbacks.onLivePreviewEnd = onLivePreviewEnd;
|
||||
|
||||
const tracked = withTrackedGsapAnimationCallbacks(callbacks, vi.fn());
|
||||
|
||||
expect(tracked.onUpdateFromProperty).toBeUndefined();
|
||||
@@ -37,6 +36,7 @@ describe("withTrackedGsapAnimationCallbacks", () => {
|
||||
expect(tracked.onUpdateKeyframeEase).toBeUndefined();
|
||||
expect(tracked.onSetAllKeyframeEases).toBeUndefined();
|
||||
expect(tracked.onUnroll).toBeUndefined();
|
||||
expect(tracked.onUpdateSegmentEase).toBeUndefined();
|
||||
expect(tracked.onLivePreview).toBe(onLivePreview);
|
||||
expect(tracked.onLivePreviewEnd).toBe(onLivePreviewEnd);
|
||||
});
|
||||
@@ -57,6 +57,7 @@ describe("withTrackedGsapAnimationCallbacks", () => {
|
||||
onUpdateArcSegment: mutation("arc-segment"),
|
||||
onUpdateKeyframeEase: mutation("keyframe-ease"),
|
||||
onSetAllKeyframeEases: mutation("all-eases"),
|
||||
onUpdateSegmentEase: mutation("segment-ease"),
|
||||
onUnroll: mutation("unroll"),
|
||||
};
|
||||
const tracked = withTrackedGsapAnimationCallbacks(callbacks, (control, name) => {
|
||||
@@ -79,6 +80,10 @@ describe("withTrackedGsapAnimationCallbacks", () => {
|
||||
requireCallback(tracked.onUpdateArcSegment)("a1", 1, { curviness: 0.5 });
|
||||
requireCallback(tracked.onUpdateKeyframeEase)("a1", 50, "power2.out");
|
||||
requireCallback(tracked.onSetAllKeyframeEases)("a1", "none");
|
||||
requireCallback(tracked.onUpdateSegmentEase)(
|
||||
[{ animationId: "a1", tweenPercentage: 50 }],
|
||||
"none",
|
||||
);
|
||||
requireCallback(tracked.onUnroll)("a1");
|
||||
|
||||
expect(events).toEqual([
|
||||
@@ -115,6 +120,8 @@ describe("withTrackedGsapAnimationCallbacks", () => {
|
||||
"mutate:keyframe-ease",
|
||||
"track:select:All keyframe eases",
|
||||
"mutate:all-eases",
|
||||
"track:select:Segment ease",
|
||||
"mutate:segment-ease",
|
||||
"track:button:Unroll animation",
|
||||
"mutate:unroll",
|
||||
]);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { ArcPathSegment } from "@hyperframes/parsers/gsap-parser";
|
||||
import { usePlayerStore } from "../../player";
|
||||
import type { AnimationKeyframeTarget } from "../../hooks/gsapTweenSynth";
|
||||
|
||||
/**
|
||||
* Edit callbacks shared by GsapAnimationSection and each AnimationCard it
|
||||
@@ -30,6 +31,7 @@ export interface GsapAnimationEditCallbacks {
|
||||
update: Partial<ArcPathSegment>,
|
||||
) => void;
|
||||
onUpdateKeyframeEase?: (animationId: string, percentage: number, ease: string) => void;
|
||||
onUpdateSegmentEase?: (targets: AnimationKeyframeTarget[], ease: string) => void;
|
||||
/** Apply one ease to every keyframe segment at once (clears per-segment overrides). */
|
||||
onSetAllKeyframeEases?: (animationId: string, ease: string) => void;
|
||||
/** Unroll a computed (helper/loop) tween into literal tweens so it edits directly. */
|
||||
@@ -122,6 +124,12 @@ export function withTrackedGsapAnimationCallbacks(
|
||||
: undefined,
|
||||
onLivePreview: callbacks.onLivePreview,
|
||||
onLivePreviewEnd: callbacks.onLivePreviewEnd,
|
||||
onUpdateSegmentEase: callbacks.onUpdateSegmentEase
|
||||
? (targets, ease) => {
|
||||
track("select", "Segment ease");
|
||||
callbacks.onUpdateSegmentEase?.(targets, ease);
|
||||
}
|
||||
: undefined,
|
||||
onSetArcPath: callbacks.onSetArcPath
|
||||
? (animationId, config) => {
|
||||
track("toggle", config.autoRotate !== undefined ? "Auto rotate" : "Arc motion");
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
// Real gsap, not a parseEase stub: this pins the seek behaviour of the `hold`
|
||||
// ease against the engine that actually runs it, and gsap is a studio
|
||||
// dependency. core's own customEase.test.ts covers the resolver in isolation.
|
||||
import { installStudioCustomEase } from "@hyperframes/core/runtime/custom-ease";
|
||||
import { gsap } from "gsap";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
describe("Studio hold ease", () => {
|
||||
it("holds the start value under seek until the destination time", () => {
|
||||
const runtimeGsap = { parseEase: gsap.parseEase.bind(gsap) };
|
||||
expect(installStudioCustomEase(runtimeGsap)).toBe(true);
|
||||
const hold = runtimeGsap.parseEase("hold");
|
||||
expect(hold).toBeTypeOf("function");
|
||||
if (typeof hold !== "function") return;
|
||||
|
||||
const target = { value: 0 };
|
||||
const timeline = gsap.timeline({ paused: true }).to(
|
||||
target,
|
||||
{
|
||||
value: 100,
|
||||
duration: 2,
|
||||
ease: hold,
|
||||
},
|
||||
0,
|
||||
);
|
||||
|
||||
timeline.seek(0.5);
|
||||
expect(target.value).toBe(0);
|
||||
timeline.seek(1);
|
||||
expect(target.value).toBe(0);
|
||||
timeline.seek(1.99);
|
||||
expect(target.value).toBe(0);
|
||||
timeline.seek(2);
|
||||
expect(target.value).toBe(100);
|
||||
timeline.kill();
|
||||
});
|
||||
});
|
||||
@@ -5,11 +5,15 @@ import { createRoot } from "react-dom/client";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { FlatMotionSection, FlatTimingRow } from "./propertyPanelFlatMotionSection";
|
||||
import type { DomEditSelection } from "./domEditing";
|
||||
import { usePlayerStore } from "../../player";
|
||||
|
||||
(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = "";
|
||||
// The store is module-global, so a test that parks a focused ease segment
|
||||
// would otherwise leak it into every test that runs after it.
|
||||
usePlayerStore.getState().reset();
|
||||
});
|
||||
|
||||
function baseElement(overrides: Partial<DomEditSelection> = {}): DomEditSelection {
|
||||
@@ -270,3 +274,68 @@ describe("FlatMotionSection", () => {
|
||||
act(() => root.unmount());
|
||||
});
|
||||
});
|
||||
|
||||
it("forwards focused bulk segment easing through the flat animation card", () => {
|
||||
const onUpdateKeyframeEase = vi.fn();
|
||||
const onUpdateSegmentEase = vi.fn();
|
||||
usePlayerStore.setState({
|
||||
focusedEaseSegment: {
|
||||
elementId: "index.html#hero",
|
||||
animationId: "a1",
|
||||
tweenPercentage: 50,
|
||||
collidingAnimationTargets: [
|
||||
{ animationId: "a1", tweenPercentage: 50 },
|
||||
{ animationId: "a2", tweenPercentage: 75 },
|
||||
],
|
||||
},
|
||||
});
|
||||
const { host, root } = renderInto(
|
||||
<FlatMotionSection
|
||||
element={baseElement()}
|
||||
animations={[
|
||||
{
|
||||
id: "a1",
|
||||
method: "to",
|
||||
position: 0,
|
||||
duration: 1,
|
||||
properties: { x: 100 },
|
||||
keyframes: {
|
||||
format: "percentage",
|
||||
keyframes: [
|
||||
{ percentage: 0, properties: { x: 0 } },
|
||||
{ percentage: 50, properties: { x: 100 } },
|
||||
],
|
||||
},
|
||||
} as never,
|
||||
]}
|
||||
showTiming={false}
|
||||
showEffects
|
||||
onSetAttribute={vi.fn()}
|
||||
onAddAnimation={vi.fn()}
|
||||
onUpdateProperty={vi.fn()}
|
||||
onUpdateMeta={vi.fn()}
|
||||
onDeleteAnimation={vi.fn()}
|
||||
onAddProperty={vi.fn()}
|
||||
onRemoveProperty={vi.fn()}
|
||||
onUpdateKeyframeEase={onUpdateKeyframeEase}
|
||||
onUpdateSegmentEase={onUpdateSegmentEase}
|
||||
/>,
|
||||
);
|
||||
|
||||
const dropdown = host.querySelector<HTMLButtonElement>("[data-ease-type-dropdown]");
|
||||
expect(dropdown).not.toBeNull();
|
||||
act(() => dropdown?.click());
|
||||
const preset = host.querySelector<HTMLButtonElement>('[data-ease-preset-id="quad-out"]');
|
||||
expect(preset).not.toBeNull();
|
||||
act(() => preset?.click());
|
||||
|
||||
expect(onUpdateSegmentEase).toHaveBeenCalledExactlyOnceWith(
|
||||
[
|
||||
{ animationId: "a1", tweenPercentage: 50 },
|
||||
{ animationId: "a2", tweenPercentage: 75 },
|
||||
],
|
||||
"power2.out",
|
||||
);
|
||||
expect(onUpdateKeyframeEase).not.toHaveBeenCalled();
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { scopedElementKey } from "../../hooks/gsapKeyframeCacheHelpers";
|
||||
import { useState } from "react";
|
||||
import type { GsapAnimation } from "@hyperframes/core/gsap-parser";
|
||||
import { useTrackDesignInput } from "../../contexts/DesignPanelInputContext";
|
||||
@@ -143,7 +144,7 @@ export function FlatMotionSection({
|
||||
// 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 renderedElementId = scopedElementKey(element);
|
||||
const focusedHere =
|
||||
focusedEaseSegment && focusedEaseSegment.elementId === renderedElementId
|
||||
? focusedEaseSegment
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import type { resolveEditingSections } from "@hyperframes/core/editing";
|
||||
import type { DomEditSelection } from "./domEditing";
|
||||
import type { PropertyPanelProps } from "./propertyPanelHelpers";
|
||||
import type { FlatLayoutSection } from "./propertyPanelFlatLayoutSection";
|
||||
|
||||
export type PropertyPanelFlatProps = Pick<
|
||||
PropertyPanelProps,
|
||||
| "projectId"
|
||||
| "projectDir"
|
||||
| "assets"
|
||||
| "previewIframeRef"
|
||||
| "onClearSelection"
|
||||
| "onUngroup"
|
||||
| "onSetStyle"
|
||||
| "onPreviewStyle"
|
||||
| "onSetAttribute"
|
||||
| "onSetAttributes"
|
||||
| "onSetAttributeLive"
|
||||
| "onApplyColorGradingScope"
|
||||
| "onSetHtmlAttribute"
|
||||
| "onRemoveBackground"
|
||||
| "onSetText"
|
||||
| "onSetTextFieldStyle"
|
||||
| "onPreviewTextFieldStyle"
|
||||
| "onAddTextField"
|
||||
| "onRemoveTextField"
|
||||
| "onAskAgent"
|
||||
| "onToggleElementHidden"
|
||||
| "onImportAssets"
|
||||
| "onAddMediaOverlay"
|
||||
| "onImportFonts"
|
||||
| "fontAssets"
|
||||
| "gsapAnimations"
|
||||
| "gsapMultipleTimelines"
|
||||
| "gsapUnsupportedTimelinePattern"
|
||||
| "onUpdateGsapProperty"
|
||||
| "onUpdateGsapMeta"
|
||||
| "onDeleteGsapAnimation"
|
||||
| "onAddGsapProperty"
|
||||
| "onRemoveGsapProperty"
|
||||
| "onUpdateGsapFromProperty"
|
||||
| "onAddGsapFromProperty"
|
||||
| "onRemoveGsapFromProperty"
|
||||
| "onAddGsapAnimation"
|
||||
| "onSetArcPath"
|
||||
| "onUpdateArcSegment"
|
||||
| "onUnroll"
|
||||
| "onUpdateKeyframeEase"
|
||||
| "onSetAllKeyframeEases"
|
||||
| "onUpdateSegmentEase"
|
||||
| "recordingState"
|
||||
| "recordingDuration"
|
||||
| "onToggleRecording"
|
||||
> &
|
||||
Pick<
|
||||
Parameters<typeof FlatLayoutSection>[0],
|
||||
| "displayX"
|
||||
| "displayY"
|
||||
| "displayW"
|
||||
| "displayH"
|
||||
| "displayR"
|
||||
| "manualOffsetEditingDisabled"
|
||||
| "manualSizeEditingDisabled"
|
||||
| "manualRotationEditingDisabled"
|
||||
| "commitManualOffset"
|
||||
| "commitManualSize"
|
||||
| "commitManualRotation"
|
||||
| "gsapAnimId"
|
||||
| "navKeyframes"
|
||||
| "animIdForProp"
|
||||
| "gsapRuntimeValues"
|
||||
| "elStart"
|
||||
| "elDuration"
|
||||
| "onCommitAnimatedProperty"
|
||||
| "onCommitAnimatedProperties"
|
||||
| "onSeekToTime"
|
||||
| "onRemoveKeyframe"
|
||||
| "onConvertToKeyframes"
|
||||
> & {
|
||||
element: DomEditSelection;
|
||||
styles: Record<string, string>;
|
||||
sections: ReturnType<typeof resolveEditingSections>;
|
||||
sourceLabel: string;
|
||||
gsapBorderRadius: { tl: number; tr: number; br: number; bl: number } | null;
|
||||
showEditableSections: boolean;
|
||||
selectedElementHidden: boolean;
|
||||
selectedElementId: string | null;
|
||||
clipboardCopied: boolean;
|
||||
onCopyElementInfo: () => void;
|
||||
currentTime: number;
|
||||
};
|
||||
@@ -2,6 +2,7 @@ import type { RefObject } from "react";
|
||||
import type { ArcPathSegment, GsapAnimation } from "@hyperframes/parsers/gsap-parser";
|
||||
import type { DomEditSelection } from "./domEditing";
|
||||
import type { ImportedFontAsset } from "./fontAssets";
|
||||
import type { GsapAnimationEditCallbacks } from "./gsapAnimationCallbacks";
|
||||
|
||||
export interface BackgroundRemovalProgress {
|
||||
status: "processing" | "complete" | "failed";
|
||||
@@ -123,6 +124,7 @@ export interface PropertyPanelProps {
|
||||
onRemoveKeyframe?: (animationId: string, percentage: number) => void;
|
||||
onUpdateKeyframeEase?: (animationId: string, percentage: number, ease: string) => void;
|
||||
onSetAllKeyframeEases?: (animationId: string, ease: string) => void;
|
||||
onUpdateSegmentEase?: NonNullable<GsapAnimationEditCallbacks["onUpdateSegmentEase"]>;
|
||||
onConvertToKeyframes?: (animationId: string, duration?: number) => void;
|
||||
onCommitAnimatedProperty?: (
|
||||
selection: DomEditSelection,
|
||||
|
||||
@@ -71,6 +71,7 @@ export interface DomEditActionsValue extends Pick<
|
||||
| "commitMutation"
|
||||
| "applyMarqueeSelection"
|
||||
| "handleUpdateKeyframeEase"
|
||||
| "handleUpdateSegmentEase"
|
||||
| "handleSetAllKeyframeEases"
|
||||
> {}
|
||||
|
||||
@@ -200,6 +201,7 @@ export function DomEditProvider({
|
||||
applyMarqueeSelection,
|
||||
handleUpdateKeyframeEase,
|
||||
handleSetAllKeyframeEases,
|
||||
handleUpdateSegmentEase,
|
||||
},
|
||||
children,
|
||||
}: {
|
||||
@@ -281,6 +283,7 @@ export function DomEditProvider({
|
||||
commitMutation: stableCommitMutation,
|
||||
applyMarqueeSelection,
|
||||
handleUpdateKeyframeEase,
|
||||
handleUpdateSegmentEase,
|
||||
handleSetAllKeyframeEases,
|
||||
}),
|
||||
[
|
||||
@@ -349,6 +352,7 @@ export function DomEditProvider({
|
||||
stableCommitMutation,
|
||||
applyMarqueeSelection,
|
||||
handleUpdateKeyframeEase,
|
||||
handleUpdateSegmentEase,
|
||||
handleSetAllKeyframeEases,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -3,8 +3,8 @@ import type { GsapAnimation } from "@hyperframes/core/gsap-parser";
|
||||
import { usePlayerStore, type KeyframeCacheEntry } from "../player/store/playerStore";
|
||||
import {
|
||||
clearKeyframeCacheForElement,
|
||||
clearKeyframeCacheForFile,
|
||||
pruneKeyframeCacheToFiles,
|
||||
replaceKeyframeCacheForFile,
|
||||
updateKeyframeCacheFromParsed,
|
||||
} from "./gsapKeyframeCacheHelpers";
|
||||
|
||||
@@ -70,48 +70,6 @@ describe("clearKeyframeCacheForElement", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("clearKeyframeCacheForFile", () => {
|
||||
it("clears the prefixed, fallback, and bare keys for every element of the file", () => {
|
||||
seed("comp.html#a");
|
||||
seed("index.html#a");
|
||||
seed("a");
|
||||
seed("comp.html#b");
|
||||
seed("b");
|
||||
|
||||
clearKeyframeCacheForFile("comp.html");
|
||||
|
||||
for (const key of ["comp.html#a", "index.html#a", "a", "comp.html#b", "b"]) {
|
||||
expect(cache().has(key)).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
// Several composition files re-scan concurrently, so a clear that walked the
|
||||
// index.html alias would delete rows a sibling file had just written.
|
||||
it("leaves an index.html-owned element alone when another file re-scans", () => {
|
||||
seed("index.html#title");
|
||||
seed("title");
|
||||
seed("comp.html#a");
|
||||
|
||||
clearKeyframeCacheForFile("comp.html");
|
||||
|
||||
expect(cache().has("index.html#title")).toBe(true);
|
||||
expect(cache().has("title")).toBe(true);
|
||||
expect(cache().has("comp.html#a")).toBe(false);
|
||||
});
|
||||
|
||||
it("leaves entries that belong to a different source file", () => {
|
||||
seed("comp.html#a");
|
||||
seed("a");
|
||||
seed("other.html#z");
|
||||
seed("z");
|
||||
|
||||
clearKeyframeCacheForFile("comp.html");
|
||||
|
||||
expect(cache().has("other.html#z")).toBe(true);
|
||||
expect(cache().has("z")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("pruneKeyframeCacheToFiles", () => {
|
||||
// Switching composition leaves the previous comp's elements cached with no
|
||||
// owner left to clear them: each file only ever clears its own entries.
|
||||
@@ -152,6 +110,99 @@ describe("pruneKeyframeCacheToFiles", () => {
|
||||
expect(cache().has("index.html#hero")).toBe(true);
|
||||
expect(cache().has("comp.html#a")).toBe(true);
|
||||
});
|
||||
|
||||
// The prune runs immediately before the atomic repopulate on every
|
||||
// composition switch. One notification per stale element put every subscriber
|
||||
// through a cache that was progressively emptier, which is the flash the
|
||||
// atomic repopulate exists to avoid.
|
||||
it("drops every stale file in one notification", () => {
|
||||
seed("old.html#a");
|
||||
seed("old.html#b");
|
||||
seed("older.html#c");
|
||||
seed("kept.html#k");
|
||||
let notifications = 0;
|
||||
const unsubscribe = usePlayerStore.subscribe(() => {
|
||||
notifications += 1;
|
||||
});
|
||||
|
||||
pruneKeyframeCacheToFiles(["kept.html"]);
|
||||
unsubscribe();
|
||||
|
||||
expect(notifications).toBe(1);
|
||||
expect([...cache().keys()]).toEqual(["kept.html#k"]);
|
||||
});
|
||||
|
||||
// A prune that finds nothing stale must not hand subscribers a fresh Map
|
||||
// identity: every keyframe consumer re-renders on cache identity alone.
|
||||
it("does not publish when nothing is stale", () => {
|
||||
seed("kept.html#k");
|
||||
const before = cache();
|
||||
let notifications = 0;
|
||||
const unsubscribe = usePlayerStore.subscribe(() => {
|
||||
notifications += 1;
|
||||
});
|
||||
|
||||
pruneKeyframeCacheToFiles(["kept.html"]);
|
||||
unsubscribe();
|
||||
|
||||
expect(notifications).toBe(0);
|
||||
expect(cache()).toBe(before);
|
||||
});
|
||||
});
|
||||
|
||||
describe("replaceKeyframeCacheForFile", () => {
|
||||
it("publishes complete keyframe and animation maps in one notification", () => {
|
||||
const staleEntry = entry();
|
||||
const otherEntry = entry();
|
||||
const staleAnimation = animWithKeyframes("stale");
|
||||
const freshAnimation = animWithKeyframes("fresh");
|
||||
usePlayerStore.setState({
|
||||
keyframeCache: new Map([
|
||||
["scene.html#stale", staleEntry],
|
||||
["index.html#stale", staleEntry],
|
||||
["stale", staleEntry],
|
||||
["other.html#other", otherEntry],
|
||||
["other", otherEntry],
|
||||
]),
|
||||
gsapAnimations: new Map([
|
||||
["scene.html#stale", [staleAnimation]],
|
||||
["index.html#stale", [staleAnimation]],
|
||||
["stale", [staleAnimation]],
|
||||
["other.html#other", [staleAnimation]],
|
||||
["other", [staleAnimation]],
|
||||
]),
|
||||
});
|
||||
const snapshots: Array<{ cacheKeys: string[]; animationKeys: string[] }> = [];
|
||||
const unsubscribe = usePlayerStore.subscribe((state) => {
|
||||
snapshots.push({
|
||||
cacheKeys: [...state.keyframeCache.keys()].sort(),
|
||||
animationKeys: [...state.gsapAnimations.keys()].sort(),
|
||||
});
|
||||
});
|
||||
|
||||
replaceKeyframeCacheForFile(
|
||||
"scene.html",
|
||||
new Map([["fresh", entry()]]),
|
||||
new Map([["fresh", [freshAnimation]]]),
|
||||
);
|
||||
unsubscribe();
|
||||
|
||||
expect(snapshots).toEqual([
|
||||
{
|
||||
cacheKeys: ["fresh", "index.html#fresh", "other", "other.html#other", "scene.html#fresh"],
|
||||
animationKeys: [
|
||||
"fresh",
|
||||
"index.html#fresh",
|
||||
"other",
|
||||
"other.html#other",
|
||||
"scene.html#fresh",
|
||||
],
|
||||
},
|
||||
]);
|
||||
expect(usePlayerStore.getState().gsapAnimations.get("scene.html#fresh")).toEqual([
|
||||
freshAnimation,
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("updateKeyframeCacheFromParsed", () => {
|
||||
|
||||
@@ -11,6 +11,47 @@ import {
|
||||
type MergeableKeyframe,
|
||||
} from "./gsapTweenSynth";
|
||||
|
||||
/** Both cache maps mid-edit, before the single store publish. */
|
||||
export interface KeyframeCacheDraft {
|
||||
keyframeCache: Map<string, KeyframeCacheEntry>;
|
||||
gsapAnimations: Map<string, GsapAnimation[]>;
|
||||
}
|
||||
|
||||
function sameEntries<V>(before: ReadonlyMap<string, V>, after: ReadonlyMap<string, V>): boolean {
|
||||
if (before.size !== after.size) return false;
|
||||
for (const [key, value] of before) {
|
||||
if (after.get(key) !== value) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every multi-key cache writer publishes through here: clone both maps once,
|
||||
* let the caller edit the drafts, publish once. The per-key store setters turned
|
||||
* one logical refresh into N notifications, and every subscriber that rendered
|
||||
* in between saw a cache that was half the old file and half the new one. The
|
||||
* identity check keeps an edit that changed nothing from allocating fresh maps
|
||||
* and re-rendering every subscriber, which is the guard the per-key setters used
|
||||
* to carry individually.
|
||||
*/
|
||||
export function publishKeyframeCache(edit: (draft: KeyframeCacheDraft) => void): void {
|
||||
const { keyframeCache, gsapAnimations } = usePlayerStore.getState();
|
||||
const draft: KeyframeCacheDraft = {
|
||||
keyframeCache: new Map(keyframeCache),
|
||||
gsapAnimations: new Map(gsapAnimations),
|
||||
};
|
||||
edit(draft);
|
||||
if (
|
||||
sameEntries(keyframeCache, draft.keyframeCache) &&
|
||||
sameEntries(gsapAnimations, draft.gsapAnimations)
|
||||
)
|
||||
return;
|
||||
usePlayerStore.setState({
|
||||
keyframeCache: draft.keyframeCache,
|
||||
gsapAnimations: draft.gsapAnimations,
|
||||
});
|
||||
}
|
||||
|
||||
export function updateKeyframeCacheFromParsed(
|
||||
animations: GsapAnimation[],
|
||||
targetPath: string,
|
||||
@@ -18,7 +59,7 @@ export function updateKeyframeCacheFromParsed(
|
||||
mutation: Record<string, unknown>,
|
||||
doc?: Document | null,
|
||||
): void {
|
||||
const { setKeyframeCache, elements, domClipChildren } = usePlayerStore.getState();
|
||||
const { elements, domClipChildren } = usePlayerStore.getState();
|
||||
const idsWithKeyframes = new Set<string>();
|
||||
// Attributed keyframes only: everything in here came from a parsed tween via
|
||||
// toClipKeyframes, so the merge can rely on the source identity. It widens
|
||||
@@ -70,15 +111,41 @@ export function updateKeyframeCacheFromParsed(
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const [id, entry] of merged) {
|
||||
for (const key of elementCacheKeys(targetPath, id)) setKeyframeCache(key, entry);
|
||||
writeGsapAnimationsForElement(targetPath, id, sourceAnimations.get(id));
|
||||
}
|
||||
const mutationSelector = (mutation as { targetSelector?: string }).targetSelector;
|
||||
const mutated = mutationSelector ? resolveSelectorElementIds(mutationSelector, doc) : [];
|
||||
const targetIds = mutated.length > 0 ? mutated : selectionId ? [selectionId] : [];
|
||||
for (const targetId of targetIds) {
|
||||
if (!idsWithKeyframes.has(targetId)) clearKeyframeCacheForElement(targetPath, targetId);
|
||||
publishKeyframeCache((draft) => {
|
||||
for (const [id, entry] of merged) {
|
||||
writeElementIntoDraft(draft, targetPath, id, entry, sourceAnimations.get(id));
|
||||
}
|
||||
for (const targetId of targetIds) {
|
||||
if (!idsWithKeyframes.has(targetId)) deleteElementFromDraft(draft, targetPath, targetId);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function writeElementIntoDraft(
|
||||
draft: KeyframeCacheDraft,
|
||||
sourceFile: string,
|
||||
elementId: string,
|
||||
entry: KeyframeCacheEntry,
|
||||
animations: GsapAnimation[] | undefined,
|
||||
): void {
|
||||
for (const key of elementCacheKeys(sourceFile, elementId)) {
|
||||
draft.keyframeCache.set(key, entry);
|
||||
if (animations) draft.gsapAnimations.set(key, animations);
|
||||
else draft.gsapAnimations.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
function deleteElementFromDraft(
|
||||
draft: KeyframeCacheDraft,
|
||||
sourceFile: string,
|
||||
elementId: string,
|
||||
): void {
|
||||
for (const key of elementCacheKeys(sourceFile, elementId)) {
|
||||
draft.keyframeCache.delete(key);
|
||||
draft.gsapAnimations.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -91,50 +158,37 @@ export function updateKeyframeCacheFromParsed(
|
||||
* preview overlay) fall back to the bare id when an element has no
|
||||
* source-prefixed key — so a clear that drops only the prefixed keys leaves the
|
||||
* bare entry behind and those readers keep showing keyframes the element no
|
||||
* longer has. Each delete is guarded by `has` so an absent key doesn't allocate
|
||||
* a new cache map and re-render every subscriber.
|
||||
* longer has. publishKeyframeCache skips the store write entirely when none of
|
||||
* the keys were present, so an absent element doesn't re-render every
|
||||
* subscriber.
|
||||
*/
|
||||
export function clearKeyframeCacheForElement(sourceFile: string, elementId: string): void {
|
||||
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);
|
||||
}
|
||||
publishKeyframeCache((draft) => deleteElementFromDraft(draft, sourceFile, elementId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear every cached element of `sourceFile` before a full re-scan repopulates
|
||||
* it. Only the file's OWN prefixed keys name the ids to clear: every write sets
|
||||
* the prefixed key (see elementCacheKeys), so the file's elements are all
|
||||
* reachable that way, and clearKeyframeCacheForElement then takes the
|
||||
* index.html alias and the bare key with them — an element whose keyframes were
|
||||
* removed (and so is absent from the re-scan) leaves no stale bare entry
|
||||
* behind. Reading the alias prefix here instead would collect ids owned by
|
||||
* OTHER files, and several files re-scan concurrently, so this file's clear
|
||||
* would wipe the entries a sibling file had just written.
|
||||
*/
|
||||
export function clearKeyframeCacheForFile(sourceFile: string): void {
|
||||
const { keyframeCache, gsapAnimations } = usePlayerStore.getState();
|
||||
function cachedElementIdsForFile(
|
||||
sourceFile: string,
|
||||
keyframeCache: ReadonlyMap<string, KeyframeCacheEntry>,
|
||||
gsapAnimations: ReadonlyMap<string, GsapAnimation[]>,
|
||||
): Set<string> {
|
||||
const sfPrefix = `${sourceFile}#`;
|
||||
const ids = new Set<string>();
|
||||
for (const key of [...keyframeCache.keys(), ...gsapAnimations.keys()]) {
|
||||
if (!key.startsWith(sfPrefix)) continue;
|
||||
ids.add(key.slice(sfPrefix.length));
|
||||
}
|
||||
for (const id of ids) {
|
||||
clearKeyframeCacheForElement(sourceFile, id);
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop every cached element owned by a file that is no longer on screen. Each
|
||||
* file only ever clears its OWN entries (see clearKeyframeCacheForFile), so
|
||||
* file only ever writes its OWN prefixed entries (see elementCacheKeys), so
|
||||
* switching composition left the previous composition's elements cached forever
|
||||
* — 240 entries per switch on a 120-clip comp, in both keyframeCache and
|
||||
* gsapAnimations, with nothing to evict them. Called once before a re-scan, with
|
||||
* the full set of files that scan covers.
|
||||
* (240 entries per switch on a 120-clip comp, in both keyframeCache and
|
||||
* gsapAnimations, with nothing to evict them). Called once before a re-scan,
|
||||
* with the full set of files that scan covers, and it publishes once: the prune
|
||||
* runs immediately before the atomic repopulate, so a per-element publish here
|
||||
* would reintroduce the empty-cache flash that repopulate was made to avoid.
|
||||
*/
|
||||
export function pruneKeyframeCacheToFiles(files: readonly string[]): void {
|
||||
const keep = new Set(files);
|
||||
@@ -142,8 +196,8 @@ export function pruneKeyframeCacheToFiles(files: readonly string[]): void {
|
||||
const stale = new Map<string, Set<string>>();
|
||||
for (const key of [...keyframeCache.keys(), ...gsapAnimations.keys()]) {
|
||||
const hash = key.indexOf("#");
|
||||
// Bare-id aliases carry no owner; clearKeyframeCacheForElement takes them
|
||||
// with their prefixed key, so skipping them here loses nothing.
|
||||
// Bare-id aliases carry no owner; deleteElementFromDraft takes them with
|
||||
// their prefixed key, so skipping them here loses nothing.
|
||||
if (hash < 0) continue;
|
||||
const sourceFile = key.slice(0, hash);
|
||||
if (keep.has(sourceFile)) continue;
|
||||
@@ -151,9 +205,25 @@ export function pruneKeyframeCacheToFiles(files: readonly string[]): void {
|
||||
ids.add(key.slice(hash + 1));
|
||||
stale.set(sourceFile, ids);
|
||||
}
|
||||
for (const [sourceFile, ids] of stale) {
|
||||
for (const id of ids) clearKeyframeCacheForElement(sourceFile, id);
|
||||
}
|
||||
publishKeyframeCache((draft) => {
|
||||
for (const [sourceFile, ids] of stale) {
|
||||
for (const id of ids) deleteElementFromDraft(draft, sourceFile, id);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The source-scoped key that names one element across panels and the store
|
||||
* (focused ease segment, keyframe cache reads). Four call sites built this
|
||||
* string by hand and two of them omitted the index.html fallback, so an element
|
||||
* with no sourceFile was addressed as `#box` by one panel and `index.html#box`
|
||||
* by another and the two never matched. One builder keeps them on one key.
|
||||
*/
|
||||
export function scopedElementKey(element: {
|
||||
sourceFile?: string | null;
|
||||
id?: string | null;
|
||||
}): string {
|
||||
return `${element.sourceFile || "index.html"}#${element.id}`;
|
||||
}
|
||||
|
||||
/** Every cache key a write for this element sets, in read-preference order. */
|
||||
@@ -163,15 +233,37 @@ export function elementCacheKeys(sourceFile: string, elementId: string): string[
|
||||
: [`${sourceFile}#${elementId}`, `index.html#${elementId}`, elementId];
|
||||
}
|
||||
|
||||
/** Replace one file's complete cache snapshot with one atomic store publish. */
|
||||
export function replaceKeyframeCacheForFile(
|
||||
sourceFile: string,
|
||||
entries: ReadonlyMap<string, KeyframeCacheEntry>,
|
||||
animationsByElement: ReadonlyMap<string, GsapAnimation[]>,
|
||||
): void {
|
||||
publishKeyframeCache((draft) => {
|
||||
for (const id of cachedElementIdsForFile(
|
||||
sourceFile,
|
||||
draft.keyframeCache,
|
||||
draft.gsapAnimations,
|
||||
)) {
|
||||
deleteElementFromDraft(draft, sourceFile, id);
|
||||
}
|
||||
for (const [id, entry] of entries) {
|
||||
writeElementIntoDraft(draft, sourceFile, id, entry, animationsByElement.get(id));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
publishKeyframeCache((draft) => {
|
||||
for (const key of elementCacheKeys(sourceFile, elementId)) {
|
||||
if (animations) draft.gsapAnimations.set(key, animations);
|
||||
else draft.gsapAnimations.delete(key);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function buildCacheKey(sourceFile: string, elementId: string): string {
|
||||
|
||||
@@ -6,11 +6,7 @@
|
||||
import type { GsapAnimation, GsapKeyframesData, ParsedGsap } from "@hyperframes/core/gsap-parser";
|
||||
import { isStudioHoldSet } from "@hyperframes/core/gsap-parser";
|
||||
import { usePlayerStore } from "../player/store/playerStore";
|
||||
import {
|
||||
clearKeyframeCacheForFile,
|
||||
elementCacheKeys,
|
||||
writeGsapAnimationsForElement,
|
||||
} from "./gsapKeyframeCacheHelpers";
|
||||
import { replaceKeyframeCacheForFile } from "./gsapKeyframeCacheHelpers";
|
||||
import { resolveClipTimingBasis, resolveSelectorElementIds, toClipKeyframes } from "./gsapShared";
|
||||
import {
|
||||
deduplicateKeyframes,
|
||||
@@ -81,8 +77,6 @@ export async function populateKeyframeCacheFromAst(
|
||||
): Promise<void> {
|
||||
const parsed = await fetchParsedAnimations(projectId, sf);
|
||||
if (!parsed) return;
|
||||
const { setKeyframeCache } = usePlayerStore.getState();
|
||||
clearKeyframeCacheForFile(sf);
|
||||
const { elements, domClipChildren } = usePlayerStore.getState();
|
||||
const mergedByElement = new Map<string, GsapKeyframesData<MergeableKeyframe>>();
|
||||
const sourceByElement = new Map<string, GsapAnimation[]>();
|
||||
@@ -109,8 +103,5 @@ export async function populateKeyframeCacheFromAst(
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const [id, kfData] of mergedByElement) {
|
||||
for (const key of elementCacheKeys(sf, id)) setKeyframeCache(key, kfData);
|
||||
writeGsapAnimationsForElement(sf, id, sourceByElement.get(id));
|
||||
}
|
||||
replaceKeyframeCacheForFile(sf, mergedByElement, sourceByElement);
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { describe, expect, it, vi } from "vitest";
|
||||
import { shouldUseSdkCutover } from "../utils/sdkCutover";
|
||||
import type { PatchOperation } from "../utils/sourcePatcher";
|
||||
import type { Composition } from "@hyperframes/sdk";
|
||||
import type { DomEditSelection } from "../components/editor/domEditingTypes";
|
||||
import type { UseDomEditSessionParams } from "./useDomEditSession";
|
||||
|
||||
const styleOp = (property: string, value: string): PatchOperation => ({
|
||||
@@ -57,6 +58,8 @@ const capturedOnReorderShadow: { fn: ((targets: string[]) => void) | undefined }
|
||||
fn: undefined,
|
||||
};
|
||||
|
||||
const domEditSelectionRef: { current: DomEditSelection | null } = { current: null };
|
||||
const gsapCommitMutation = Object.assign(vi.fn(), { batch: vi.fn() });
|
||||
vi.mock("../utils/sdkResolverShadow", () => ({
|
||||
runResolverShadow: vi.fn(),
|
||||
recordResolverParity: (...args: unknown[]) => recordResolverParity(...args),
|
||||
@@ -83,11 +86,11 @@ vi.mock("./useDomEditCommits", () => ({
|
||||
}));
|
||||
vi.mock("./useDomSelection", () => ({
|
||||
useDomSelection: () => ({
|
||||
domEditSelection: null,
|
||||
domEditSelection: domEditSelectionRef.current,
|
||||
domEditGroupSelections: [],
|
||||
domEditHoverSelection: null,
|
||||
activeGroupElement: null,
|
||||
domEditSelectionRef: { current: null },
|
||||
domEditSelectionRef,
|
||||
domEditGroupSelectionsRef: { current: [] },
|
||||
setActiveGroupElement: vi.fn(),
|
||||
applyDomSelection: vi.fn(),
|
||||
@@ -123,7 +126,7 @@ vi.mock("./useGsapTweenCache", () => ({
|
||||
}));
|
||||
vi.mock("./useGsapScriptCommits", () => ({
|
||||
useGsapScriptCommits: () => ({
|
||||
commitMutation: vi.fn(),
|
||||
commitMutation: gsapCommitMutation,
|
||||
updateGsapProperty: vi.fn(),
|
||||
updateGsapMeta: vi.fn(),
|
||||
deleteGsapAnimation: vi.fn(),
|
||||
@@ -277,3 +280,149 @@ describe("onReorderShadow source filter", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("bulk segment ease commits", () => {
|
||||
it("uses one ordered batch for many ids and sane paths for one or no ids", async () => {
|
||||
const { useDomEditSession } = await import("./useDomEditSession");
|
||||
const selection: DomEditSelection = {
|
||||
id: "hero",
|
||||
element: document.createElement("div"),
|
||||
label: "Hero",
|
||||
tagName: "DIV",
|
||||
sourceFile: "index.html",
|
||||
compositionPath: "index.html",
|
||||
isCompositionHost: false,
|
||||
isInsideLockedComposition: false,
|
||||
boundingBox: { x: 0, y: 0, width: 100, height: 100 },
|
||||
textContent: null,
|
||||
dataAttributes: {},
|
||||
inlineStyles: {},
|
||||
computedStyles: {},
|
||||
textFields: [],
|
||||
capabilities: {
|
||||
canSelect: true,
|
||||
canEditStyles: true,
|
||||
canCrop: true,
|
||||
canMove: true,
|
||||
canResize: true,
|
||||
canApplyManualOffset: true,
|
||||
canApplyManualSize: true,
|
||||
canApplyManualRotation: true,
|
||||
},
|
||||
};
|
||||
domEditSelectionRef.current = selection;
|
||||
gsapCommitMutation.mockClear();
|
||||
gsapCommitMutation.batch.mockClear();
|
||||
let updateSegmentEase:
|
||||
| ((targets: Array<{ animationId: string; tweenPercentage: number }>, ease: string) => void)
|
||||
| undefined;
|
||||
|
||||
function Probe() {
|
||||
const params: UseDomEditSessionParams = {
|
||||
projectId: "proj-1",
|
||||
activeCompPath: "index.html",
|
||||
isMasterView: false,
|
||||
compIdToSrc: new Map(),
|
||||
captionEditMode: false,
|
||||
compositionLoading: false,
|
||||
previewIframeRef: { current: null },
|
||||
timelineElements: [],
|
||||
setSelectedTimelineElementId: vi.fn(),
|
||||
setRightCollapsed: vi.fn(),
|
||||
setRightPanelTab: vi.fn(),
|
||||
showToast: vi.fn(),
|
||||
refreshPreviewDocumentVersion: vi.fn(),
|
||||
queueDomEditSave: async <T,>(save: () => Promise<T>) => save(),
|
||||
readProjectFile: async () => "",
|
||||
writeProjectFile: async () => {},
|
||||
updateEditingFileContent: vi.fn(),
|
||||
domEditSaveTimestampRef: { current: 0 },
|
||||
editHistory: { recordEdit: async () => {} },
|
||||
fileTree: [],
|
||||
importedFontAssetsRef: { current: [] },
|
||||
projectDir: null,
|
||||
projectIdRef: { current: "proj-1" },
|
||||
previewIframe: null,
|
||||
refreshKey: 0,
|
||||
previewDocumentVersion: 0,
|
||||
rightPanelTab: "design",
|
||||
applyStudioManualEditsToPreviewRef: { current: async () => {} },
|
||||
syncPreviewHistoryHotkey: vi.fn(),
|
||||
reloadPreview: vi.fn(),
|
||||
setRefreshKey: vi.fn(),
|
||||
};
|
||||
updateSegmentEase = useDomEditSession(params).handleUpdateSegmentEase;
|
||||
return null;
|
||||
}
|
||||
|
||||
const container = document.createElement("div");
|
||||
const root = createRoot(container);
|
||||
act(() => root.render(<Probe />));
|
||||
try {
|
||||
expect(updateSegmentEase).toBeTypeOf("function");
|
||||
if (!updateSegmentEase) return;
|
||||
const options = { label: "Update segment ease", softReload: true };
|
||||
const targets = [
|
||||
{ animationId: "move-x", tweenPercentage: 20 },
|
||||
{ animationId: "move-y", tweenPercentage: 50 },
|
||||
{ animationId: "fade", tweenPercentage: 80 },
|
||||
];
|
||||
updateSegmentEase(targets, "power2.inOut");
|
||||
|
||||
expect(gsapCommitMutation).not.toHaveBeenCalled();
|
||||
expect(gsapCommitMutation.batch).toHaveBeenCalledTimes(1);
|
||||
expect(gsapCommitMutation.batch).toHaveBeenCalledWith(
|
||||
targets.map(({ animationId, tweenPercentage }) => ({
|
||||
selection,
|
||||
mutation: {
|
||||
type: "update-keyframe",
|
||||
animationId,
|
||||
percentage: tweenPercentage,
|
||||
properties: {},
|
||||
ease: "power2.inOut",
|
||||
},
|
||||
options,
|
||||
})),
|
||||
options,
|
||||
);
|
||||
|
||||
gsapCommitMutation.mockClear();
|
||||
gsapCommitMutation.batch.mockClear();
|
||||
updateSegmentEase([{ animationId: "fade", tweenPercentage: 25 }], "none");
|
||||
expect(gsapCommitMutation).toHaveBeenCalledTimes(1);
|
||||
expect(gsapCommitMutation).toHaveBeenCalledWith(
|
||||
selection,
|
||||
{
|
||||
type: "update-keyframe",
|
||||
animationId: "fade",
|
||||
percentage: 25,
|
||||
properties: {},
|
||||
ease: "none",
|
||||
},
|
||||
{ label: "Update keyframe ease", softReload: true },
|
||||
);
|
||||
expect(gsapCommitMutation.batch).not.toHaveBeenCalled();
|
||||
|
||||
gsapCommitMutation.mockClear();
|
||||
updateSegmentEase([], "linear");
|
||||
expect(gsapCommitMutation).not.toHaveBeenCalled();
|
||||
expect(gsapCommitMutation.batch).not.toHaveBeenCalled();
|
||||
|
||||
// A commit with no batch transport (a wrapped one, e.g. inside a gesture
|
||||
// transaction) must still write every tween. Optional-chaining the batch
|
||||
// call would drop the whole edit here and report nothing.
|
||||
gsapCommitMutation.mockClear();
|
||||
const restoreBatch = gsapCommitMutation.batch;
|
||||
Reflect.deleteProperty(gsapCommitMutation, "batch");
|
||||
try {
|
||||
updateSegmentEase(targets, "power1.in");
|
||||
expect(gsapCommitMutation).toHaveBeenCalledTimes(targets.length);
|
||||
} finally {
|
||||
gsapCommitMutation.batch = restoreBatch;
|
||||
}
|
||||
} finally {
|
||||
domEditSelectionRef.current = null;
|
||||
act(() => root.unmount());
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -19,8 +19,7 @@ import { useGsapCacheVersion } from "./useGsapTweenCache";
|
||||
import { useDomEditWiring } from "./useDomEditWiring";
|
||||
import { useGsapAwareEditing } from "./useGsapAwareEditing";
|
||||
import { useStudioSelectionPublisher } from "./useStudioSelectionPublisher";
|
||||
|
||||
// ── Types ──
|
||||
import { useKeyframeEaseCommits } from "./useKeyframeEaseCommits";
|
||||
|
||||
interface RecordEditInput {
|
||||
label: string;
|
||||
@@ -71,8 +70,6 @@ export interface UseDomEditSessionParams {
|
||||
forceReloadSdkSession?: () => void;
|
||||
}
|
||||
|
||||
// ── Hook ──
|
||||
|
||||
export function useDomEditSession({
|
||||
projectId,
|
||||
activeCompPath,
|
||||
@@ -113,8 +110,6 @@ export function useDomEditSession({
|
||||
forceReloadSdkSession,
|
||||
}: UseDomEditSessionParams) {
|
||||
void _setRefreshKey;
|
||||
// ── Selection ──
|
||||
|
||||
const {
|
||||
domEditSelection,
|
||||
domEditGroupSelections,
|
||||
@@ -149,8 +144,6 @@ export function useDomEditSession({
|
||||
rightPanelTab,
|
||||
});
|
||||
|
||||
// ── Agent modal ──
|
||||
|
||||
const {
|
||||
agentModalOpen,
|
||||
agentModalAnchorPoint,
|
||||
@@ -423,9 +416,6 @@ export function useDomEditSession({
|
||||
removeAllKeyframes,
|
||||
handleDomManualEditsReset,
|
||||
});
|
||||
|
||||
// ── Preview interaction ──
|
||||
|
||||
const {
|
||||
handlePreviewCanvasMouseDown,
|
||||
handlePreviewCanvasPointerMove,
|
||||
@@ -444,9 +434,6 @@ export function useDomEditSession({
|
||||
setActiveGroupElement,
|
||||
onClickToSource,
|
||||
});
|
||||
|
||||
// ── GSAP-aware geometry intercepts + animated property commit ──
|
||||
|
||||
const {
|
||||
handleGsapAwarePathOffsetCommit,
|
||||
handleGsapAwareGroupPathOffsetCommit,
|
||||
@@ -473,45 +460,8 @@ export function useDomEditSession({
|
||||
setArcPath,
|
||||
updateArcSegment,
|
||||
});
|
||||
|
||||
const handleUpdateKeyframeEase = useCallback(
|
||||
(animationId: string, percentage: number, ease: string) => {
|
||||
const sel = domEditSelectionRef.current;
|
||||
if (!sel) return;
|
||||
gsapCommitMutation(
|
||||
sel,
|
||||
{
|
||||
type: "update-keyframe",
|
||||
animationId,
|
||||
percentage,
|
||||
properties: {},
|
||||
ease,
|
||||
},
|
||||
{ label: "Update keyframe ease", softReload: true },
|
||||
);
|
||||
},
|
||||
[gsapCommitMutation, domEditSelectionRef],
|
||||
);
|
||||
|
||||
// Apply one ease to every segment at once (AE select-all + F9): set easeEach
|
||||
// and strip per-keyframe overrides in a single mutation.
|
||||
const handleSetAllKeyframeEases = useCallback(
|
||||
(animationId: string, ease: string) => {
|
||||
const sel = domEditSelectionRef.current;
|
||||
if (!sel) return;
|
||||
gsapCommitMutation(
|
||||
sel,
|
||||
{
|
||||
type: "update-meta",
|
||||
animationId,
|
||||
updates: { easeEach: ease, resetKeyframeEases: true },
|
||||
},
|
||||
{ label: "Apply ease to all segments", softReload: true },
|
||||
);
|
||||
},
|
||||
[gsapCommitMutation, domEditSelectionRef],
|
||||
);
|
||||
|
||||
const { handleUpdateSegmentEase, handleUpdateKeyframeEase, handleSetAllKeyframeEases } =
|
||||
useKeyframeEaseCommits({ gsapCommitMutation, domEditSelectionRef });
|
||||
return {
|
||||
// State
|
||||
domEditSelection,
|
||||
@@ -591,6 +541,7 @@ export function useDomEditSession({
|
||||
commitAnimatedProperty,
|
||||
commitAnimatedProperties,
|
||||
handleSetArcPath,
|
||||
handleUpdateSegmentEase,
|
||||
handleUpdateArcSegment,
|
||||
handleUnroll,
|
||||
invalidateGsapCache: bumpGsapCache,
|
||||
|
||||
@@ -5,6 +5,7 @@ import { readRuntimeKeyframes, scanAllRuntimeKeyframes } from "./gsapRuntimeBrid
|
||||
import {
|
||||
clearKeyframeCacheForElement,
|
||||
pruneKeyframeCacheToFiles,
|
||||
publishKeyframeCache,
|
||||
writeGsapAnimationsForElement,
|
||||
} from "./gsapKeyframeCacheHelpers";
|
||||
import { resolveClipTimingBasis, toAbsoluteTime, toClipPercentage } from "./gsapShared";
|
||||
@@ -313,11 +314,15 @@ export function useGsapAnimationsForElement(
|
||||
...(ease ? { ease } : {}),
|
||||
...(easeEach ? { easeEach } : {}),
|
||||
};
|
||||
const { setKeyframeCache } = usePlayerStore.getState();
|
||||
setKeyframeCache(`${sourceFile}#${elementId}`, merged);
|
||||
// PropertyPanel reads the cache by bare elementId (without sourceFile prefix),
|
||||
// so write a duplicate entry under the bare key for cross-component lookups.
|
||||
setKeyframeCache(elementId, merged);
|
||||
// PropertyPanel reads the cache by bare elementId (without sourceFile
|
||||
// prefix), so the same entry is written under the bare key for
|
||||
// cross-component lookups. Both keys land in one publish: a reader that woke
|
||||
// between two separate writes saw the prefixed key updated and the bare one
|
||||
// still stale.
|
||||
publishKeyframeCache((draft) => {
|
||||
draft.keyframeCache.set(`${sourceFile}#${elementId}`, merged);
|
||||
draft.keyframeCache.set(elementId, merged);
|
||||
});
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [elementId, sourceFile, animations, domClipChildrenKey]);
|
||||
|
||||
@@ -416,29 +421,35 @@ export function usePopulateKeyframeCacheForFile(
|
||||
}
|
||||
const scanned = scanAllRuntimeKeyframes(iframe, clipById);
|
||||
if (scanned.size === 0) return false;
|
||||
const { setKeyframeCache, keyframeCache } = usePlayerStore.getState();
|
||||
for (const [id, data] of scanned) {
|
||||
const cacheKey = `${sf}#${id}`;
|
||||
const fallbackKey = `index.html#${id}`;
|
||||
const alreadyCached =
|
||||
keyframeCache.has(cacheKey) || keyframeCache.has(fallbackKey) || keyframeCache.has(id);
|
||||
if (alreadyCached) continue;
|
||||
// Skip position-only set tweens from runtime too — same filter as AST path
|
||||
const isPosOnly =
|
||||
data.keyframes.length === 1 &&
|
||||
Object.keys(data.keyframes[0].properties).every((k) => k === "x" || k === "y");
|
||||
if (isPosOnly) {
|
||||
continue;
|
||||
// One publish for the whole scan: a scan of a 120-clip composition used to
|
||||
// emit up to three store notifications per element, and every subscriber
|
||||
// in between re-rendered against a cache only partly filled in.
|
||||
publishKeyframeCache((draft) => {
|
||||
for (const [id, data] of scanned) {
|
||||
const cacheKey = `${sf}#${id}`;
|
||||
const fallbackKey = `index.html#${id}`;
|
||||
const alreadyCached =
|
||||
draft.keyframeCache.has(cacheKey) ||
|
||||
draft.keyframeCache.has(fallbackKey) ||
|
||||
draft.keyframeCache.has(id);
|
||||
if (alreadyCached) continue;
|
||||
// Skip position-only set tweens from runtime too, same filter as AST path
|
||||
const isPosOnly =
|
||||
data.keyframes.length === 1 &&
|
||||
Object.keys(data.keyframes[0].properties).every((k) => k === "x" || k === "y");
|
||||
if (isPosOnly) {
|
||||
continue;
|
||||
}
|
||||
const entry = {
|
||||
format: "percentage" as const,
|
||||
keyframes: data.keyframes,
|
||||
...(data.easeEach ? { easeEach: data.easeEach } : {}),
|
||||
};
|
||||
draft.keyframeCache.set(cacheKey, entry);
|
||||
if (sf !== "index.html") draft.keyframeCache.set(fallbackKey, entry);
|
||||
draft.keyframeCache.set(id, entry);
|
||||
}
|
||||
const entry = {
|
||||
format: "percentage" as const,
|
||||
keyframes: data.keyframes,
|
||||
...(data.easeEach ? { easeEach: data.easeEach } : {}),
|
||||
};
|
||||
setKeyframeCache(cacheKey, entry);
|
||||
if (sf !== "index.html") setKeyframeCache(fallbackKey, entry);
|
||||
setKeyframeCache(id, entry);
|
||||
}
|
||||
});
|
||||
runtimeScanDoneRef.current = `kf-cache:${projectId}:${sf}:${version}`;
|
||||
return true;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import { useCallback, type RefObject } from "react";
|
||||
import type { CommitMutation } from "./gsapScriptCommitTypes";
|
||||
import type { AnimationKeyframeTarget } from "./gsapTweenSynth";
|
||||
import type { DomEditSelection } from "../components/editor/domEditing";
|
||||
|
||||
interface KeyframeEaseCommitsInput {
|
||||
gsapCommitMutation: CommitMutation;
|
||||
domEditSelectionRef: RefObject<DomEditSelection | null>;
|
||||
}
|
||||
|
||||
export function useKeyframeEaseCommits({
|
||||
gsapCommitMutation,
|
||||
domEditSelectionRef,
|
||||
}: KeyframeEaseCommitsInput) {
|
||||
const handleUpdateSegmentEase = useCallback(
|
||||
(targets: AnimationKeyframeTarget[], ease: string) => {
|
||||
const selection = domEditSelectionRef.current;
|
||||
if (!selection || targets.length === 0) return;
|
||||
const options = {
|
||||
label: targets.length === 1 ? "Update keyframe ease" : "Update segment ease",
|
||||
softReload: true,
|
||||
};
|
||||
const calls = targets.map(({ animationId, tweenPercentage }) => ({
|
||||
selection,
|
||||
mutation: {
|
||||
type: "update-keyframe",
|
||||
animationId,
|
||||
percentage: tweenPercentage,
|
||||
properties: {},
|
||||
ease,
|
||||
},
|
||||
options,
|
||||
}));
|
||||
if (calls.length === 1) {
|
||||
const call = calls[0];
|
||||
if (call) void gsapCommitMutation(call.selection, call.mutation, call.options);
|
||||
return;
|
||||
}
|
||||
const batch = gsapCommitMutation.batch;
|
||||
if (batch) {
|
||||
void batch(calls, options);
|
||||
return;
|
||||
}
|
||||
// A wrapped commit (a gesture transaction, say) carries no batch
|
||||
// transport. Serial keeps the edit correct at the cost of one round trip
|
||||
// per tween and one undo entry per tween; an optional-chained call here
|
||||
// would silently drop the whole edit instead.
|
||||
for (const call of calls)
|
||||
void gsapCommitMutation(call.selection, call.mutation, call.options);
|
||||
},
|
||||
[gsapCommitMutation, domEditSelectionRef],
|
||||
);
|
||||
|
||||
const handleUpdateKeyframeEase = useCallback(
|
||||
(animationId: string, percentage: number, ease: string) =>
|
||||
handleUpdateSegmentEase([{ animationId, tweenPercentage: percentage }], ease),
|
||||
[handleUpdateSegmentEase],
|
||||
);
|
||||
|
||||
const handleSetAllKeyframeEases = useCallback(
|
||||
(animationId: string, ease: string) => {
|
||||
const sel = domEditSelectionRef.current;
|
||||
if (!sel) return;
|
||||
gsapCommitMutation(
|
||||
sel,
|
||||
{
|
||||
type: "update-meta",
|
||||
animationId,
|
||||
updates: { easeEach: ease, resetKeyframeEases: true },
|
||||
},
|
||||
{ label: "Apply ease to all segments", softReload: true },
|
||||
);
|
||||
},
|
||||
[gsapCommitMutation, domEditSelectionRef],
|
||||
);
|
||||
|
||||
return { handleUpdateSegmentEase, handleUpdateKeyframeEase, handleSetAllKeyframeEases };
|
||||
}
|
||||
@@ -66,4 +66,25 @@ describe("KeyframeDiamondContextMenu", () => {
|
||||
expect(onDelete).toHaveBeenCalledWith("box", target);
|
||||
expect(onMoveToPlayhead).toHaveBeenCalledWith(element, target);
|
||||
});
|
||||
|
||||
// An arc waypoint on a two-anchor path cannot be dropped on its own, so the
|
||||
// caller withholds onDelete rather than offering an entry that does nothing.
|
||||
it("hides the single-node delete when no handler is given", () => {
|
||||
const host = document.createElement("div");
|
||||
document.body.appendChild(host);
|
||||
const root = createRoot(host);
|
||||
act(() =>
|
||||
root.render(
|
||||
<KeyframeDiamondContextMenu state={state} onClose={() => {}} onDeleteAll={vi.fn()} />,
|
||||
),
|
||||
);
|
||||
|
||||
const labels = Array.from(document.body.querySelectorAll("button")).map(
|
||||
(button) => button.textContent,
|
||||
);
|
||||
expect(labels).toEqual(["Delete All Keyframes"]);
|
||||
|
||||
act(() => root.unmount());
|
||||
host.remove();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -19,7 +19,10 @@ export interface KeyframeDiamondContextMenuState {
|
||||
interface KeyframeDiamondContextMenuProps {
|
||||
state: KeyframeDiamondContextMenuState;
|
||||
onClose: () => void;
|
||||
onDelete: (elementId: string, keyframe: TimelineKeyframeTarget) => void;
|
||||
/** Omitted where this node cannot be deleted on its own (see the arc-waypoint
|
||||
* floor in removeMotionPathPointInScript): an entry that silently no-ops is
|
||||
* worse than no entry. */
|
||||
onDelete?: (elementId: string, keyframe: TimelineKeyframeTarget) => void;
|
||||
onDeleteAll: (element: TimelineElement) => void;
|
||||
/** Retime the keyframe to the current playhead, preserving its value + ease. */
|
||||
onMoveToPlayhead?: (element: TimelineElement, keyframe: TimelineKeyframeTarget) => void;
|
||||
@@ -43,7 +46,9 @@ export const KeyframeDiamondContextMenu = memo(function KeyframeDiamondContextMe
|
||||
};
|
||||
|
||||
const menuWidth = 200;
|
||||
const menuHeight = onMoveToPlayhead ? 100 : 70;
|
||||
// Measured off the rendered rows, so the flip-up test below stays right as
|
||||
// optional entries drop out.
|
||||
const menuHeight = 10 + (1 + (onMoveToPlayhead ? 1 : 0) + (onDelete ? 1 : 0)) * 30;
|
||||
const overflowY = state.y + menuHeight - window.innerHeight;
|
||||
const adjustedX = state.x + menuWidth > window.innerWidth ? state.x - menuWidth : state.x;
|
||||
const adjustedY = overflowY > 0 ? state.y - overflowY - 8 : state.y;
|
||||
@@ -71,16 +76,18 @@ export const KeyframeDiamondContextMenu = memo(function KeyframeDiamondContextMe
|
||||
)}
|
||||
|
||||
{/* Delete */}
|
||||
<button
|
||||
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, keyframe);
|
||||
onClose();
|
||||
}}
|
||||
>
|
||||
Delete Keyframe
|
||||
</button>
|
||||
{onDelete && (
|
||||
<button
|
||||
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, keyframe);
|
||||
onClose();
|
||||
}}
|
||||
>
|
||||
Delete Keyframe
|
||||
</button>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -686,12 +686,12 @@ describe("TimelineClipDiamonds", () => {
|
||||
return { host, root };
|
||||
};
|
||||
|
||||
it("hides the inline ease button on a colliding merged segment", () => {
|
||||
// The 50->100 segment ends on a keyframe shared by two animations, so one
|
||||
// button cannot honestly stand for the several curves that meet there. Only
|
||||
// the unambiguous 0->50 segment keeps its button.
|
||||
it("shows the inline ease button on a colliding merged segment (bulk edit)", () => {
|
||||
// Both segments (0->50, 50->100) render their ease button; the 50->100
|
||||
// segment ends on a keyframe shared by two animations and the button now
|
||||
// bulk-edits both rather than being hidden.
|
||||
const { host, root } = renderSegmentLane(true);
|
||||
expect(host.querySelectorAll("[data-keyframe-ease-segment]").length).toBe(1);
|
||||
expect(host.querySelectorAll("[data-keyframe-ease-segment]").length).toBe(2);
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
|
||||
@@ -90,13 +90,13 @@ export function TimelineDiamondConnectors({
|
||||
|
||||
/**
|
||||
* The ease control targets one segment, so it needs the keyframe's own
|
||||
* animationId/tweenPercentage. On a merged inline row it is hidden where two
|
||||
* source animations collide at this percentage (one button cannot honestly
|
||||
* stand for several curves) or the keyframe has no source animation id
|
||||
* (runtime-scanned) so there is no tween to target.
|
||||
* animationId. A merged keyframe now shows one too: the editor edits every
|
||||
* colliding tween together, so one button standing for several curves is
|
||||
* honest. Only a keyframe with no source animation id (runtime-scanned) is left
|
||||
* out, because there is no tween to target.
|
||||
*/
|
||||
function showsEaseControl(kf: TimelineDiamondKeyframe): boolean {
|
||||
return (kf.collidingAnimationTargets?.length ?? 0) <= 1 && kf.animationId !== undefined;
|
||||
return kf.animationId !== undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -221,6 +221,35 @@ describe("buildExpandedElements", () => {
|
||||
expect(child.key).toBe(expectedStoreKey);
|
||||
});
|
||||
|
||||
// Regression: a child row is built from a manifest clip, which carries none of
|
||||
// the host element's attributes. Reading hidden off the manifest left every
|
||||
// expanded row reporting itself visible, so the eye wrote data-hidden a second
|
||||
// time instead of removing it and the element could never be shown again.
|
||||
it("inherits hidden and locked state from the flat store element", () => {
|
||||
const elements = [
|
||||
el({ id: "s1", domId: "s1", start: 0, duration: 14 }),
|
||||
el({
|
||||
id: "eyebrow",
|
||||
key: "index.html#eyebrow",
|
||||
domId: "eyebrow",
|
||||
start: 0,
|
||||
duration: 14,
|
||||
hidden: true,
|
||||
timelineLocked: true,
|
||||
}),
|
||||
];
|
||||
const manifest = [
|
||||
clip({ id: "s1", start: 0, duration: 14 }),
|
||||
clip({ id: "eyebrow", start: 0, duration: 14 }),
|
||||
];
|
||||
const parentMap = new Map([["eyebrow", "s1"]]);
|
||||
|
||||
const out = buildExpandedElements(elements, manifest, parentMap, "s1", "s1");
|
||||
const child = out.find((e) => e.domId === "eyebrow")!;
|
||||
expect(child.hidden).toBe(true);
|
||||
expect(child.timelineLocked).toBe(true);
|
||||
});
|
||||
|
||||
// Sub-comp internals (group + pills) have no data-start, so they're not in the
|
||||
// manifest. They arrive as DOM children and must still expand under their host.
|
||||
it("expands DOM-only sub-comp children (no manifest clip) under the host", () => {
|
||||
|
||||
@@ -134,6 +134,27 @@ interface DisplayBounds {
|
||||
track: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* State that lives on the live host element, not in the clip manifest:
|
||||
* `data-hidden`, `data-timeline-locked`, `data-timeline-role`. A child row is
|
||||
* built from a manifest clip with no hostEl to read, so
|
||||
* createTimelineElementFromManifestClip cannot see any of it. The flat store
|
||||
* element for the same child WAS built with one, so it is inherited from there.
|
||||
*
|
||||
* Without this the eye on an expanded child always reported the row visible, so
|
||||
* clicking it wrote data-hidden again instead of removing it, and a hidden child
|
||||
* could never be shown again (not even after a reload, since the attribute is in
|
||||
* the source).
|
||||
*/
|
||||
function hostElementState(flat: TimelineElement | undefined): Partial<TimelineElement> {
|
||||
if (!flat) return {};
|
||||
return {
|
||||
hidden: flat.hidden,
|
||||
timelineLocked: flat.timelineLocked,
|
||||
timelineRole: flat.timelineRole,
|
||||
};
|
||||
}
|
||||
|
||||
// `display` bounds come from the top-level scene clip (where the expanded row is
|
||||
// drawn). `editBasis` comes from the child's immediate sub-comp host: its absolute
|
||||
// start anchors local-time edits and its compositionSrc is the file edits write to.
|
||||
@@ -143,6 +164,7 @@ function buildChildElements(
|
||||
display: DisplayBounds,
|
||||
editBasis: { start: number; sourceFile: string | undefined },
|
||||
expandedHostKey: string,
|
||||
elements: readonly TimelineElement[],
|
||||
): TimelineElement[] {
|
||||
const result: TimelineElement[] = [];
|
||||
for (const child of siblings) {
|
||||
@@ -170,6 +192,7 @@ function buildChildElements(
|
||||
});
|
||||
result.push({
|
||||
...base,
|
||||
...hostElementState(elements.find((element) => element.key === key)),
|
||||
key,
|
||||
start: clamped.start,
|
||||
duration: clamped.duration,
|
||||
@@ -281,6 +304,7 @@ export function buildExpandedElements(
|
||||
},
|
||||
editBasis,
|
||||
parentKey,
|
||||
elements,
|
||||
);
|
||||
if (expanded.length === 0) return filterToTopLevel(elements, parentMap);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user