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
5 changes: 5 additions & 0 deletions packages/studio/src/components/editor/previewDrafts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ export function registerPreviewStandIn(

export const previewStandIn = (standIn: Element) => standIns.get(standIn);

export function previewDraftLive(standIn: Element): boolean {
const target = standIns.get(standIn);
return !!target && !!queues.get(target.iframe)?.drawn.has(target.handle);
}

function queueFor(iframe: HTMLIFrameElement): Queue {
let queue = queues.get(iframe);
if (!queue) {
Expand Down
135 changes: 135 additions & 0 deletions packages/studio/src/hooks/geometryCommits.sealed.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
// @vitest-environment happy-dom

import { act, createElement } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
findPreviewElementForSelection,
resolvePreviewSelection,
} from "../components/editor/previewSelection";
import { drawPreviewDraft } from "../components/editor/previewDrafts";
import { sealedPreviewFrame } from "../player/lib/sealedPreviewFrame.test-helpers";
import { resizeSelectionFromAgent } from "../webmcp/StudioAgentTools";
import type { PersistDomEditOperations } from "./domEditCommitTypes";
import { useDomEditPositionPatchCommit } from "./useDomEditPositionPatchCommit";
import { useDomGeometryCommits } from "./useDomGeometryCommits";

(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;

const PATH = "index.html";
const CARD = `<div id="card" style="position: absolute; left: 10px; top: 10px; width: 100px; height: 50px">Hi</div>`;

afterEach(() => {
document.body.innerHTML = "";
});

/** Studio's geometry commits on a sealed preview of CARD, saving through `persist`. */
async function sealedCard(persist: PersistDomEditOperations) {
document.body.innerHTML = CARD;
const card = document.getElementById("card")!;
const { iframe } = sealedPreviewFrame();
const found = await findPreviewElementForSelection(
iframe,
{ id: "card", sourceFile: PATH },
PATH,
);
const selection = (await resolvePreviewSelection(iframe, found!, {
activeCompositionPath: PATH,
isMasterView: false,
skipSourceProbe: true,
}))!;
let commits: ReturnType<typeof useDomGeometryCommits> | undefined;
function Harness() {
const commitPositionPatchToHtml = useDomEditPositionPatchCommit({
activeCompPath: PATH,
previewIframeRef: { current: iframe },
persistDomEditOperations: persist,
showToast: vi.fn(),
});
commits = useDomGeometryCommits({
showToast: vi.fn(),
readOnlyPreview: false,
commitPositionPatchToHtml,
});
return null;
}
act(() => createRoot(document.createElement("div")).render(createElement(Harness)));
return { card, selection, commits: commits! };
}

/** Lets the port's request and the frame's reply land. */
const settle = () => act(() => new Promise((resolve) => setTimeout(resolve, 20)));
const saved = () => vi.fn<PersistDomEditOperations>(async () => undefined);

describe("geometry commits in a sealed preview", () => {
it("draws a resize from the agent on the frame's element", async () => {
const { card, selection, commits } = await sealedCard(saved());

await resizeSelectionFromAgent(
selection,
{ width: 200, height: 80 },
commits.handleDomBoxSizeCommit,
);
await settle();

expect([card.style.width, card.style.height]).toEqual(["200px", "80px"]);
});

it("draws a size typed in the inspector on the frame's element", async () => {
const persist = saved();
const { card, selection, commits } = await sealedCard(persist);

await commits.handleDomBoxSizeCommit(selection, { width: 160, height: 90 });
await settle();

expect([card.style.width, card.style.height]).toEqual(["160px", "90px"]);
expect(persist.mock.calls[0]?.[2]).toMatchObject({ skipRefresh: true });
});

it("draws an offset typed in the inspector on the frame's element", async () => {
const { card, selection, commits } = await sealedCard(saved());

await commits.stageElementPositionOffset(selection, { x: 40, y: 20 }, true).save();
await settle();

expect(card.style.translate).toBe(selection.element.style.translate);
expect(card.style.translate).toMatch(/40px/);
});

it("draws a rotation from the agent on the frame's element", async () => {
const { card, selection, commits } = await sealedCard(saved());

await commits.handleDomRotationCommit(selection, { angle: 30 });
await settle();

expect(card.style.rotate).toBe("30deg");
});

it("leaves the frame to a drag whose draft is still live", async () => {
const { card, selection, commits } = await sealedCard(saved());
drawPreviewDraft(selection.element, { size: { width: 150, height: 50 } });
await settle();

await commits.handleDomBoxSizeCommit(selection, { width: 200, height: 80 });
await settle();

expect(card.style.width).toBe("150px");
});

it("puts the frame's element and the selection back exactly when the save fails", async () => {
const failed = vi.fn<PersistDomEditOperations>(async () => {
throw new Error("disk full");
});
const { card, selection, commits } = await sealedCard(failed);
const frameBefore = card.style.cssText;
const shownBefore = selection.element.style.cssText;

await expect(
commits.handleDomBoxSizeCommit(selection, { width: 200, height: 80 }),
).rejects.toThrow("disk full");
await settle();

expect(card.style.cssText).toBe(frameBefore);
expect(selection.element.style.cssText).toBe(shownBefore);
});
});
1 change: 1 addition & 0 deletions packages/studio/src/hooks/useDomEditCommits.ts
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,7 @@ export function useDomEditCommits({

const commitPositionPatchToHtml = useDomEditPositionPatchCommit({
activeCompPath,
previewIframeRef,
persistDomEditOperations,
showToast,
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ function paramsWith(persistDomEditOperations: () => Promise<undefined>) {
showToast,
params: {
activeCompPath: "index.html",
previewIframeRef: { current: null },
persistDomEditOperations,
showToast,
},
Expand Down
51 changes: 42 additions & 9 deletions packages/studio/src/hooks/useDomEditPositionPatchCommit.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import { useCallback } from "react";
import { useCallback, type RefObject } from "react";
import type { DomEditSelection } from "../components/editor/domEditing";
import { previewDraftLive } from "../components/editor/previewDrafts";
import {
editSealedSelection,
showSavedStylesOnStandIn,
} from "../components/editor/previewSelection";
import { afterSealedDraw } from "../player/lib/previewElements";
import type { PatchOperation } from "../utils/sourcePatcher";
import { trackStudioSaveFailure } from "../utils/studioSaveDiagnostics";
import { DomEditSaveQueueOpenError } from "../utils/domEditSaveQueue";
Expand All @@ -8,6 +14,7 @@ import { wasAlreadyToasted } from "./domEditPersistFailure";

interface UseDomEditPositionPatchCommitParams {
activeCompPath: string | null;
previewIframeRef: RefObject<HTMLIFrameElement | null>;
persistDomEditOperations: PersistDomEditOperations;
showToast: (message: string, tone?: "error" | "info") => void;
}
Expand All @@ -20,20 +27,46 @@ type PositionPatchOptions = {
deferRender?: boolean;
};

/** A sealed frame shows the patch's own styles and attributes, unless a gesture's draft already does. */
function drawOnSealedFrame(
iframe: HTMLIFrameElement | null,
selection: DomEditSelection,
patches: PatchOperation[],
) {
if (previewDraftLive(selection.element)) return null;
const own = patches.filter((p) => p.childSelector === undefined && p.childIndex === undefined);
const entries = (type: PatchOperation["type"]) =>
own.filter((p) => p.type === type).map((p): [string, string | null] => [p.property, p.value]);
const styles = entries("inline-style");
const edit = editSealedSelection(iframe, selection, {
styles,
attributes: entries("attribute"),
});
const shown = styles.filter((entry): entry is [string, string] => entry[1] !== null);
if (edit) showSavedStylesOnStandIn(selection.element, shown);
return edit;
}

export function useDomEditPositionPatchCommit({
activeCompPath,
previewIframeRef,
persistDomEditOperations,
showToast,
}: UseDomEditPositionPatchCommitParams) {
return useCallback(
(selection: DomEditSelection, patches: PatchOperation[], options: PositionPatchOptions) => {
return persistDomEditOperations(selection, patches, {
label: options.label,
coalesceKey: options.coalesceKey,
coalesceMs: options.coalesceMs,
skipRefresh: options.skipRefresh ?? true,
deferRender: options.deferRender,
}).catch((error) => {
const sealedEdit = drawOnSealedFrame(previewIframeRef.current, selection, patches);
const saved = afterSealedDraw(sealedEdit, (drawn) =>
persistDomEditOperations(selection, patches, {
label: options.label,
coalesceKey: options.coalesceKey,
coalesceMs: options.coalesceMs,
skipRefresh: (options.skipRefresh ?? true) && drawn,
deferRender: options.deferRender,
}),
);
return Promise.resolve(saved).catch((error) => {
sealedEdit?.restore();
// The paused-save banner already explains this refusal. Rethrow so the
// caller reverts the preview instead of treating an unsaved edit as committed.
if (error instanceof DomEditSaveQueueOpenError) throw error;
Expand All @@ -53,6 +86,6 @@ export function useDomEditPositionPatchCommit({
throw error;
});
},
[activeCompPath, persistDomEditOperations, showToast],
[activeCompPath, persistDomEditOperations, previewIframeRef, showToast],
);
}
1 change: 1 addition & 0 deletions packages/studio/src/hooks/useDomGeometryCommit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ export function useDomGeometryCommit({
});
const commitPositionPatchToHtml = useDomEditPositionPatchCommit({
activeCompPath,
previewIframeRef: iframeRef,
persistDomEditOperations,
showToast,
});
Expand Down
Loading