Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
125 changes: 125 additions & 0 deletions packages/studio/src/hooks/useStudioTestHooks.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
// @vitest-environment happy-dom
import { act } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, describe, expect, it, vi } from "vitest";
import { usePlayerStore } from "../player/store/playerStore";
import {
createTimelinePerformanceFixture,
type TimelinePerformanceFixtureProfile,
} from "../player/lib/timelinePerformanceFixture";
import { useStudioTestHooks } from "./useStudioTestHooks";

Reflect.set(globalThis, "IS_REACT_ACT_ENVIRONMENT", true);

const PROFILES: readonly TimelinePerformanceFixtureProfile[] = [
"dense-short",
"long-overlap",
"keyframe-heavy-expanded",
"composition-heavy",
"remote-unsupported",
];

function Probe(): null {
useStudioTestHooks({
previewIframeRef: { current: null },
buildDomSelectionFromTarget: vi.fn(),
applyDomSelection: vi.fn(),
});
return null;
}

describe("timeline performance fixture", () => {
afterEach(() => {
window.__studioTest = undefined;
usePlayerStore.getState().reset();
});

it("generates stable 50k identities, counts, distribution, and duration", () => {
const first = createTimelinePerformanceFixture({
elementCount: 50_000,
profile: "dense-short",
});
const second = createTimelinePerformanceFixture({
elementCount: 50_000,
profile: "dense-short",
});

expect(first.summary).toEqual(second.summary);
expect(first.summary).toEqual({
elementCount: 50_000,
profile: "dense-short",
duration: 120,
trackCount: 1_000,
keyframedElementCount: 0,
expandedElementCount: 0,
});
expect(new Set(first.elements.map((element) => element.track)).size).toBe(1_000);
const perTrack = new Map<number, number>();
for (const element of first.elements) {
perTrack.set(element.track, (perTrack.get(element.track) ?? 0) + 1);
}
expect(Math.max(...perTrack.values())).toBeLessThanOrEqual(128);
expect(first.elements.slice(0, 3)).toEqual(second.elements.slice(0, 3));
expect(first.elements.at(-1)).toEqual(second.elements.at(-1));
});

it.each(PROFILES)("builds the %s 1k scale profile", (profile) => {
const fixture = createTimelinePerformanceFixture({ elementCount: 1_000, profile });
expect(fixture.elements).toHaveLength(1_000);
expect(fixture.summary.elementCount).toBe(1_000);
expect(fixture.summary.duration).toBeGreaterThan(0);
expect(new Set(fixture.elements.map((element) => element.key)).size).toBe(1_000);
if (profile === "keyframe-heavy-expanded") {
expect(fixture.keyframeCache.size).toBe(1_000);
expect(fixture.gsapAnimations.size).toBe(1_000);
expect(fixture.expandedClipIds.size).toBe(1_000);
}
});

it("publishes one dev-only loader that replaces fixture state atomically", () => {
const host = document.createElement("div");
const root = createRoot(host);
act(() => root.render(<Probe />));
const api = window.__studioTest;
expect(api).toBeDefined();
if (!api) throw new Error("Expected dev Studio test API");
let notifications = 0;
const unsubscribe = usePlayerStore.subscribe(() => {
notifications += 1;
});

const summary = api.loadTimelinePerformanceFixture({
elementCount: 1_000,
profile: "keyframe-heavy-expanded",
});

expect(summary.elementCount).toBe(1_000);
expect(notifications).toBe(1);
expect(usePlayerStore.getState()).toMatchObject({
duration: 600,
timelineReady: true,
});
expect(usePlayerStore.getState().elements).toHaveLength(1_000);
expect(usePlayerStore.getState().expandedClipIds.size).toBe(1_000);
unsubscribe();
act(() => root.unmount());
expect(window.__studioTest).toBeUndefined();
});

it("does not mutate state when the fixture request is invalid", () => {
const host = document.createElement("div");
const root = createRoot(host);
act(() => root.render(<Probe />));
const api = window.__studioTest;
if (!api) throw new Error("Expected dev Studio test API");
const before = usePlayerStore.getState().elements;

expect(() =>
Reflect.apply(api.loadTimelinePerformanceFixture, api, [
{ elementCount: 999, profile: "dense-short" },
]),
).toThrow("elementCount must be 1000 or 50000");
expect(usePlayerStore.getState().elements).toBe(before);
act(() => root.unmount());
});
});
36 changes: 36 additions & 0 deletions packages/studio/src/hooks/useStudioTestHooks.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
import { useEffect } from "react";
import type { DomEditSelection } from "../components/editor/domEditing";
import { usePlayerStore } from "../player/store/playerStore";
import {
readTimelinePerformanceDiagnostics,
type TimelinePerformanceDiagnostics,
} from "../player/lib/timelinePerformanceDiagnostics";
import {
createTimelinePerformanceFixture,
type TimelinePerformanceFixtureSpec,
type TimelinePerformanceFixtureSummary,
} from "../player/lib/timelinePerformanceFixture";
import { TIMELINE_VIEWPORT_BUDGETS } from "../player/lib/timelineViewportBudgets";

