diff --git a/packages/core/src/runtime/editing/editElement.test.ts b/packages/core/src/runtime/editing/editElement.test.ts
new file mode 100644
index 0000000000..caae4adbe3
--- /dev/null
+++ b/packages/core/src/runtime/editing/editElement.test.ts
@@ -0,0 +1,124 @@
+import { afterEach, describe, expect, it } from "vitest";
+import { handleFor } from "../editingHandles";
+import { editElement, MAX_EDIT_ENTRIES, MAX_EDIT_VALUE, parseEditElement } from "./editElement";
+
+afterEach(() => {
+ document.body.innerHTML = "";
+});
+
+const HANDLE = "0123456789abcdef:1";
+
+describe("edit-element", () => {
+ it("takes a handle with bounded style and attribute entries", () => {
+ const params = { handle: HANDLE, styles: [["opacity", "0.5"]], attributes: [["title", null]] };
+ expect(parseEditElement(params)).toEqual(params);
+ expect(parseEditElement({ ...params, extra: 1 })).toBeNull();
+ expect(parseEditElement({ ...params, styles: [["opacity;", "1"]] })).toBeNull();
+ expect(
+ parseEditElement({ ...params, styles: [["color", "x".repeat(MAX_EDIT_VALUE + 1)]] }),
+ ).toBeNull();
+ });
+
+ it("takes vendor-prefixed styles and an important marker, and no more entries than the bound", () => {
+ const style = (entry: unknown[]) => ({ handle: HANDLE, styles: [entry], attributes: [] });
+ expect(parseEditElement(style(["-webkit-mask-image", "none"]))).not.toBeNull();
+ expect(parseEditElement(style(["color", "red", "important"]))).not.toBeNull();
+ expect(parseEditElement(style(["color", "red", "urgent"]))).toBeNull();
+ const many = Array.from({ length: MAX_EDIT_ENTRIES + 1 }, (_, i) => [`data-n${i}`, "1"]);
+ expect(parseEditElement({ handle: HANDLE, styles: [], attributes: many })).toBeNull();
+ expect(
+ parseEditElement({ handle: HANDLE, styles: [], attributes: many.slice(1) }),
+ ).not.toBeNull();
+ });
+
+ it("takes only the attributes the property panel writes", () => {
+ const attribute = (name: string) =>
+ parseEditElement({ handle: HANDLE, styles: [], attributes: [[name, "x"]] });
+ for (const name of ["data-volume", "loop", "muted", "alt", "title", "src"])
+ expect(attribute(name), name).not.toBeNull();
+ for (const name of ["href", "srcdoc", "xlink:href", "action", "formaction", "style", "class"])
+ expect(attribute(name), name).toBeNull();
+ });
+
+ it("refuses event handler attributes", () => {
+ const params = { handle: HANDLE, styles: [], attributes: [["onclick", "alert(1)"]] };
+ expect(parseEditElement(params)).toBeNull();
+ expect(parseEditElement({ ...params, attributes: [["ONLOAD", "x"]] })).toBeNull();
+ });
+
+ it("draws styles and attributes and answers what they held before", () => {
+ document.body.innerHTML = `
`;
+ const card = document.getElementById("card")!;
+ const result = editElement({
+ handle: handleFor(card),
+ styles: [
+ ["color", "blue"],
+ ["opacity", "0.5"],
+ ],
+ attributes: [
+ ["data-volume", null],
+ ["title", "Card"],
+ ],
+ });
+ expect(result).toEqual({
+ applied: true,
+ styles: [
+ ["color", "red"],
+ ["opacity", null],
+ ],
+ attributes: [
+ ["data-volume", "1"],
+ ["title", null],
+ ],
+ });
+ expect(card.style.color).toBe("blue");
+ expect(card.style.opacity).toBe("0.5");
+ expect(card.hasAttribute("data-volume")).toBe(false);
+ expect(card.getAttribute("title")).toBe("Card");
+ });
+
+ it("sets a src only on media", () => {
+ document.body.innerHTML = `
`;
+ const box = document.getElementById("box")!;
+ const pic = document.getElementById("pic")!;
+ const src = (el: Element) =>
+ editElement({ handle: handleFor(el), styles: [], attributes: [["src", "b.png"]] });
+ expect(src(box).applied).toBe(false);
+ expect(box.hasAttribute("src")).toBe(false);
+ expect(src(pic)).toEqual({ applied: true, styles: [], attributes: [["src", "a.png"]] });
+ expect(pic.getAttribute("src")).toBe("b.png");
+ });
+
+ it("answers an important style with its priority, so putting it back keeps it", () => {
+ document.body.innerHTML = ``;
+ const card = document.getElementById("card")!;
+ const handle = handleFor(card);
+ const { styles } = editElement({ handle, styles: [["color", "blue"]], attributes: [] });
+ expect(styles).toEqual([["color", "red", "important"]]);
+ editElement({ handle, styles, attributes: [] });
+ expect(card.style.getPropertyValue("color")).toBe("red");
+ expect(card.style.getPropertyPriority("color")).toBe("important");
+ });
+
+ it("draws nothing whose old value is too long to send back", () => {
+ document.body.innerHTML = ``;
+ const card = document.getElementById("card")!;
+ card.setAttribute("data-fx", "x".repeat(MAX_EDIT_VALUE + 1));
+ const result = editElement({
+ handle: handleFor(card),
+ styles: [["color", "blue"]],
+ attributes: [["data-fx", "short"]],
+ });
+ expect(result.applied).toBe(false);
+ expect(card.style.color).toBe("");
+ expect(card.getAttribute("data-fx")).toHaveLength(MAX_EDIT_VALUE + 1);
+ });
+
+ it("applies nothing for a handle the page no longer has", () => {
+ expect(editElement({ handle: HANDLE, styles: [["color", "blue"]], attributes: [] })).toEqual({
+ applied: false,
+ styles: [],
+ attributes: [],
+ });
+ });
+});
diff --git a/packages/core/src/runtime/editing/editElement.ts b/packages/core/src/runtime/editing/editElement.ts
new file mode 100644
index 0000000000..568ae4a886
--- /dev/null
+++ b/packages/core/src/runtime/editing/editElement.ts
@@ -0,0 +1,86 @@
+// `edit-element`: a property panel edit drawn live on one element: inline styles and attributes,
+// null removing one. The reply carries what each name held before, so a failed save can put it back.
+import { EDITING_ELEMENT_HANDLE, type EditingElementHandle } from "../editingElement";
+import { elementForHandle } from "../editingHandles";
+import { isStylableElement } from "../domRealm";
+
+export type ElementEditEntry = [name: string, value: string | null];
+export type StyleEditEntry = [name: string, value: string | null, priority?: "important"];
+export type EditElementParams = {
+ handle: EditingElementHandle;
+ styles: StyleEditEntry[];
+ attributes: ElementEditEntry[];
+};
+export type EditElementResult = {
+ applied: boolean;
+ styles: StyleEditEntry[];
+ attributes: ElementEditEntry[];
+};
+
+export const MAX_EDIT_ENTRIES = 64;
+export const MAX_EDIT_VALUE = 200_000;
+const STYLE_NAME = /^(?:-?[a-z][a-z0-9-]*|--[\w\u0080--]+)$/;
+const DATA_ATTRIBUTE = /^data-[a-z0-9_-]+$/;
+const PANEL_ATTRIBUTES = new Set(["loop", "muted", "alt", "title", "src"]);
+const MEDIA_TAGS = new Set(["img", "video", "audio"]);
+
+const isAttributeName = (name: string) => DATA_ATTRIBUTE.test(name) || PANEL_ATTRIBUTES.has(name);
+const isValue = (value: unknown) =>
+ value === null || (typeof value === "string" && value.length <= MAX_EDIT_VALUE);
+
+function entries(value: unknown, valid: (entry: unknown[]) => boolean): T[] | null {
+ if (!Array.isArray(value) || value.length > MAX_EDIT_ENTRIES) return null;
+ const ok = value.every((entry) => Array.isArray(entry) && valid(entry));
+ return ok ? (value as T[]) : null;
+}
+
+const styleEntry = ([name, value, priority, ...rest]: unknown[]) =>
+ typeof name === "string" &&
+ STYLE_NAME.test(name) &&
+ isValue(value) &&
+ (priority === undefined || priority === "important") &&
+ rest.length === 0;
+
+const attributeEntry = ([name, value, ...rest]: unknown[]) =>
+ typeof name === "string" && isAttributeName(name) && isValue(value) && rest.length === 0;
+
+export function parseEditElement(params: unknown): EditElementParams | null {
+ if (Object.prototype.toString.call(params) !== "[object Object]") return null;
+ const record = params as Record;
+ if (Object.keys(record).sort().join() !== "attributes,handle,styles") return null;
+ const { handle } = record;
+ if (typeof handle !== "string" || !EDITING_ELEMENT_HANDLE.test(handle)) return null;
+ const styles = entries(record.styles, styleEntry);
+ const attributes = entries(record.attributes, attributeEntry);
+ return styles && attributes ? { handle, styles, attributes } : null;
+}
+
+const NOT_APPLIED: EditElementResult = { applied: false, styles: [], attributes: [] };
+
+/** Draws nothing it could not put back: a `src` off media, or a value too long to send back. */
+export function editElement({ handle, styles, attributes }: EditElementParams): EditElementResult {
+ const element = elementForHandle(handle);
+ if (!isStylableElement(element)) return NOT_APPLIED;
+ const style = element.style;
+ const media = MEDIA_TAGS.has(element.localName);
+ if (attributes.some(([name]) => name === "src") && !media) return NOT_APPLIED;
+ const before: EditElementResult = {
+ applied: true,
+ styles: styles.map(([name]): StyleEditEntry => {
+ const value = style.getPropertyValue(name) || null;
+ return style.getPropertyPriority(name) ? [name, value, "important"] : [name, value];
+ }),
+ attributes: attributes.map(([name]): ElementEditEntry => [name, element.getAttribute(name)]),
+ };
+ if (![...before.styles, ...before.attributes].every(([, value]) => isValue(value)))
+ return NOT_APPLIED;
+ for (const [name, value, priority] of styles) {
+ if (value === null) style.removeProperty(name);
+ else style.setProperty(name, value, priority ?? "");
+ }
+ for (const [name, value] of attributes) {
+ if (value === null) element.removeAttribute(name);
+ else element.setAttribute(name, value);
+ }
+ return before;
+}
diff --git a/packages/core/src/runtime/editingAgent.test.ts b/packages/core/src/runtime/editingAgent.test.ts
index 6e04cce034..88fa856e98 100644
--- a/packages/core/src/runtime/editingAgent.test.ts
+++ b/packages/core/src/runtime/editingAgent.test.ts
@@ -199,6 +199,7 @@ describe("installEditingAgent", () => {
"motion-path-home",
"max-z-index",
"crop-lift",
+ "edit-element",
],
},
});
diff --git a/packages/core/src/runtime/editingAgent.ts b/packages/core/src/runtime/editingAgent.ts
index 76efb0e03f..b4af319539 100644
--- a/packages/core/src/runtime/editingAgent.ts
+++ b/packages/core/src/runtime/editingAgent.ts
@@ -57,6 +57,7 @@ import { assignAudioGroup } from "./editing/assignAudioGroup";
import { audioMeter } from "./editing/audioMeter";
import { documentMarkup } from "./editing/documentMarkup";
import { setAudioGroupAttribute } from "./editing/setAudioGroupAttribute";
+import { editElement } from "./editing/editElement";
type Handlers = {
[K in EditingRequestKind]: (
@@ -218,6 +219,7 @@ const HANDLERS: Handlers = {
"motion-path-home": ({ selector }) => motionPathHome(selector),
"max-z-index": () => maxZIndex(),
"crop-lift": cropLift,
+ "edit-element": editElement,
};
function serve(port: MessagePort): void {
diff --git a/packages/core/src/runtime/editingPort.test.ts b/packages/core/src/runtime/editingPort.test.ts
index 5dc030bb20..e7c4b680c2 100644
--- a/packages/core/src/runtime/editingPort.test.ts
+++ b/packages/core/src/runtime/editingPort.test.ts
@@ -102,6 +102,7 @@ describe("createEditingPortClient", () => {
"motion-path-home",
"max-z-index",
"crop-lift",
+ "edit-element",
],
});
} finally {
diff --git a/packages/core/src/runtime/editingPort.ts b/packages/core/src/runtime/editingPort.ts
index f6823b0da1..11d022ac95 100644
--- a/packages/core/src/runtime/editingPort.ts
+++ b/packages/core/src/runtime/editingPort.ts
@@ -60,6 +60,11 @@ import {
parseSetAudioGroupAttribute,
type SetAudioGroupAttributeParams,
} from "./editing/setAudioGroupAttribute";
+import {
+ parseEditElement,
+ type EditElementParams,
+ type EditElementResult,
+} from "./editing/editElement";
export {
buildStableSelector,
@@ -170,6 +175,7 @@ export const EDITING_REQUEST_KINDS = [
"motion-path-home",
"max-z-index",
"crop-lift",
+ "edit-element",
] as const;
export type EditingRequestKind = (typeof EDITING_REQUEST_KINDS)[number];
@@ -303,6 +309,7 @@ export interface EditingRequests {
params: { handle: EditingElementHandle; lift: boolean };
result: { lifted: boolean; clipPath: string | null };
};
+ "edit-element": { params: EditElementParams; result: EditElementResult };
}
export type EditingParams = EditingRequests[K]["params"];
export type EditingResult = EditingRequests[K]["result"];
@@ -510,6 +517,7 @@ const PARAM_PARSERS: {
hasKeys(params, "handle,lift") && isHandle(params.handle) && typeof params.lift === "boolean"
? { handle: params.handle, lift: params.lift }
: null,
+ "edit-element": parseEditElement,
};
/** Validates one request off the wire. Never throws: anything unusable becomes a typed error. */
diff --git a/packages/studio/src/components/editor/previewSelection.ts b/packages/studio/src/components/editor/previewSelection.ts
index 358016168b..ffaf66f6c7 100644
--- a/packages/studio/src/components/editor/previewSelection.ts
+++ b/packages/studio/src/components/editor/previewSelection.ts
@@ -26,8 +26,10 @@ import {
previewElementSelectorIndex,
previewPointerTargets,
previewElementSourceFile,
+ editPreviewElement,
queryPreviewElements,
type PreviewElement,
+ type PreviewElementEdit,
} from "../../player/lib/previewElements";
import { coversCompositionRoot } from "./domEditingRootLayer";
import {
@@ -518,6 +520,15 @@ export async function findPointerTargets(
return (described ?? []).filter((element) => element !== null);
}
+export function editSealedSelection(
+ iframe: HTMLIFrameElement | null | undefined,
+ selection: DomEditSelection,
+ edit: Parameters[2],
+): PreviewElementEdit | null {
+ if (!iframe || !selection.handle || !previewFrameOpaque(iframe)) return null;
+ return editPreviewElement(iframe, selection.handle, edit);
+}
+
/** A stand-in is never connected: an opaque frame's selection stands until it is replaced. */
export const selectionElementLive = (selection: DomEditSelection) =>
selection.handle !== undefined || selection.element.isConnected;
diff --git a/packages/studio/src/hooks/domEditCommits.sealed.test.ts b/packages/studio/src/hooks/domEditCommits.sealed.test.ts
new file mode 100644
index 0000000000..dc9dfa7421
--- /dev/null
+++ b/packages/studio/src/hooks/domEditCommits.sealed.test.ts
@@ -0,0 +1,191 @@
+// @vitest-environment happy-dom
+
+import { act, createElement } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, describe, expect, it, vi } from "vitest";
+// The frame's real runtime agent, serving the opaque frame from this document.
+import { installMarkedEditingAgent } from "../../../core/src/runtime/editingAgent.test-helpers";
+import { detachedFakeIframe } from "../player/hooks/timelinePlayerTestHarness";
+import {
+ findPreviewElementForSelection,
+ resolvePreviewSelection,
+} from "../components/editor/previewSelection";
+import type { DomEditSelection } from "../components/editor/domEditing";
+import type { PersistDomEditOperations } from "./domEditCommitTypes";
+import { commitDomStyles } from "./domStyleCommit";
+import { useDomEditAttributeCommits } from "./useDomEditAttributeCommits";
+
+(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const closers: Array<() => void> = [];
+afterEach(() => {
+ closers.splice(0).forEach((close) => close());
+ document.body.innerHTML = "";
+});
+
+/** A frame Studio cannot read, whose runtime is the real editing agent over this document. */
+function opaqueFrame(): HTMLIFrameElement {
+ const frame: Record = {};
+ const iframe = detachedFakeIframe(frame);
+ Object.defineProperty(iframe, "contentDocument", { value: null });
+ Object.defineProperty(frame, "document", {
+ get: () => {
+ throw new DOMException("blocked", "SecurityError");
+ },
+ });
+ const parent = {
+ postMessage: (data: unknown, _origin: string, ports: MessagePort[]) =>
+ window.dispatchEvent(
+ new MessageEvent("message", { source: frame as unknown as Window, data, ports }),
+ ),
+ } as unknown as Window;
+ const agent = installMarkedEditingAgent(parent);
+ frame.postMessage = (data: unknown) =>
+ window.dispatchEvent(new MessageEvent("message", { source: parent, data }));
+ closers.push(() => agent.dispose());
+ return iframe;
+}
+
+const PATH = "index.html";
+
+async function sealedCard(markup: string) {
+ document.body.innerHTML = markup;
+ const card = document.getElementById("card")!;
+ const iframe = opaqueFrame();
+ const target = { id: "card", sourceFile: PATH };
+ const found = await findPreviewElementForSelection(iframe, target, PATH);
+ const selection = await resolvePreviewSelection(iframe, found!, {
+ activeCompositionPath: PATH,
+ isMasterView: false,
+ skipSourceProbe: true,
+ });
+ return { card, iframe, selection: selection! };
+}
+
+/** Lets the port's request and the frame's reply land. */
+const settle = () => act(() => new Promise((resolve) => setTimeout(resolve, 20)));
+
+function styleContext(iframe: HTMLIFrameElement, persist: PersistDomEditOperations) {
+ return {
+ activeCompPath: PATH,
+ previewIframeRef: { current: iframe },
+ persistDomEditOperations: persist,
+ showToast: vi.fn(),
+ versions: new Map(),
+ };
+}
+
+function attributeCommits(
+ iframe: HTMLIFrameElement,
+ selection: DomEditSelection,
+ persist: PersistDomEditOperations,
+) {
+ let commits: ReturnType | undefined;
+ function Harness() {
+ commits = useDomEditAttributeCommits({
+ activeCompPath: PATH,
+ previewIframeRef: { current: iframe },
+ showToast: vi.fn(),
+ domEditSelection: selection,
+ refreshDomEditSelectionFromPreview: vi.fn(),
+ persistDomEditOperations: persist,
+ });
+ return null;
+ }
+ act(() => createRoot(document.createElement("div")).render(createElement(Harness)));
+ return commits!;
+}
+
+describe("DOM edit commits in a sealed preview", () => {
+ it("draws a style commit on the frame's element and saves it without a reload", async () => {
+ const { card, iframe, selection } = await sealedCard(`Hi
`);
+ const persist = vi.fn(async () => undefined);
+ const outcome = await commitDomStyles(styleContext(iframe, persist), selection, {
+ opacity: "0.5",
+ });
+ await settle();
+ expect(outcome.ok).toBe(true);
+ expect(card.style.opacity).toBe("0.5");
+ expect(persist.mock.calls[0]?.[2]).toMatchObject({ skipRefresh: true });
+ });
+
+ it("puts the frame's style back when the save fails", async () => {
+ const { card, iframe, selection } = await sealedCard(
+ `Hi
`,
+ );
+ const persist = vi.fn(async () => {
+ throw new Error("disk full");
+ });
+ await commitDomStyles(styleContext(iframe, persist), selection, { color: "blue" });
+ await settle();
+ expect(card.style.color).toBe("red");
+ });
+
+ it("reloads a sealed frame for a font change, which it cannot load from Studio", async () => {
+ const { iframe, selection } = await sealedCard(`Hi
`);
+ const persist = vi.fn(async () => undefined);
+ await commitDomStyles(styleContext(iframe, persist), selection, { "font-family": "Inter" });
+ expect(persist.mock.calls[0]?.[2]).toMatchObject({ skipRefresh: false });
+ });
+
+ it("reloads when the frame no longer has the element to draw on", async () => {
+ const { card, iframe, selection } = await sealedCard(`Hi
`);
+ card.remove();
+ const persist = vi.fn(async () => undefined);
+ await commitDomStyles(styleContext(iframe, persist), selection, { opacity: "0.5" });
+ expect(persist.mock.calls[0]?.[2]).toMatchObject({ skipRefresh: false });
+ });
+
+ it("reloads when the frame refuses the edit", async () => {
+ const { card, iframe, selection } = await sealedCard(`Hi
`);
+ const persist = vi.fn(async () => undefined);
+ const tooLong = `"${"x".repeat(200_001)}"`;
+ await commitDomStyles(styleContext(iframe, persist), selection, {
+ "font-feature-settings": tooLong,
+ });
+ expect(persist.mock.calls[0]?.[2]).toMatchObject({ skipRefresh: false });
+ expect(card.style.fontFeatureSettings).toBe("");
+ });
+
+ it("draws data and HTML attribute commits on the frame's element", async () => {
+ const { card, iframe, selection } = await sealedCard(`Hi
`);
+ const persist = vi.fn(async () => undefined);
+ const commits = attributeCommits(iframe, selection, persist);
+ await act(() => commits.handleDomAttributeQuietCommit("volume", "0.25"));
+ await act(() => commits.handleDomHtmlAttributeCommit("title", "Card"));
+ await settle();
+ expect(card.dataset.volume).toBe("0.25");
+ expect(card.getAttribute("title")).toBe("Card");
+ });
+
+ it("never puts back a value over a newer edit that saved", async () => {
+ const { card, iframe, selection } = await sealedCard(
+ `Hi
`,
+ );
+ let saves = 0;
+ const persist = vi.fn(async () => {
+ if (saves++ === 0) throw new Error("disk full");
+ });
+ const commits = attributeCommits(iframe, selection, persist);
+ await act(async () => {
+ const first = commits.handleDomHtmlAttributeCommit("title", "first");
+ for (let i = 0; i < 5; i++) await Promise.resolve();
+ await Promise.all([first, commits.handleDomHtmlAttributeCommit("title", "second")]);
+ });
+ await settle();
+ expect(card.getAttribute("title")).toBe("second");
+ });
+
+ it("puts the frame's attributes back when a batch save fails", async () => {
+ const { card, iframe, selection } = await sealedCard(
+ `Hi
`,
+ );
+ const persist = vi.fn(async () => {
+ throw new Error("disk full");
+ });
+ const commits = attributeCommits(iframe, selection, persist);
+ await act(() => commits.handleDomAttributesCommit(selection, { start: "3", duration: "4" }));
+ await settle();
+ expect([card.dataset.start, card.dataset.duration]).toEqual(["1", "2"]);
+ });
+});
diff --git a/packages/studio/src/hooks/domStyleCommit.ts b/packages/studio/src/hooks/domStyleCommit.ts
index 33158c1586..7bf9122cac 100644
--- a/packages/studio/src/hooks/domStyleCommit.ts
+++ b/packages/studio/src/hooks/domStyleCommit.ts
@@ -13,6 +13,8 @@ import {
type DomEditSelection,
} from "../components/editor/domEditing";
import type { ImportedFontAsset } from "../components/editor/fontAssets";
+import { editSealedSelection } from "../components/editor/previewSelection";
+import { afterSealedDraw, type PreviewElementEdit } from "../player/lib/previewElements";
import type { PersistDomEditOperations } from "./domEditCommitTypes";
import { reportDomEditPersistFailure } from "./domEditPersistFailure";
import {
@@ -86,6 +88,7 @@ export async function commitDomStyles(
}
let editedElement: HTMLElement | null = null;
const previousInline = new Map();
+ let sealedEdit: PreviewElementEdit | null = null;
return runReportedDomEditCommit({
capture: () => {
@@ -96,7 +99,12 @@ export async function commitDomStyles(
previousInline.set(property, el.style.getPropertyValue(property));
},
apply: () => {
- if (!editedElement) return;
+ if (!editedElement) {
+ sealedEdit = editSealedSelection(previewIframeRef.current, selection, {
+ styles: liveStyles,
+ });
+ return;
+ }
for (const [property, value] of liveStyles) editedElement.style.setProperty(property, value);
if (fontFamily !== undefined && doc) {
injectPreviewGoogleFont(doc, fontFamily);
@@ -104,14 +112,17 @@ export async function commitDomStyles(
}
},
persist: () =>
- persistDomEditOperations(selection, operations, {
- label: "Edit layer style",
- // Inline styles are already live, so a reload would only blank the preview.
- skipRefresh: true,
- importedFont: importedFont ?? undefined,
- }),
+ afterSealedDraw(sealedEdit, (drawn) =>
+ persistDomEditOperations(selection, operations, {
+ label: "Edit layer style",
+ // Live styles skip the reload; a sealed frame reloads to load a new font.
+ skipRefresh: drawn && !(sealedEdit && fontFamily !== undefined),
+ importedFont: importedFont ?? undefined,
+ }),
+ ),
shouldRevert: ownsAny,
revert: () => {
+ sealedEdit?.restore(owned.filter(({ isLatest }) => isLatest()).map((o) => o.property));
const el = editedElement;
if (!el) return;
// ponytail: background-image fit styles are not reverted here.
diff --git a/packages/studio/src/hooks/useDomEditAttributeCommits.ts b/packages/studio/src/hooks/useDomEditAttributeCommits.ts
index c2fa94a1c9..c8c39bcca1 100644
--- a/packages/studio/src/hooks/useDomEditAttributeCommits.ts
+++ b/packages/studio/src/hooks/useDomEditAttributeCommits.ts
@@ -14,6 +14,8 @@ import { bumpDomEditCommitMapVersion, runDomEditCommit } from "./domEditCommitRu
import { syncStoredAutomationFromPreview } from "../player/lib/automationStoreSync";
import { HF_AUDIO_GROUP_ATTR, HF_AUDIO_GROUP_TAG } from "@hyperframes/core/audio-groups";
import { invalidateGroupInfoCache } from "../player/lib/timelineGroupInfo";
+import { editSealedSelection } from "../components/editor/previewSelection";
+import { afterSealedDraw, type PreviewElementEdit } from "../player/lib/previewElements";
// ── Types ──
@@ -161,6 +163,7 @@ export function useDomEditAttributeCommits({
const op: PatchOperation = { type: "attribute", property: attr, value };
let editedElement: HTMLElement | null = null;
let previousValue: string | null = null;
+ let sealedEdit: PreviewElementEdit | null = null;
await runDomEditCommit({
capture: () => {
@@ -175,20 +178,27 @@ export function useDomEditAttributeCommits({
previousValue = captured.previousValue;
},
apply: () => {
- if (!editedElement) return;
const nextValue = value === null || value === "" ? null : value;
+ if (!editedElement) {
+ const attributes: Array<[string, string | null]> = [[fullAttr, nextValue]];
+ sealedEdit = editSealedSelection(iframe, domEditSelection, { attributes });
+ return;
+ }
setOrRemovePreviewAttribute(editedElement, fullAttr, nextValue);
},
persist: options.previewOnly
? async () => {}
: () =>
- persistDomEditOperations(domEditSelection, [op], {
- label: options.label,
- coalesceKey: commitKey,
- skipRefresh: options.skipRefresh,
- }),
+ afterSealedDraw(sealedEdit, (drawn) =>
+ persistDomEditOperations(domEditSelection, [op], {
+ label: options.label,
+ coalesceKey: commitKey,
+ skipRefresh: options.skipRefresh && drawn,
+ }),
+ ),
shouldRevert: () => isLatestCommit(),
revert: () => {
+ sealedEdit?.restore();
if (!editedElement) return;
setOrRemovePreviewAttribute(editedElement, fullAttr, previousValue);
},
@@ -256,6 +266,7 @@ export function useDomEditAttributeCommits({
commitKey,
);
let captured: CapturedMultiAttributeElement | null = null;
+ let sealedEdit: PreviewElementEdit | null = null;
let landed = false;
await runDomEditCommit({
@@ -268,21 +279,31 @@ export function useDomEditAttributeCommits({
);
},
apply: () => {
- if (!captured) return;
+ if (!captured) {
+ const attributes = entries.map(({ fullAttr, value }): [string, string | null] => [
+ fullAttr,
+ value,
+ ]);
+ sealedEdit = editSealedSelection(iframe, selection, { attributes });
+ return;
+ }
for (const entry of entries) {
setOrRemovePreviewAttribute(captured.element, entry.fullAttr, entry.value);
}
},
persist: () =>
- persistDomEditOperations(selection, ops, {
- label: options.label,
- coalesceKey: commitKey,
- skipRefresh: options.skipRefresh,
- prepareContent: options.prepareContent,
- }),
+ afterSealedDraw(sealedEdit, (drawn) =>
+ persistDomEditOperations(selection, ops, {
+ label: options.label,
+ coalesceKey: commitKey,
+ skipRefresh: options.skipRefresh && drawn,
+ prepareContent: options.prepareContent,
+ }),
+ ),
shouldRevert: (error) =>
isLatestCommit() && !(error instanceof DomEditPersistPreparedWriteError),
revert: () => {
+ sealedEdit?.restore();
if (!captured) return;
for (const entry of entries) {
setOrRemovePreviewAttribute(
@@ -413,6 +434,7 @@ export function useDomEditAttributeCommits({
const op: PatchOperation = { type: "html-attribute", property: attr, value };
let editedElement: HTMLElement | null = null;
let previousValue: string | null = null;
+ let sealedEdit: PreviewElementEdit | null = null;
await runDomEditCommit({
capture: () => {
@@ -427,12 +449,13 @@ export function useDomEditAttributeCommits({
previousValue = captured.previousValue;
},
apply: () => {
- if (!editedElement) return;
- setOrRemovePreviewAttribute(
- editedElement,
- attr,
- resolveOptimisticAttributeValue(attr, value),
- );
+ const optimistic = resolveOptimisticAttributeValue(attr, value);
+ if (!editedElement) {
+ const attributes: Array<[string, string | null]> = [[attr, optimistic]];
+ sealedEdit = editSealedSelection(iframe, domEditSelection, { attributes });
+ return;
+ }
+ setOrRemovePreviewAttribute(editedElement, attr, optimistic);
},
persist: () =>
persistDomEditOperations(domEditSelection, [op], {
@@ -442,6 +465,7 @@ export function useDomEditAttributeCommits({
}),
shouldRevert: () => isLatestCommit(),
revert: () => {
+ sealedEdit?.restore();
if (!editedElement) return;
setOrRemovePreviewAttribute(editedElement, attr, previousValue);
},
diff --git a/packages/studio/src/player/lib/previewElements.ts b/packages/studio/src/player/lib/previewElements.ts
index e9d984c420..f4f70d58eb 100644
--- a/packages/studio/src/player/lib/previewElements.ts
+++ b/packages/studio/src/player/lib/previewElements.ts
@@ -310,3 +310,69 @@ export async function previewLayers(
if (typeof missingGroup !== "boolean") return null;
return layers.every(isLayer) ? { layers, truncated, missingGroup } : null;
}
+
+type EditEntry = [name: string, value: string | null];
+type StyleEntry = [name: string, value: string | null, priority?: "important"];
+const isEditEntries = (value: unknown, priority = false): value is StyleEntry[] =>
+ Array.isArray(value) &&
+ value.every(
+ (entry) =>
+ Array.isArray(entry) &&
+ isText(entry[0]) &&
+ (entry[1] === null || isText(entry[1])) &&
+ (entry.length === 2 || (priority && entry.length === 3 && entry[2] === "important")),
+ );
+
+export interface PreviewElementEdit {
+ drawn: Promise;
+ restore(names?: readonly string[]): void;
+}
+
+/** Draws inline `styles` and `attributes` on the frame's element, null removing one. */
+const latestWriters = new WeakMap>();
+
+export function editPreviewElement(
+ iframe: HTMLIFrameElement,
+ handle: string,
+ edit: { styles?: EditEntry[]; attributes?: EditEntry[] },
+): PreviewElementEdit {
+ const send = (styles: StyleEntry[], attributes: EditEntry[]) =>
+ previewRequest(iframe, "edit-element", { handle, styles, attributes });
+ const writers = latestWriters.get(iframe) ?? new Map();
+ latestWriters.set(iframe, writers);
+ const self = Symbol("edit");
+ const key = (part: string, name: string) => `${handle} ${part} ${name}`;
+ for (const [name] of edit.styles ?? []) writers.set(key("style", name), self);
+ for (const [name] of edit.attributes ?? []) writers.set(key("attr", name), self);
+ const reply = send(edit.styles ?? [], edit.attributes ?? []);
+ return {
+ drawn: reply.then((before) => before?.applied === true),
+ restore(names) {
+ // Checked when the old values go back: a later edit of a name owns it by then.
+ const owns = (part: string, name: string) =>
+ (!names || names.includes(name)) && writers.get(key(part, name)) === self;
+ void reply.then((before) => {
+ if (!before?.applied || !isEditEntries(before.styles, true)) return;
+ if (!isEditEntries(before.attributes)) return;
+ const styles = before.styles.filter(([name]) => owns("style", name));
+ const attributes = before.attributes.filter(([name]) => owns("attr", name));
+ if (styles.length || attributes.length) void send(styles, attributes);
+ });
+ },
+ };
+}
+
+const SEALED_DRAW_WAIT_MS = 300;
+
+/** Saves a live edit at once; a sealed one once the frame says it drew it, else after the wait. */
+export function afterSealedDraw(edit: PreviewElementEdit | null, save: (drawn: boolean) => T) {
+ if (!edit) return save(true);
+ let timer: ReturnType | undefined;
+ const late = new Promise((resolve) => {
+ timer = setTimeout(resolve, SEALED_DRAW_WAIT_MS, false);
+ });
+ return Promise.race([edit.drawn, late]).then((drawn) => {
+ clearTimeout(timer);
+ return save(drawn);
+ });
+}