Skip to content
Merged
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
91 changes: 91 additions & 0 deletions packages/core/src/runtime/editing/restoreAttributes.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { parseRestoreAttributes, restoreAttributes } from "./restoreAttributes";

type TestWindow = Window & Record<string, unknown>;
const win = window as TestWindow;

function player() {
const calls: string[] = [];
win.__player = { seek: (t: number) => calls.push(`seek ${t}`), isPlaying: () => false };
win.__hfForceTimelineRebind = () => calls.push("rebind");
win.__hfStudioManualEditsApply = () => calls.push("manual");
return calls;
}

afterEach(() => {
document.body.innerHTML = "";
for (const name of ["__player", "__hfForceTimelineRebind", "__hfStudioManualEditsApply"])
delete win[name];
});

const moved = '<div data-hf-id="box" class="card" style="left: 90px"></div>';
const restore = (key: string, attributes: [string, string][], file: string | null = null) => ({
scopes: [{ file, elements: [{ key, attributes }] }],
scripted: false,
time: 1.5,
});

describe("restore-attributes", () => {
it("puts the restored attributes on the live element and rebinds at the playhead", () => {
document.body.innerHTML = moved;
const calls = player();
const params = restore("hf:box", [
["data-hf-id", "box"],
["style", "left: 0px"],
]);
expect(restoreAttributes(params)).toEqual({ applied: true });
const box = document.querySelector('[data-hf-id="box"]')!;
expect(box.getAttribute("style")).toBe("left: 0px");
expect(box.hasAttribute("class")).toBe(false);
expect(calls).toEqual(["seek 1.5", "rebind", "manual"]);
});

it("restores each copy of an inlined sub-composition", () => {
document.body.innerHTML = [1, 2]
.map((n) => `<section data-composition-file="sub.html" id="host${n}">${moved}</section>`)
.join("");
player();
const params = restore("hf:box", [["data-hf-id", "box"]], "sub.html");
expect(restoreAttributes(params)).toEqual({ applied: true });
expect(document.querySelectorAll("[style]")).toHaveLength(0);
});

it("changes nothing when an element is missing, shared by two, or GSAP-parsed under a script", () => {
const attributes: [string, string][] = [["data-hf-id", "box"]];
const refused = (html: string, params = restore("hf:box", attributes)) => {
document.body.innerHTML = html;
player();
const before = document.body.innerHTML;
expect(restoreAttributes(params)).toEqual({ applied: false });
expect(document.body.innerHTML).toBe(before);
};
refused('<div data-hf-id="other"></div>');
refused(moved + moved);
refused(moved, restore("hf:box", attributes, "missing.html"));
document.body.innerHTML = moved;
Object.assign(document.querySelector("div")!, { _gsap: {} });
const rebind = vi.fn();
player();
win.__hfForceTimelineRebind = rebind;
expect(restoreAttributes({ ...restore("hf:box", attributes), scripted: true })).toEqual({
applied: false,
});
expect(rebind).not.toHaveBeenCalled();
});

it("accepts only bounded, well-formed params", () => {
const ok = restore("hf:box", [["style", "left: 0"]]);
expect(parseRestoreAttributes(ok)).toEqual(ok);
for (const bad of [
{ ...ok, time: -1 },
{ ...ok, extra: 1 },
{ ...ok, scopes: [] },
restore("box", [["style", "x"]]),
restore("hf:box", [["on click", "x"]]),
restore("hf:box", [["style", 1 as unknown as string]]),
restore("hf:box", [], ""),
{ ...ok, scopes: [{ file: null, elements: Array(2_001).fill(ok.scopes[0]!.elements[0]) }] },
])
expect(parseRestoreAttributes(bad)).toBeNull();
});
});
163 changes: 163 additions & 0 deletions packages/core/src/runtime/editing/restoreAttributes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
// `restore-attributes`: an undo or redo that only changes identified elements' attributes, applied in place.
// The parent diffs the saved files and sends each changed element's full restored attribute set.