interface StudioTestHookDeps {
previewIframeRef: React.MutableRefObject<HTMLIFrameElement | null>;
Expand All @@ -12,6 +23,11 @@ interface StudioTestHookDeps {

interface StudioTestApi {
selectByDomId: (id: string) => Promise<boolean>;
loadTimelinePerformanceFixture: (
spec: TimelinePerformanceFixtureSpec,
) => TimelinePerformanceFixtureSummary;
readTimelinePerformanceDiagnostics: () => Readonly<TimelinePerformanceDiagnostics>;
timelineViewportBudgets: typeof TIMELINE_VIEWPORT_BUDGETS;
}

declare global {
Expand Down Expand Up @@ -52,6 +68,26 @@ export function useStudioTestHooks({
applyDomSelection(selection, { revealPanel: true });
return true;
},
loadTimelinePerformanceFixture: (spec) => {
const fixture = createTimelinePerformanceFixture(spec);
usePlayerStore.setState({
currentTime: 0,
duration: fixture.summary.duration,
timelineReady: true,
zoomMode: "manual",
manualZoomPercent: 2_000,
elements: fixture.elements,
selectedElementId: null,
selectedElementIds: new Set(),
selectedKeyframes: new Set(),
keyframeCache: fixture.keyframeCache,
gsapAnimations: fixture.gsapAnimations,
expandedClipIds: fixture.expandedClipIds,
});
return fixture.summary;
},
readTimelinePerformanceDiagnostics: () => readTimelinePerformanceDiagnostics(),
timelineViewportBudgets: TIMELINE_VIEWPORT_BUDGETS,
};
window.__studioTest = api;
return () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
// @vitest-environment happy-dom
import { afterEach, describe, expect, it } from "vitest";
import {
getTimelineResourceBudgetStatus,
readTimelinePerformanceDiagnostics,
resolveTimelineScrollStrategy,
} from "./timelinePerformanceDiagnostics";
import { resolveTimelineViewportBudgets } from "./timelineViewportBudgets";

describe("timeline performance diagnostics", () => {
afterEach(() => {
document.body.replaceChildren();
});

it("reads mounted resources without mutating the timeline", () => {
document.body.innerHTML = `
<div aria-label="Timeline" data-timeline-scheduler-queued="3"
data-timeline-scheduler-active="2" data-timeline-cache-bytes="4096">
<div data-timeline-row><div data-clip="true"></div><div data-clip="true"></div></div>
<div data-timeline-row><div data-clip="true"></div></div>
<div data-timeline-grid-cell></div><div data-timeline-grid-cell></div>
<div data-timeline-poster-state="ready"></div>
<div data-timeline-poster-state="error"></div>
</div>`;
const before = document.body.innerHTML;

expect(readTimelinePerformanceDiagnostics()).toMatchObject({
timelineRoots: 1,
mountedRows: 2,
mountedClipRoots: 3,
maxMountedClipRootsInOneRow: 2,
mountedTimeGridCells: 2,
schedulerQueued: 3,
schedulerActive: 2,
cacheBytes: 4096,
posterStates: { idle: 0, loading: 0, ready: 1, fallback: 0, error: 1 },
});
expect(document.body.innerHTML).toBe(before);
});

it("returns the zero baseline after unmount or reset removes the DOM", () => {
document.body.innerHTML = '<div aria-label="Timeline"><div data-clip="true"></div></div>';
expect(readTimelinePerformanceDiagnostics().mountedClipRoots).toBe(1);

document.body.replaceChildren();

expect(readTimelinePerformanceDiagnostics()).toEqual({
timelineRoots: 0,
mountedRows: 0,
mountedClipRoots: 0,
maxMountedClipRootsInOneRow: 0,
mountedTimeGridCells: 0,
mountedTimelineDescendants: 0,
schedulerQueued: 0,
schedulerActive: 0,
cacheBytes: 0,
posterStates: { idle: 0, loading: 0, ready: 0, fallback: 0, error: 0 },
});
});

it("checks the DOM ceilings including the strict descendant boundary", () => {
const budgets = resolveTimelineViewportBudgets({
maxMountedClipRoots: 2,
maxMountedClipRootsPerRow: 1,
maxMountedTimelineDescendants: 4,
});
expect(
getTimelineResourceBudgetStatus(
{
...readTimelinePerformanceDiagnostics(),
mountedClipRoots: 2,
maxMountedClipRootsInOneRow: 2,
mountedTimelineDescendants: 4,
},
budgets,
),
).toEqual({ clipRoots: true, clipRootsPerRow: false, descendants: false });
});

it("selects direct scrolling only through the configured safety envelope", () => {
expect(resolveTimelineScrollStrategy(8_000_000)).toBe("direct");
expect(resolveTimelineScrollStrategy(8_000_001)).toBe("segmented");
expect(() => resolveTimelineScrollStrategy(Number.NaN)).toThrow("content width");
});
});
115 changes: 115 additions & 0 deletions packages/studio/src/player/lib/timelinePerformanceDiagnostics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import { TIMELINE_VIEWPORT_BUDGETS, type TimelineViewportBudgets } from "./timelineViewportBudgets";

export type TimelinePosterState = "idle" | "loading" | "ready" | "fallback" | "error";

export interface TimelinePerformanceDiagnostics {
timelineRoots: number;
mountedRows: number;
mountedClipRoots: number;
maxMountedClipRootsInOneRow: number;
mountedTimeGridCells: number;
mountedTimelineDescendants: number;
schedulerQueued: number;
schedulerActive: number;
cacheBytes: number;
posterStates: Readonly<Record<TimelinePosterState, number>>;
}

export interface TimelineResourceBudgetStatus {
clipRoots: boolean;
clipRootsPerRow: boolean;
descendants: boolean;
}

function readNonNegativeNumber(value: string | undefined): number {
const number = Number(value);
return Number.isFinite(number) && number >= 0 ? number : 0;
}

function countPosters(root: ParentNode): Readonly<Record<TimelinePosterState, number>> {
const counts: Record<TimelinePosterState, number> = {
idle: 0,
loading: 0,
ready: 0,
fallback: 0,
error: 0,
};
for (const node of root.querySelectorAll<HTMLElement>("[data-timeline-poster-state]")) {
const state = node.dataset.timelinePosterState;
if (state && state in counts) counts[state as TimelinePosterState] += 1;
}
return Object.freeze(counts);
}

function maxClipsInOneRow(root: ParentNode): number {
const byRow = new Map<Element | null, number>();
for (const clip of root.querySelectorAll<HTMLElement>('[data-clip="true"]')) {
const row = clip.closest("[data-timeline-row]");
byRow.set(row, (byRow.get(row) ?? 0) + 1);
}
return Math.max(0, ...byRow.values());
}

function sumDataAttribute(root: ParentNode, selector: string, dataKey: string): number {
let total = 0;
for (const node of root.querySelectorAll<HTMLElement>(selector)) {
total += readNonNegativeNumber(node.dataset[dataKey]);
}
return total;
}

/**
* Read current timeline costs directly from the mounted DOM. No counters are
* retained, so an unmount or project reset is reflected as a zero baseline on
* the next read rather than depending on cleanup ordering.
*/
export function readTimelinePerformanceDiagnostics(
root: ParentNode = document,
): Readonly<TimelinePerformanceDiagnostics> {
const timelineRoots = root.querySelectorAll<HTMLElement>('[aria-label="Timeline"]');
let mountedTimelineDescendants = 0;
for (const timelineRoot of timelineRoots) {
mountedTimelineDescendants += timelineRoot.querySelectorAll("*").length;
}
return Object.freeze({
timelineRoots: timelineRoots.length,
mountedRows: root.querySelectorAll("[data-timeline-row]").length,
mountedClipRoots: root.querySelectorAll('[data-clip="true"]').length,
maxMountedClipRootsInOneRow: maxClipsInOneRow(root),
mountedTimeGridCells: root.querySelectorAll("[data-timeline-grid-cell]").length,
mountedTimelineDescendants,
schedulerQueued: sumDataAttribute(
root,
"[data-timeline-scheduler-queued]",
"timelineSchedulerQueued",
),
schedulerActive: sumDataAttribute(
root,
"[data-timeline-scheduler-active]",
"timelineSchedulerActive",
),
cacheBytes: sumDataAttribute(root, "[data-timeline-cache-bytes]", "timelineCacheBytes"),
posterStates: countPosters(root),
});
}

export function getTimelineResourceBudgetStatus(
diagnostics: TimelinePerformanceDiagnostics,
budgets: Readonly<TimelineViewportBudgets> = TIMELINE_VIEWPORT_BUDGETS,
): Readonly<TimelineResourceBudgetStatus> {
return Object.freeze({
clipRoots: diagnostics.mountedClipRoots <= budgets.maxMountedClipRoots,
clipRootsPerRow: diagnostics.maxMountedClipRootsInOneRow <= budgets.maxMountedClipRootsPerRow,
descendants: diagnostics.mountedTimelineDescendants < budgets.maxMountedTimelineDescendants,
});
}

export function resolveTimelineScrollStrategy(
contentWidthPx: number,
budgets: Readonly<TimelineViewportBudgets> = TIMELINE_VIEWPORT_BUDGETS,
): "direct" | "segmented" {
if (!Number.isFinite(contentWidthPx) || contentWidthPx < 0) {
throw new RangeError("Timeline content width must be a finite non-negative number");
}
return contentWidthPx <= budgets.directScrollSafetyPx ? "direct" : "segmented";
}
Loading
Loading