fix(studio): text fields and text edits work in a sealed preview (#8156)

* test(studio): text fields and text edits in a sealed preview

* fix(studio): text fields and text edits work in a sealed preview

* refactor(core): shorter notes on edit-element markup

* refactor(studio): name the sealed text edit's steps so the code audit passes

* refactor(studio): share the text commits' steps and split the put-back check

* refactor(studio): say the sealed text edit's steps in names, not comments
This commit is contained in:
Miguel Ángel
2026-11-20 20:53:16 +00:00
committed by GitHub
parent 39fa5ae9d2
commit 6a15e8af9e
8 changed files with 456 additions and 112 deletions
@@ -114,6 +114,36 @@ describe("edit-element", () => {
expect(card.getAttribute("data-fx")).toHaveLength(MAX_EDIT_VALUE + 1);
});
it("draws text markup and answers the markup it replaced", () => {
document.body.innerHTML = `<h1 id="t">Old <span class="a">bit</span></h1>`;
const title = document.getElementById("t")!;
const html = 'New <span class="a" style="color: red">bit</span>';
const result = editElement({ handle: handleFor(title), styles: [], attributes: [], html });
expect(result).toEqual({
applied: true,
styles: [],
attributes: [],
html: 'Old <span class="a">bit</span>',
});
expect(title.innerHTML).toBe(html);
});
it("draws no markup beyond inline text, and none over markup it could not put back", () => {
document.body.innerHTML = `<h1 id="t">Old</h1><div id="d"><img src="a.png" /></div>`;
const draw = (id: string, html: string) =>
editElement({
handle: handleFor(document.getElementById(id)!),
styles: [],
attributes: [],
html,
}).applied;
for (const html of ['<img src="x">', '<a href="x">x</a>', '<span onclick="x">x</span>'])
expect(draw("t", html), html).toBe(false);
expect(document.getElementById("t")!.innerHTML).toBe("Old");
expect(draw("d", "text")).toBe(false);
expect(parseEditElement({ handle: HANDLE, styles: [], attributes: [], html: 1 })).toBeNull();
});
it("applies nothing for a handle the page no longer has", () => {
expect(editElement({ handle: HANDLE, styles: [["color", "blue"]], attributes: [] })).toEqual({
applied: false,
@@ -2,7 +2,7 @@
// 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";
import { isStylableElement, type StylableElement } from "../domRealm";
export type ElementEditEntry = [name: string, value: string | null];
export type StyleEditEntry = [name: string, value: string | null, priority?: "important"];
@@ -10,11 +10,13 @@ export type EditElementParams = {
handle: EditingElementHandle;
styles: StyleEditEntry[];
attributes: ElementEditEntry[];
html?: string;
};
export type EditElementResult = {
applied: boolean;
styles: StyleEditEntry[];
attributes: ElementEditEntry[];
html?: string;
};
export const MAX_EDIT_ENTRIES = 64;
@@ -25,6 +27,34 @@ 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 TEXT_TAGS = new Set([
"span",
"strong",
"b",
"em",
"i",
"u",
"s",
"br",
"sub",
"sup",
"small",
]);
const TEXT_ATTRIBUTES = new Set(["class", "id", "style", "title", "lang", "dir"]);
/** Markup a text field writes: text in inline text tags, no URL, no handler. */
function isTextMarkup(html: string): boolean {
if (html.length > MAX_EDIT_VALUE) return false;
const holder = document.createElement("template");
holder.innerHTML = html;
return Array.from(holder.content.querySelectorAll("*")).every(
(el) =>
TEXT_TAGS.has(el.localName) &&
el
.getAttributeNames()
.every((name) => TEXT_ATTRIBUTES.has(name) || DATA_ATTRIBUTE.test(name)),
);
}
const isValue = (value: unknown) =>
value === null || (typeof value === "string" && value.length <= MAX_EDIT_VALUE);
@@ -47,40 +77,61 @@ const attributeEntry = ([name, value, ...rest]: unknown[]) =>
export function parseEditElement(params: unknown): EditElementParams | null {
if (Object.prototype.toString.call(params) !== "[object Object]") return null;
const record = params as Record<string, unknown>;
if (Object.keys(record).sort().join() !== "attributes,handle,styles") return null;
const { handle } = record;
const keys = Object.keys(record).sort().join();
if (keys !== "attributes,handle,styles" && keys !== "attributes,handle,html,styles") return null;
const { handle, html } = record;
if (typeof handle !== "string" || !EDITING_ELEMENT_HANDLE.test(handle)) return null;
if (html !== undefined && (typeof html !== "string" || html.length > MAX_EDIT_VALUE)) return null;
const styles = entries<StyleEditEntry>(record.styles, styleEntry);
const attributes = entries<ElementEditEntry>(record.attributes, attributeEntry);
return styles && attributes ? { handle, styles, attributes } : null;
if (!styles || !attributes) return null;
return html === undefined ? { handle, styles, attributes } : { handle, styles, attributes, html };
}
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;
function refused(element: StylableElement, attributes: ElementEditEntry[], html?: string) {
if (attributes.some(([name]) => name === "src") && !MEDIA_TAGS.has(element.localName))
return true;
return html !== undefined && !(isTextMarkup(element.innerHTML) && isTextMarkup(html));
}
function valuesBefore(
element: StylableElement,
{ styles, attributes, html }: EditElementParams,
): EditElementResult {
const style = element.style;
const media = MEDIA_TAGS.has(element.localName);
if (attributes.some(([name]) => name === "src") && !media) return NOT_APPLIED;
const before: EditElementResult = {
return {
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)]),
...(html !== undefined && { html: element.innerHTML }),
};
if (![...before.styles, ...before.attributes].every(([, value]) => isValue(value)))
return NOT_APPLIED;
}
function draw(element: StylableElement, { styles, attributes, html }: EditElementParams) {
for (const [name, value, priority] of styles) {
if (value === null) style.removeProperty(name);
else style.setProperty(name, value, priority ?? "");
if (value === null) element.style.removeProperty(name);
else element.style.setProperty(name, value, priority ?? "");
}
for (const [name, value] of attributes) {
if (value === null) element.removeAttribute(name);
else element.setAttribute(name, value);
}
if (html !== undefined) element.innerHTML = html;
}
/** Draws nothing it could not put back: `src` off media, a too-long value, or non-text markup. */
export function editElement(params: EditElementParams): EditElementResult {
const element = elementForHandle(params.handle);
if (!isStylableElement(element) || refused(element, params.attributes, params.html))
return NOT_APPLIED;
const before = valuesBefore(element, params);
if (![...before.styles, ...before.attributes].every(([, value]) => isValue(value)))
return NOT_APPLIED;
draw(element, params);
return before;
}
@@ -134,7 +134,7 @@ export function collectDomEditTextFields(el: HTMLElement): DomEditTextField[] {
return [];
}
function escapeHtmlText(value: string): string {
export function escapeHtmlText(value: string): string {
return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
}
@@ -75,6 +75,7 @@ import {
} from "./manualEditsTypes";
import { rememberFrameTranslate, TRANSLATE_PX_PROPERTIES, translatePx } from "./plainTranslate";
import { rememberFrameClipPath } from "./domEditOverlayCrop";
import { previewTextFields } from "./previewTextFields";
let inertDocument: Document | undefined;
const inert = () => (inertDocument ??= document.implementation.createHTMLDocument(""));
@@ -349,8 +350,7 @@ const compositionSourceOf = (element: PreviewElement) =>
attr(element, "data-composition-src") ?? attr(element, "data-composition-file") ?? undefined;
/**
* `resolveDomEditSelection` for a frame element Studio has a description of. Text fields are left
* empty: they are read for text edits, which write through the frame's document.
* `resolveDomEditSelection` for a frame element Studio has a description of.
*/
export async function resolvePreviewSelection(
iframe: HTMLIFrameElement,
@@ -433,7 +433,7 @@ export async function resolvePreviewSelection(
dataAttributes: getDataAttributes(probe),
inlineStyles,
computedStyles,
textFields: [],
textFields: await previewTextFields(iframe, current),
capabilities,
existsInSource,
};
@@ -0,0 +1,71 @@
// Text fields of an element in a frame Studio cannot script, read from its runtime's descriptions.
import { previewComputedStyles } from "../../player/lib/previewChannel";
import { describePreviewElements, type PreviewElement } from "../../player/lib/previewElements";
import { isEditableTextLeaf, isHtmlElement } from "./domEditingDom";
import { collectDomEditTextFields } from "./domEditingLayers";
import { CURATED_STYLE_PROPERTIES, type DomEditTextField } from "./domEditingTypes";
let probeDocument: Document | undefined;
function probe(element: PreviewElement): HTMLElement {
const doc = (probeDocument ??= document.implementation.createHTMLDocument(""));
let el: HTMLElement;
try {
el = doc.createElement(element.tag);
} catch {
el = doc.createElement("div");
}
for (const [name, value] of element.attributes) {
try {
el.setAttribute(name, value);
} catch {
// A name the parser took but setAttribute refuses; no field reads such a name.
}
}
for (const [name, value] of Object.entries(element.inlineStyles))
el.style.setProperty(name, value);
return el;
}
/** `collectDomEditTextFields` for the frame's element; none when any description was cut. */
export async function previewTextFields(
iframe: HTMLIFrameElement,
element: PreviewElement,
): Promise<DomEditTextField[]> {
const handles = element.children.flatMap((child) => ("handle" in child ? [child.handle] : []));
const described = handles.length ? await describePreviewElements(iframe, handles) : [];
if (element.truncated || !described?.every((child) => child && !child.truncated)) return [];
const root = probe(element);
const handleOf = new Map<Element, string>([[root, element.handle]]);
let next = 0;
for (const child of element.children) {
if ("text" in child) {
root.append(child.text);
continue;
}
const description = described[next++]!;
const el = probe(description);
if (description.children.some((grandchild) => "handle" in grandchild))
el.append(el.ownerDocument.createElement("span"));
else el.textContent = description.text;
root.append(el);
handleOf.set(el, description.handle);
}
const leaves = Array.from(root.children).filter(isHtmlElement).filter(isEditableTextLeaf);
const fields = collectDomEditTextFields(root);
let leaf = 0;
const sources = fields.map((field): Element | undefined => {
if (field.source === "self") return root;
if (field.source === "child") return leaves[leaf++];
return undefined;
});
return Promise.all(
fields.map(async (field, index) => {
const source = sources[index];
const handle = source && handleOf.get(source);
if (!handle) return field;
const styles = await previewComputedStyles(iframe, { handle }, [...CURATED_STYLE_PROPERTIES]);
return { ...field, computedStyles: styles ?? {} };
}),
);
}
@@ -0,0 +1,138 @@
// @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 { useDomEditTextCommits } from "./useDomEditTextCommits";
(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<string, unknown> = {};
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 found = await findPreviewElementForSelection(
iframe,
{ id: "card", sourceFile: PATH },
PATH,
);
const selection = await resolvePreviewSelection(iframe, found!, {
activeCompositionPath: PATH,
isMasterView: false,
skipSourceProbe: true,
});
return { card, iframe, selection: selection! };
}
const settle = () => act(() => new Promise((resolve) => setTimeout(resolve, 20)));
function textCommits(
iframe: HTMLIFrameElement,
selection: DomEditSelection,
persist: PersistDomEditOperations,
) {
const refresh = vi.fn();
let commits: ReturnType<typeof useDomEditTextCommits> | undefined;
function Harness() {
commits = useDomEditTextCommits({
activeCompPath: PATH,
previewIframeRef: { current: iframe },
showToast: vi.fn(),
domEditSelection: selection,
applyDomSelection: vi.fn(),
refreshDomEditSelectionFromPreview: refresh,
buildDomSelectionFromTarget: vi.fn(async () => null),
persistDomEditOperations: persist,
resolveImportedFontAsset: () => null,
readOnlyPreview: false,
});
return null;
}
act(() => createRoot(document.createElement("div")).render(createElement(Harness)));
return { commits: commits!, refresh };
}
describe("text edits in a sealed preview", () => {
it("gives a sealed selection the text fields of its element", async () => {
const { selection } = await sealedCard(
`<div id="card"><span>First</span><span style="color: red">Second</span></div>`,
);
expect(selection.textFields.map((field) => [field.source, field.value])).toEqual([
["child", "First"],
["child", "Second"],
]);
expect(selection.textFields[1]!.computedStyles.color).toMatch(/red|255, 0, 0/);
});
it("draws a text commit on the frame's element and re-reads the selection", async () => {
const { card, iframe, selection } = await sealedCard(`<h1 id="card">Old</h1>`);
const persist = vi.fn<PersistDomEditOperations>(async () => undefined);
const { commits, refresh } = textCommits(iframe, selection, persist);
const outcome = await act(() => commits.handleDomTextCommitForSelection(selection, "New <b>"));
await settle();
expect(outcome.ok).toBe(true);
expect(card.textContent).toBe("New <b>");
expect(persist.mock.calls[0]?.[2]).toMatchObject({ skipRefresh: true });
expect(refresh).toHaveBeenCalledWith(selection);
});
it("draws a field commit and puts the text back when the save fails", async () => {
const { card, iframe, selection } = await sealedCard(
`<div id="card"><span>First</span><span>Second</span></div>`,
);
const persist = vi.fn<PersistDomEditOperations>(async () => undefined);
const { commits } = textCommits(iframe, selection, persist);
await act(() =>
commits.handleDomTextCommitForSelection(selection, "Changed", selection.textFields[1]!.key),
);
await settle();
expect(card.children[1]!.textContent).toBe("Changed");
persist.mockRejectedValueOnce(new Error("disk full"));
await act(() =>
commits.handleDomTextCommitForSelection(selection, "Lost", selection.textFields[0]!.key),
);
await settle();
expect(card.children[0]!.textContent).toBe("First");
});
});
@@ -25,6 +25,9 @@ import {
type DomEditCommitOutcome,
} from "./domEditCommitRunner";
import { commitDomStyles } from "./domStyleCommit";
import { editSealedSelection } from "../components/editor/previewSelection";
import { escapeHtmlText } from "../components/editor/domEditingLayers";
import { afterSealedDraw, type PreviewElementEdit } from "../player/lib/previewElements";
import { useDomEditAttributeCommits } from "./useDomEditAttributeCommits";
import type { InlineTextEditCommit } from "./useInlineTextEdit";
import type { ResolveDomSelectionOptions } from "./useDomSelectionTypes";
@@ -71,6 +74,64 @@ async function resyncDomTextSelectionFromPreview(
applyDomSelection(nextSelection, { revealPanel: false, preserveGroup: true });
}
type TextResync = Pick<
UseDomEditTextCommitsParams,
"buildDomSelectionFromTarget" | "applyDomSelection" | "refreshDomEditSelectionFromPreview"
>;
function textWriteSteps(input: {
iframe: HTMLIFrameElement | null;
selection: DomEditSelection;
activeCompPath: string | null;
textCommit: ReturnType<typeof planDomTextCommit>;
text: string;
isLatest: ReturnType<typeof bumpDomEditCommitMapVersion>;
showToast: UseDomEditTextCommitsParams["showToast"];
resync: TextResync;
}) {
const { iframe, selection, activeCompPath, textCommit, text, isLatest } = input;
const doc = iframe?.contentDocument;
let editedElement: HTMLElement | null = null;
let previousInnerHtml: string | null = null;
let sealedEdit: PreviewElementEdit | null = null;
const steps = {
capture: () => {
const el = doc ? findElementForSelection(doc, selection, activeCompPath) : null;
if (!el) return;
editedElement = el;
previousInnerHtml = el.innerHTML;
},
apply: () => {
const serialized = textCommit.usesSerializedTextFields;
if (!editedElement) {
const html = serialized ? textCommit.nextContent : escapeHtmlText(text);
sealedEdit = editSealedSelection(iframe, selection, { html });
} else if (serialized) editedElement.innerHTML = textCommit.nextContent;
else editedElement.textContent = text;
},
shouldRevert: () => isLatest(),
revert: () => {
sealedEdit?.restore();
if (editedElement && previousInnerHtml !== null) editedElement.innerHTML = previousInnerHtml;
},
onError: (error: unknown) =>
reportDomEditPersistFailure(selection, textCommit.operations, error, input.showToast),
shouldResync: isLatest,
resync: () =>
sealedEdit
? input.resync.refreshDomEditSelectionFromPreview(selection)
: resyncDomTextSelectionFromPreview(
doc,
selection,
activeCompPath,
input.resync.buildDomSelectionFromTarget,
input.resync.applyDomSelection,
),
onFinally: isLatest.release,
};
return { steps, sealedEdit: () => sealedEdit };
}
// ── Hook ──
export function useDomEditTextCommits({
@@ -162,50 +223,31 @@ export function useDomEditTextCommits({
);
const nextTextFields = buildNextDomTextFields(selection.textFields, value, fieldKey);
const textCommit = planDomTextCommit(selection.textFields, nextTextFields, value);
const iframe = previewIframeRef.current;
const doc = iframe?.contentDocument;
let editedElement: HTMLElement | null = null;
let previousInnerHtml: string | null = null;
const write = textWriteSteps({
iframe: previewIframeRef.current,
selection,
activeCompPath,
textCommit,
text: value,
isLatest: isLatestTextCommit,
showToast,
resync: {
buildDomSelectionFromTarget,
applyDomSelection,
refreshDomEditSelectionFromPreview,
},
});
return runReportedDomEditCommit({
capture: () => {
if (!doc) return;
const el = findElementForSelection(doc, selection, activeCompPath);
if (!el) return;
editedElement = el;
previousInnerHtml = el.innerHTML;
},
apply: () => {
if (!editedElement) return;
if (textCommit.usesSerializedTextFields) {
editedElement.innerHTML = textCommit.nextContent;
} else {
editedElement.textContent = value;
}
},
...write.steps,
persist: () =>
persistDomEditOperations(selection, textCommit.operations, {
label: "Edit text",
skipRefresh: true,
shouldSave: isLatestTextCommit,
}),
shouldRevert: () => isLatestTextCommit(),
revert: () => {
if (!editedElement || previousInnerHtml === null) return;
editedElement.innerHTML = previousInnerHtml;
},
onError: (error) =>
reportDomEditPersistFailure(selection, textCommit.operations, error, showToast),
shouldResync: isLatestTextCommit,
resync: () =>
resyncDomTextSelectionFromPreview(
doc,
selection,
activeCompPath,
buildDomSelectionFromTarget,
applyDomSelection,
afterSealedDraw(write.sealedEdit(), (drawn) =>
persistDomEditOperations(selection, textCommit.operations, {
label: "Edit text",
skipRefresh: drawn,
shouldSave: isLatestTextCommit,
}),
),
onFinally: isLatestTextCommit.release,
});
},
[
@@ -214,6 +256,7 @@ export function useDomEditTextCommits({
buildDomSelectionFromTarget,
persistDomEditOperations,
previewIframeRef,
refreshDomEditSelectionFromPreview,
showToast,
],
);
@@ -324,7 +367,7 @@ export function useDomEditTextCommits({
async (
selection: DomEditSelection,
nextTextFields: DomEditTextField[],
options?: { importedFont?: ImportedFontAsset | null },
options?: { importedFont?: ImportedFontAsset | null; fontFamily?: boolean },
) => {
const isLatestTextCommit = bumpDomEditCommitMapVersion(
domTextCommitVersionRef.current,
@@ -335,52 +378,34 @@ export function useDomEditTextCommits({
nextTextFields,
nextTextFields[0]?.value ?? "",
);
const iframe = previewIframeRef.current;
const doc = iframe?.contentDocument;
let editedElement: HTMLElement | null = null;
let previousInnerHtml: string | null = null;
const importedFont = options?.importedFont ?? null;
const write = textWriteSteps({
iframe: previewIframeRef.current,
selection,
activeCompPath,
textCommit,
text: textCommit.nextContent,
isLatest: isLatestTextCommit,
showToast,
resync: {
buildDomSelectionFromTarget,
applyDomSelection,
refreshDomEditSelectionFromPreview,
},
});
await runDomEditCommit({
capture: () => {
if (!doc) return;
const el = findElementForSelection(doc, selection, activeCompPath);
if (!el) return;
editedElement = el;
previousInnerHtml = el.innerHTML;
},
apply: () => {
if (!editedElement) return;
if (textCommit.usesSerializedTextFields) {
editedElement.innerHTML = textCommit.nextContent;
} else {
editedElement.textContent = textCommit.nextContent;
}
},
...write.steps,
persist: async () => {
await persistDomEditOperations(selection, textCommit.operations, {
label: "Edit text",
skipRefresh: true,
importedFont: importedFont ?? undefined,
});
const sealedFontNeedsReload = Boolean(write.sealedEdit() && options?.fontFamily);
await afterSealedDraw(write.sealedEdit(), (drawn) =>
persistDomEditOperations(selection, textCommit.operations, {
label: "Edit text",
skipRefresh: drawn && !sealedFontNeedsReload,
importedFont: importedFont ?? undefined,
}),
);
},
shouldRevert: () => isLatestTextCommit(),
revert: () => {
if (!editedElement || previousInnerHtml === null) return;
editedElement.innerHTML = previousInnerHtml;
},
onError: (error) =>
reportDomEditPersistFailure(selection, textCommit.operations, error, showToast),
shouldResync: isLatestTextCommit,
resync: () =>
resyncDomTextSelectionFromPreview(
doc,
selection,
activeCompPath,
buildDomSelectionFromTarget,
applyDomSelection,
),
onFinally: isLatestTextCommit.release,
});
},
[
@@ -389,6 +414,7 @@ export function useDomEditTextCommits({
buildDomSelectionFromTarget,
persistDomEditOperations,
previewIframeRef,
refreshDomEditSelectionFromPreview,
showToast,
],
);
@@ -429,7 +455,10 @@ export function useDomEditTextCommits({
: entry,
);
await commitDomTextFields(domEditSelection, nextTextFields, { importedFont });
await commitDomTextFields(domEditSelection, nextTextFields, {
importedFont,
fontFamily: property === "font-family",
});
},
[
commitDomTextFields,
@@ -353,28 +353,56 @@ const isEditEntries = (value: unknown, priority = false): value is StyleEntry[]
(entry.length === 2 || (priority && entry.length === 3 && entry[2] === "important")),
);
type EditReply = Awaited<ReturnType<typeof previewRequest<"edit-element">>>;
function heldBefore(before: EditReply | null | undefined) {
if (!before?.applied || !isEditEntries(before.styles, true)) return null;
if (!isEditEntries(before.attributes)) return null;
const html = typeof before.html === "string" ? before.html : undefined;
return { styles: before.styles, attributes: before.attributes, html };
}
function ownedPutBack(
before: EditReply | null | undefined,
owns: (part: string, name: string) => boolean,
) {
const held = heldBefore(before);
if (!held) return null;
const styles = held.styles.filter(([name]) => owns("style", name));
const attributes = held.attributes.filter(([name]) => owns("attr", name));
const html = owns("html", "") ? held.html : undefined;
const any = styles.length > 0 || attributes.length > 0 || html !== undefined;
return any ? { styles, attributes, html } : null;
}
export interface PreviewElementEdit {
drawn: Promise<boolean>;
restore(names?: readonly string[]): void;
}
/** Draws inline `styles` and `attributes` on the frame's element, null removing one. */
const latestWriters = new WeakMap<HTMLIFrameElement, Map<string, symbol>>();
/** Draws inline `styles`, `attributes` and text markup on the frame's element, null removing one. */
export function editPreviewElement(
iframe: HTMLIFrameElement,
handle: string,
edit: { styles?: EditEntry[]; attributes?: EditEntry[] },
edit: { styles?: EditEntry[]; attributes?: EditEntry[]; html?: string },
): PreviewElementEdit {
const send = (styles: StyleEntry[], attributes: EditEntry[]) =>
previewRequest(iframe, "edit-element", { handle, styles, attributes });
const send = (styles: StyleEntry[], attributes: EditEntry[], html?: string) =>
previewRequest(iframe, "edit-element", {
handle,
styles,
attributes,
...(html !== undefined && { html }),
});
const writers = latestWriters.get(iframe) ?? new Map<string, symbol>();
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 ?? []);
if (edit.html !== undefined) writers.set(key("html", ""), self);
const reply = send(edit.styles ?? [], edit.attributes ?? [], edit.html);
return {
drawn: reply.then((before) => before?.applied === true),
restore(names) {
@@ -382,11 +410,8 @@ export function editPreviewElement(
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 back = ownedPutBack(before, owns);
if (back) void send(back.styles, back.attributes, back.html);
});
},
};