/** `hf:<data-hf-id>` or `id:<id>`, the key the parent's restore diff uses. */
export type RestoreElementKey = string;
export type RestoreAttribute = [name: string, value: string];
export type RestoreScope = {
/** null: the active document, which is the whole preview; else a sub-composition file the preview inlines. */
file: string | null;
elements: { key: RestoreElementKey; attributes: RestoreAttribute[] }[];
};
/** `scripted`: the files keep an unchanged GSAP script, so an element GSAP has parsed needs a re-run instead. */
export type RestoreAttributesParams = { scopes: RestoreScope[]; scripted: boolean; time: number };

const MAX_SCOPES = 64;
const MAX_ELEMENTS = 2_000;
const MAX_ATTRIBUTES = 256;
const MAX_KEY_LENGTH = 512;
const MAX_VALUE_LENGTH = 200_000;
const ATTRIBUTE_NAME = /^[^\s"'>/=]{1,256}$/;
const IDENTITY_SELECTOR = "[id], [data-hf-id]";

const isRecord = (value: unknown): value is Record<string, unknown> =>
Object.prototype.toString.call(value) === "[object Object]";
const keysAre = (value: Record<string, unknown>, keys: string) =>
Object.keys(value).sort().join() === keys;

function attribute(value: unknown): RestoreAttribute | null {
if (!Array.isArray(value) || value.length !== 2) return null;
const [name, text] = value;
return typeof name === "string" &&
ATTRIBUTE_NAME.test(name) &&
typeof text === "string" &&
text.length <= MAX_VALUE_LENGTH
? [name, text]
: null;
}

function element(value: unknown): RestoreScope["elements"][number] | null {
if (!isRecord(value) || !keysAre(value, "attributes,key")) return null;
const { key, attributes } = value;
if (typeof key !== "string" || key.length > MAX_KEY_LENGTH || !/^(hf|id):./.test(key))
return null;
if (!Array.isArray(attributes) || attributes.length > MAX_ATTRIBUTES) return null;
const parsed = attributes.map(attribute);
return parsed.every(Boolean) ? { key, attributes: parsed as RestoreAttribute[] } : null;
}

const isScopeFile = (file: unknown): file is string | null =>
file === null || (typeof file === "string" && file.length > 0 && file.length <= MAX_KEY_LENGTH);

function scope(value: unknown): RestoreScope | null {
if (!isRecord(value) || !keysAre(value, "elements,file")) return null;
const { file, elements } = value;
if (!isScopeFile(file) || !Array.isArray(elements) || !elements.length) return null;
const parsed = elements.map(element);
return parsed.every(Boolean) ? { file, elements: parsed as RestoreScope["elements"] } : null;
}

export function parseRestoreAttributes(params: unknown): RestoreAttributesParams | null {
if (!isRecord(params) || !keysAre(params, "scopes,scripted,time")) return null;
const { scopes, scripted, time } = params;
if (typeof scripted !== "boolean") return null;
if (typeof time !== "number" || !Number.isFinite(time) || time < 0) return null;
if (!Array.isArray(scopes) || !scopes.length || scopes.length > MAX_SCOPES) return null;
const parsed = scopes.map(scope);
if (!parsed.every(Boolean)) return null;
const count = (parsed as RestoreScope[]).reduce((n, s) => n + s.elements.length, 0);
return count <= MAX_ELEMENTS ? { scopes: parsed as RestoreScope[], scripted, time } : null;
}

function identityKey(el: Element): RestoreElementKey | null {
const hfId = el.getAttribute("data-hf-id");
if (hfId) return `hf:${hfId}`;
const id = el.getAttribute("id");
return id ? `id:${id}` : null;
}

/** Every identified element under `root` by key, or null when two share one. */
function identityMap(root: ParentNode): Map<RestoreElementKey, Element> | null {
const map = new Map<RestoreElementKey, Element>();
for (const el of root.querySelectorAll(IDENTITY_SELECTOR)) {
const key = identityKey(el);
if (!key) continue;
if (map.has(key)) return null;
map.set(key, el);
}
return map;
}

// The active document is the whole preview; a sub-composition lives in each host that inlines it.
function scopeRoots(file: string | null): ParentNode[] {
if (file === null) return [document];
return Array.from(document.querySelectorAll("[data-composition-file]")).filter(
(host) => host.getAttribute("data-composition-file") === file,
);
}

type RestorePlan = [Element, RestoreAttribute[]][];

/** Adds `root`'s live elements to `plan`; false when any is missing or not the file's own. */
function planRoot(
root: ParentNode,
elements: RestoreScope["elements"],
plan: RestorePlan,
): boolean {
const live = identityMap(root);
if (!live) return false;
for (const { key, attributes } of elements) {
const el = live.get(key);
// The preview rewrites a sub-composition's own root, so its attributes are not the file's.
if (!el || el.hasAttribute("data-hf-inner-root")) return false;
plan.push([el, attributes]);
}
return true;
}

/** Each live element with the attributes it takes, or null when any is missing or not the file's own. */
function planRestore(scopes: RestoreScope[]): RestorePlan | null {
const plan: RestorePlan = [];
for (const { file, elements } of scopes) {
const roots = scopeRoots(file);
if (!roots.length || !roots.every((root) => planRoot(root, elements, plan))) return null;
}
return plan;
}

type RestoreWindow = Window & {
__player?: { seek?: (t: number) => void; isPlaying?: () => boolean; play?: () => void };
__hfForceTimelineRebind?: () => void;
__hfStudioManualEditsApply?: () => void;
__hfSuppressSceneMutations?: <T>(fn: () => T) => T;
};

/** Rebinds the timeline to the live attributes at `time`, as an in-place soft reload does, without running scripts. */
function rebindAt(win: RestoreWindow, time: number): void {
const finalize = () => {
const wasPlaying = win.__player?.isPlaying?.() === true;
win.__player?.seek?.(time);
win.__hfForceTimelineRebind?.();
win.__hfStudioManualEditsApply?.();
if (wasPlaying) win.__player?.play?.();
};
if (win.__hfSuppressSceneMutations) win.__hfSuppressSceneMutations(finalize);
else finalize();
}

/** Applies the restore in place; `applied: false` changes nothing, and the parent reloads instead. */
export function restoreAttributes({ scopes, scripted, time }: RestoreAttributesParams): {
applied: boolean;
} {
const win = window as RestoreWindow;
const plan = planRestore(scopes);
if (!plan || typeof win.__player?.seek !== "function") return { applied: false };
if (scripted && plan.some(([el]) => "_gsap" in el)) return { applied: false };
for (const [el, attributes] of plan) {
const keep = new Set(attributes.map(([name]) => name));
for (const name of el.getAttributeNames()) if (!keep.has(name)) el.removeAttribute(name);
for (const [name, value] of attributes) el.setAttribute(name, value);
}
rebindAt(win, time);
return { applied: true };
}
1 change: 1 addition & 0 deletions packages/core/src/runtime/editingAgent.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ describe("installEditingAgent", () => {
"gesture-start",
"console-errors",
"watch-keys",
"restore-attributes",
],
},
});
Expand Down
2 changes: 2 additions & 0 deletions packages/core/src/runtime/editingAgent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import { elementGeometry } from "./editingGeometry";
import { pointerTargetsAt } from "./editingTargets";
import { layersOf } from "./editingLayers";
import { drawDrafts } from "./editingDraft";
import { restoreAttributes } from "./editing/restoreAttributes";
import { gestureStart } from "./editingGestureStart";
import {
getLogicalOpacity,
Expand Down Expand Up @@ -188,6 +189,7 @@ const HANDLERS: Handlers = {
return { errors, truncated: from + errors.length < seen.length };
},
"watch-keys": ({ combos }, port) => watchKeys(port, combos),
"restore-attributes": (params) => restoreAttributes(params),
};

