diff --git a/packages/core/src/runtime/editing/restoreAttributes.test.ts b/packages/core/src/runtime/editing/restoreAttributes.test.ts new file mode 100644 index 0000000000..3e510f3b72 --- /dev/null +++ b/packages/core/src/runtime/editing/restoreAttributes.test.ts @@ -0,0 +1,91 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { parseRestoreAttributes, restoreAttributes } from "./restoreAttributes"; + +type TestWindow = Window & Record; +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 = '
'; +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) => `
${moved}
`) + .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('
'); + 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(); + }); +}); diff --git a/packages/core/src/runtime/editing/restoreAttributes.ts b/packages/core/src/runtime/editing/restoreAttributes.ts new file mode 100644 index 0000000000..542a11dfeb --- /dev/null +++ b/packages/core/src/runtime/editing/restoreAttributes.ts @@ -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:` or `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 => + Object.prototype.toString.call(value) === "[object Object]"; +const keysAre = (value: Record, 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 | null { + const map = new Map(); + 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?: (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 }; +} diff --git a/packages/core/src/runtime/editingAgent.test.ts b/packages/core/src/runtime/editingAgent.test.ts index 936382bec8..baef4a8eda 100644 --- a/packages/core/src/runtime/editingAgent.test.ts +++ b/packages/core/src/runtime/editingAgent.test.ts @@ -169,6 +169,7 @@ describe("installEditingAgent", () => { "gesture-start", "console-errors", "watch-keys", + "restore-attributes", ], }, }); diff --git a/packages/core/src/runtime/editingAgent.ts b/packages/core/src/runtime/editingAgent.ts index 851d774f0e..69da49f23b 100644 --- a/packages/core/src/runtime/editingAgent.ts +++ b/packages/core/src/runtime/editingAgent.ts @@ -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, @@ -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 { diff --git a/packages/core/src/runtime/editingPort.test.ts b/packages/core/src/runtime/editingPort.test.ts index cba273ceb9..1fef9c46b1 100644 --- a/packages/core/src/runtime/editingPort.test.ts +++ b/packages/core/src/runtime/editingPort.test.ts @@ -77,6 +77,7 @@ describe("createEditingPortClient", () => { "gesture-start", "console-errors", "watch-keys", + "restore-attributes", ], }); } finally { diff --git a/packages/core/src/runtime/editingPort.ts b/packages/core/src/runtime/editingPort.ts index 0206f79b70..59cbcba70f 100644 --- a/packages/core/src/runtime/editingPort.ts +++ b/packages/core/src/runtime/editingPort.ts @@ -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, @@ -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]; @@ -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 = EditingRequests[K]["params"]; export type EditingResult = EditingRequests[K]["result"]; @@ -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. */ diff --git a/packages/studio/src/utils/gsapUndoRestore.sealed.test.ts b/packages/studio/src/utils/gsapUndoRestore.sealed.test.ts new file mode 100644 index 0000000000..eadd4f8554 --- /dev/null +++ b/packages/studio/src/utils/gsapUndoRestore.sealed.test.ts @@ -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) => `${body}`; +const box = (left: number) => `
t
`; +const script = (text: string) => ``; + +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(); + }); +}); diff --git a/packages/studio/src/utils/gsapUndoRestore.ts b/packages/studio/src/utils/gsapUndoRestore.ts index 8bf8d087d2..6a7d8e1f95 100644 --- a/packages/studio/src/utils/gsapUndoRestore.ts +++ b/packages/studio/src/utils/gsapUndoRestore.ts @@ -15,6 +15,8 @@ import { ensureHfIds, isCompositionTemplate } from "@hyperframes/parsers/hf-ids" import { findAuthoredElement, parseSavedSource } from "./authoredSource"; import { STUDIO_EDIT_ATTRS } from "../components/editor/manualEditsSeekReapply"; import { markScenesStale } from "../player/sceneSwap"; +import { previewFrameOpaque, previewRequest } from "../player/lib/previewChannel"; +import type { EditingParams } from "@hyperframes/core/runtime/editing-port"; import { STUDIO_ORIGINAL_INLINE_TRANSLATE_ATTR } from "../components/editor/manualEditsTypes"; import { countStudioPreviewChange, studioGestureDraws } from "../components/editor/manualEditsDom"; @@ -356,6 +358,68 @@ function repaintWhileReloading(win: PreviewWindow, doc: Document, restored?: str ); } +type SealedRestore = Omit, "time">; + +const restoredAttributes = (el: Element): [string, string][] => + el.getAttributeNames().map((name) => [name, el.getAttribute(name) ?? ""]); + +// The preview server stamps data-hf-id on every page it serves. +const stamped = (html: string) => (html.includes("data-hf-id") ? html : ensureHfIds(html)); + +type SealedFile = { scripted: boolean; elements: SealedRestore["scopes"][number]["elements"] }; + +/** One file's changed elements with their restored attributes, or null when it needs a reload. */ +function sealedFile(file: UndoRestoreFile, isActive: boolean): SealedFile | null { + // A changed script is re-run in the frame, which a sealed preview cannot be asked to do yet. + if (extractGsapScriptText(file.restored) !== extractGsapScriptText(file.previous)) return null; + const prevDoc = parseRestoreSource(stamped(file.previous)); + const nextDoc = parseRestoreSource(stamped(file.restored)); + const scripted = restoreScripted(prevDoc, nextDoc, isActive); + const keys = diffRestoreDocs(prevDoc, nextDoc); + const restoredByKey = identityElementMap(nextDoc); + if (scripted === null || !keys || !restoredByKey) return null; + const elements = keys.map((key) => ({ + key, + attributes: restoredAttributes(restoredByKey.get(key)!), + })); + return { scripted, elements }; +} + +/** A sealed preview's in-place restore from the files alone, or null when it needs a reload. */ +function sealedRestore(activeDocPath: string, files: RestoreFiles): SealedRestore | null { + const restore: SealedRestore = { scopes: [], scripted: false }; + for (const [path, file] of Object.entries(files)) { + const isActive = path === activeDocPath; + const found = sealedFile(file, isActive); + if (!found) return null; + restore.scripted ||= found.scripted; + if (found.elements.length) + restore.scopes.push({ file: isActive ? null : path, elements: found.elements }); + } + return restore.scopes.length ? restore : null; +} + +/** Sends the restore to a sealed preview; a refusal, or no answer, reloads it. */ +function applySealedRestore( + iframe: HTMLIFrameElement, + activeDocPath: string, + files: RestoreFiles, + currentTime: number, + reloadPreview: () => void, +): "soft" | "full" { + const restore = sealedRestore(activeDocPath, files); + if (!restore) { + reloadPreview(); + return "full"; + } + void previewRequest(iframe, "restore-attributes", { ...restore, time: currentTime }).then( + (reply) => { + if (!reply?.applied) reloadPreview(); + }, + ); + return "soft"; +} + /** * Soft-apply an undo/redo restore to the live preview WITHOUT a full iframe * remount (which blanks the frame black and re-flashes the WebGL context). Eligible @@ -402,6 +466,8 @@ export function applyUndoRestoreToPreview( markScenesStale(iframe, paths); reload(); }; + if (iframe && files && previewFrameOpaque(iframe)) + return applySealedRestore(iframe, activeDocPath, files, currentTime, reloadPreview); const doc = iframe?.contentDocument; const win = iframe?.contentWindow as PreviewWindow | null; const plan = doc && files && win ? planRestoreTargets(doc, activeDocPath, files) : null; diff --git a/scripts/package-size-budgets.json b/scripts/package-size-budgets.json index 659e2a753c..45d00fc23e 100644 --- a/scripts/package-size-budgets.json +++ b/scripts/package-size-budgets.json @@ -21,7 +21,7 @@ }, "@hyperframes/inspector": { "packed": 880000, - "unpacked": 3780000 + "unpacked": 3820000 }, "@hyperframes/lint": { "packed": 191022,