function serve(port: MessagePort): void {
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/runtime/editingPort.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ describe("createEditingPortClient", () => {
"gesture-start",
"console-errors",
"watch-keys",
"restore-attributes",
],
});
} finally {
Expand Down
4 changes: 4 additions & 0 deletions packages/core/src/runtime/editingPort.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
* otherwise takes straight off the frame's window, which an opaque-origin
* preview does not allow.
*/
import { parseRestoreAttributes, type RestoreAttributesParams } from "./editing/restoreAttributes";
import {
EDITING_ELEMENT_HANDLE,
MAX_DESCRIBE_HANDLES,
Expand Down Expand Up @@ -109,6 +110,7 @@ export const EDITING_REQUEST_KINDS = [
"gesture-start",
"console-errors",
"watch-keys",
"restore-attributes",
] as const;
export type EditingRequestKind = (typeof EDITING_REQUEST_KINDS)[number];

Expand Down Expand Up @@ -217,6 +219,7 @@ export interface EditingRequests {
/** The frame cancels these combos outside the elements that own keys, and forwards them and their
* keyups to this port; an empty list stops. */
"watch-keys": { params: { combos: string[] }; result: { watching: number } };
"restore-attributes": { params: RestoreAttributesParams; result: { applied: boolean } };
}
export type EditingParams<K extends EditingRequestKind> = EditingRequests[K]["params"];
export type EditingResult<K extends EditingRequestKind> = EditingRequests[K]["result"];
Expand Down Expand Up @@ -403,6 +406,7 @@ const PARAM_PARSERS: {
"console-errors": (params) =>
hasKeys(params, "from") && isOffset(params.from) ? { from: params.from } : null,
"watch-keys": comboList,
"restore-attributes": parseRestoreAttributes,
};

/** Validates one request off the wire. Never throws: anything unusable becomes a typed error. */
Expand Down
73 changes: 73 additions & 0 deletions packages/studio/src/utils/gsapUndoRestore.sealed.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
// @vitest-environment happy-dom

import { beforeEach, describe, expect, it, vi } from "vitest";

const channel = vi.hoisted(() => ({ request: vi.fn() }));
vi.mock("../player/lib/previewChannel", () => ({
previewFrameOpaque: () => true,
previewRequest: channel.request,
}));
import { applyUndoRestoreToPreview } from "./gsapUndoRestore";

const page = (body: string) => `<html><body>${body}</body></html>`;
const box = (left: number) => `<div data-hf-id="box" style="left: ${left}px">t</div>`;
const script = (text: string) => `<script>gsap.timeline().to("#t", ${text});</script>`;

function undo(previous: string, restored: string) {
const reload = vi.fn();
const iframe = document.createElement("iframe");
const files = { "index.html": { previous: page(previous), restored: page(restored) } };
return { reload, strategy: applyUndoRestoreToPreview(iframe, null, files, 2, reload), iframe };
}

const settled = () => new Promise((resolve) => setTimeout(resolve, 0));

beforeEach(() => channel.request.mockReset());

describe("undo on a sealed preview", () => {
it("sends the restored attributes to the frame instead of reloading", async () => {
channel.request.mockResolvedValue({ applied: true });
const { reload, strategy, iframe } = undo(box(90), box(0));
expect(strategy).toBe("soft");
expect(channel.request).toHaveBeenCalledWith(iframe, "restore-attributes", {
scopes: [
{
file: null,
elements: [
{
key: "hf:box",
attributes: [
["data-hf-id", "box"],
["style", "left: 0px"],
],
},
],
},
],
scripted: false,
time: 2,
});
await settled();
expect(reload).not.toHaveBeenCalled();
});

it("reloads when the frame refuses or does not answer", async () => {
for (const reply of [{ applied: false }, null]) {
channel.request.mockResolvedValue(reply);
const { reload } = undo(box(90), box(0));
await settled();
expect(reload).toHaveBeenCalledOnce();
}
});

it("says the files keep a GSAP script, and reloads at once when the script itself changed", () => {
channel.request.mockResolvedValue({ applied: true });
undo(box(90) + script("{ x: 1 }"), box(0) + script("{ x: 1 }"));
expect(channel.request.mock.calls[0]![2]).toMatchObject({ scripted: true });
channel.request.mockReset();
const { reload, strategy } = undo(box(90) + script("{ x: 1 }"), box(0) + script("{ x: 2 }"));
expect(strategy).toBe("full");
expect(reload).toHaveBeenCalledOnce();
expect(channel.request).not.toHaveBeenCalled();
});
});
Loading
Loading