Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
feat(studio): a host can save style edits on a selection through the Studio style commit (#4698)
Miguel Ángel0af671c6df8f
diff --git a/packages/studio/src/hooks/domStyleCommit.ts b/packages/studio/src/hooks/domStyleCommit.tsnew file mode 100644index 0000000000..190c570b39--- /dev/null+++ b/packages/studio/src/hooks/domStyleCommit.ts@@ -0,0 +1,129 @@+import type { PatchOperation } from "../utils/sourcePatcher";+import {+ isImageBackgroundValue,+ isManualGeometryStyleProperty,+ normalizeDomEditStyleValue,+} from "../utils/studioHelpers";+import {+ injectPreviewGoogleFont,+ injectPreviewImportedFont,+ ensureImportedFontFace,+} from "../utils/studioFontHelpers";+import {+ buildDomEditStylePatchOperation,+ findElementForSelection,+ getDomEditTargetKey,+ type DomEditSelection,+} from "../components/editor/domEditing";+import type { ImportedFontAsset } from "../components/editor/fontAssets";+import type { PersistDomEditOperations } from "./domEditCommitTypes";+import { reportDomEditPersistFailure } from "./domEditPersistFailure";+import {+ bumpDomEditCommitMapVersion,+ domEditCommitDeclined,+ runReportedDomEditCommit,+ type DomEditCommitOutcome,+} from "./domEditCommitRunner";++const IMAGE_BACKGROUND_FIT: Array<[string, string]> = [+ ["background-position", "center"],+ ["background-repeat", "no-repeat"],+ ["background-size", "contain"],+];++export interface DomStyleCommitContext {+ activeCompPath: string | null;+ previewIframeRef: React.RefObject<HTMLIFrameElement | null>;+ persistDomEditOperations: PersistDomEditOperations;+ showToast: (message: string, tone?: "error" | "info") => void;+ /** Latest-commit versions per target and property set; keep one map per caller. */+ versions: Map<string, symbol>;+ resolveImportedFontAsset?: (fontFamilyValue: string) => ImportedFontAsset | null;+ resync?: (selection: DomEditSelection) => void;+}++/** Applies inline styles live and saves them as one source patch and one undo step. */+// fallow-ignore-next-line complexity+export async function commitDomStyles(+ context: DomStyleCommitContext,+ selection: DomEditSelection,+ styles: Record<string, string>,+): Promise<DomEditCommitOutcome> {+ const entries = Object.entries(styles);+ if (entries.length === 0) return domEditCommitDeclined("no-selection");+ if (entries.some(([property]) => isManualGeometryStyleProperty(property)))+ return domEditCommitDeclined("geometry-property");+ if (!selection.capabilities.canEditStyles) return domEditCommitDeclined("styles-not-editable");++ const { activeCompPath, previewIframeRef, persistDomEditOperations, showToast } = context;+ // One version per element and property, so a failed save never reverts a later edit's property.+ const targetKey = getDomEditTargetKey(selection);+ const owned = entries.map(([property]) => ({+ property,+ isLatest: bumpDomEditCommitMapVersion(context.versions, `${targetKey}:${property}`),+ }));+ const ownsAny = () => owned.some(({ isLatest }) => isLatest());+ const fontFamily = styles["font-family"];+ const importedFont =+ fontFamily !== undefined ? (context.resolveImportedFontAsset?.(fontFamily) ?? null) : null;+ const doc = previewIframeRef.current?.contentDocument;+ const operations: PatchOperation[] = [];+ const liveStyles: Array<[string, string]> = [];+ for (const [property, value] of entries) {+ const normalized = normalizeDomEditStyleValue(property, value);+ operations.push(buildDomEditStylePatchOperation(property, normalized));+ liveStyles.push([property, normalized]);+ if (property === "background-image" && isImageBackgroundValue(value)) {+ for (const [fit, fitValue] of IMAGE_BACKGROUND_FIT) {+ if (fit in styles) continue;+ operations.push(buildDomEditStylePatchOperation(fit, fitValue));+ liveStyles.push([fit, fitValue]);+ }+ }+ }+ let editedElement: HTMLElement | null = null;+ const previousInline = new Map<string, string>();++ return runReportedDomEditCommit({+ capture: () => {+ const el = doc ? findElementForSelection(doc, selection, activeCompPath) : null;+ if (!el) return;+ editedElement = el;+ for (const [property] of entries)+ previousInline.set(property, el.style.getPropertyValue(property));+ },+ apply: () => {+ if (!editedElement) return;+ for (const [property, value] of liveStyles) editedElement.style.setProperty(property, value);+ if (fontFamily !== undefined && doc) {+ injectPreviewGoogleFont(doc, fontFamily);+ if (importedFont) injectPreviewImportedFont(doc, importedFont);+ }+ },+ persist: () =>+ persistDomEditOperations(selection, operations, {+ label: "Edit layer style",+ // Inline styles are already live, so a reload would only blank the preview.+ skipRefresh: true,+ prepareContent: importedFont+ ? (html, sourceFile) => ensureImportedFontFace(html, importedFont, sourceFile)+ : undefined,+ }),+ shouldRevert: ownsAny,+ revert: () => {+ const el = editedElement;+ if (!el) return;+ // ponytail: background-image fit styles are not reverted here.+ for (const { property, isLatest } of owned) {+ const previous = previousInline.get(property);+ if (previous === undefined || !isLatest()) continue;+ if (previous === "") el.style.removeProperty(property);+ else el.style.setProperty(property, previous);+ }+ },+ onError: (error) => reportDomEditPersistFailure(selection, operations, error, showToast),+ shouldResync: ownsAny,+ resync: () => context.resync?.(selection),+ onFinally: () => owned.forEach(({ isLatest }) => isLatest.release()),+ });+}diff --git a/packages/studio/src/hooks/useDomEditCommits.ts b/packages/studio/src/hooks/useDomEditCommits.tsindex 680d3d0222..8726a95822 100644--- a/packages/studio/src/hooks/useDomEditCommits.ts+++ b/packages/studio/src/hooks/useDomEditCommits.ts@@ -1,20 +1,15 @@import { buildProjectApiPath } from "../utils/projectRouting";-import { useCallback, useRef } from "react";+import { useCallback } from "react";import { findUnsafeDomPatchValues } from "@hyperframes/core/studio-api/finite-mutation";import { FONT_EXT } from "../utils/mediaTypes";--import { trackStudioEvent } from "../utils/studioTelemetry";import { primaryFontFamilyValue } from "../utils/studioFontHelpers";import { StudioSaveHttpError, trackStudioSaveFailure } from "../utils/studioSaveDiagnostics";-import { buildDomEditPatchTarget, type DomEditSelection } from "../components/editor/domEditing";+import type { DomEditSelection } from "../components/editor/domEditing";import { fontFamilyFromAssetPath, type ImportedFontAsset } from "../components/editor/fontAssets";-import type { CommitDomEditPatchBatches, PersistDomEditOperations } from "./domEditCommitTypes";+import type { CommitDomEditPatchBatches } from "./domEditCommitTypes";import type { PatchOperation } from "../utils/sourcePatcher";-import {- DomEditPersistUnsafeValueError,- DomEditPersistUnresolvableError,- warnDomEditPersistNoOp,-} from "./domEditPersistFailure";+import { DomEditPersistUnsafeValueError } from "./domEditPersistFailure";+import { useDomEditPersist, type RecordEditInput } from "./useDomEditPersist";import { useDomEditPositionPatchCommit } from "./useDomEditPositionPatchCommit";import { useDomEditTextCommits } from "./useDomEditTextCommits";import { useDomGeometryCommits } from "./useDomGeometryCommits";@@ -24,19 +19,9 @@ import {batchesAreInlineStyleOnly,formatUnsafeFieldList,patchElementBatches,- postPatchElement,- writePreparedContent,} from "./useDomEditCommitsHelpers";import type { CutoverResult } from "../utils/sdkCutover";-import { reseekPreviewRuntime } from "./timelineTrackVisibility";import { serializeStudioFileMutations } from "../utils/studioFileMutationCoordinator";-import { readProjectFileContent } from "../utils/studioFileHistory";-interface RecordEditInput {- label: string;- coalesceKey?: string;- coalesceMs?: number;- files: Record<string, { before: string; after: string }>;-}export interface UseDomEditCommitsParams {activeCompPath: string | null;@@ -132,168 +117,18 @@ export function useDomEditCommits({[fileTree, projectId, importedFontAssetsRef],);- const reportedUnresolvableRef = useRef(new Set<string>());-- // fallow-ignore-next-line complexity- const performPersistDomEditOperations = useCallback(- // fallow-ignore-next-line complexity- async (- selection: DomEditSelection,- operations: PatchOperation[],- options: Parameters<PersistDomEditOperations>[2],- expectedProjectId: string,- ) => {- if (projectIdRef.current !== expectedProjectId) {- throw new Error("Active project changed before the edit could be saved");- }- const pid = expectedProjectId;- if (options?.shouldSave && !options.shouldSave()) return;-- const targetPath = selection.sourceFile || activeCompPath || "index.html";- const completePersistence = <T>(result: T, changed: boolean): T => {- if (options?.skipRefresh && changed) reseekPreviewRuntime(previewIframeRef.current);- return result;- };-- const readTarget = async (): Promise<string | null> => {- const content = await readProjectFileContent(pid, targetPath);- if (projectIdRef.current !== expectedProjectId) {- throw new Error("Active project changed before the edit could be saved");- }- return options?.shouldSave && !options.shouldSave() ? null : content;- };-- // Validate layout values BEFORE any persist path runs. The SDK cutover- // path (onTrySdkPersist) returns early on success, so leaving this check- // after it let invalid numeric values bypass the guard whenever the- // cutover flag was on.- const patchTarget = buildDomEditPatchTarget(selection);- const patchBody = { target: patchTarget, operations };- const unsafeFields = findUnsafeDomPatchValues(patchBody);- if (unsafeFields.length > 0) {- const fields = formatUnsafeFieldList(unsafeFields);- showToast("Couldn't save edit because it contains invalid layout values", "error");- throw new DomEditPersistUnsafeValueError(`DOM patch contains unsafe values: ${fields}`, {- alreadyToasted: true,- });- }-- // Skip the SDK path when prepareContent is set (e.g. @font-face injection- // for a custom font): sdkCutoverPersist serializes only the patched DOM- // and would drop the injected content. Let the server path run prepareContent.- // The SDK joins the file queue itself and re-reads there; this read is only its fallback.- if (onTrySdkPersist && !options?.prepareContent) {- const originalContent = await readTarget();- if (originalContent === null) return;- const cutover = await onTrySdkPersist(selection, operations, originalContent, targetPath, {- label: options?.label,- coalesceKey: options?.coalesceKey,- skipRefresh: options?.skipRefresh,- });- if (cutover.status === "failed") throw cutover.error;- if (cutover.status === "committed") {- // SDK handled it — its in-memory doc is already current, so do NOT- // forceReload (that would echo-reload the session we just wrote).- return completePersistence(- { sourceFile: targetPath, version: cutover.version, changed: true },- true,- );- }- }-- const history = {- label: options?.label ?? "Edit layer",- coalesceKey: options?.coalesceKey,- coalesceMs: options?.coalesceMs,- };- const prepare = options?.prepareContent;- // Read, server patch, follow-up write and history hold the file's queue, so no save lands between them.- const saved = await serializeStudioFileMutations(writeProjectFile, [targetPath], async () => {- const originalContent = await readTarget();- if (originalContent === null) return null;- const patchData = await postPatchElement(pid, targetPath, patchBody, showToast);- if (!patchData.changed) return { patchData, patchedContent: null, finalContent: null };-- const patchedContent =- typeof patchData.content === "string" ? patchData.content : originalContent;- const finalContent = prepare- ? await writePreparedContent(- targetPath,- patchedContent,- prepare,- writeProjectFile,- showToast,- )- : patchedContent;-- await editHistory.recordEdit({- ...history,- files: { [targetPath]: { before: originalContent, after: finalContent } },- });- return { patchData, patchedContent, finalContent };- });- if (saved === null) return;- const { patchData, patchedContent, finalContent } = saved;-- if (finalContent === null) {- if (patchData.matched === false) {- const targetKey = selection.selector ?? selection.id ?? "selection";- if (!reportedUnresolvableRef.current.has(targetKey)) {- reportedUnresolvableRef.current.add(targetKey);- trackStudioEvent("save_skipped_unresolvable", {- target_id: selection.id ?? undefined,- target_selector: selection.selector ?? undefined,- target_source_file: selection.sourceFile ?? undefined,- composition: activeCompPath ?? undefined,- });- }- throw new DomEditPersistUnresolvableError(targetPath);- }- warnDomEditPersistNoOp(selection, operations);- return completePersistence(- typeof patchData.path === "string" && typeof patchData.version === "string"- ? { sourceFile: patchData.path, version: patchData.version, changed: false }- : undefined,- false,- );- }- forceReloadSdkSession?.();-- if (!options?.skipRefresh) {- reloadPreview();- }- return completePersistence(- finalContent === patchedContent &&- typeof patchData.path === "string" &&- typeof patchData.version === "string"- ? { sourceFile: patchData.path, version: patchData.version, changed: true }- : undefined,- true,- );- },- [- activeCompPath,- editHistory,- writeProjectFile,- projectIdRef,- reloadPreview,- showToast,- forceReloadSdkSession,- onTrySdkPersist,- previewIframeRef,- ],- );-- const persistDomEditOperations: PersistDomEditOperations = useCallback(- (selection, operations, options) => {- const expectedProjectId = projectIdRef.current;- if (!expectedProjectId) return Promise.reject(new Error("No active project"));- return queueDomEditSave(() =>- performPersistDomEditOperations(selection, operations, options, expectedProjectId),- );- },- [performPersistDomEditOperations, projectIdRef, queueDomEditSave],- );+ const persistDomEditOperations = useDomEditPersist({+ activeCompPath,+ previewIframeRef,+ showToast,+ queueDomEditSave,+ writeProjectFile,+ editHistory,+ projectIdRef,+ reloadPreview,+ forceReloadSdkSession,+ onTrySdkPersist,+ });const commitDomEditPatchBatches: CommitDomEditPatchBatches = useCallback((batches, options) => {diff --git a/packages/studio/src/hooks/useDomEditPersist.ts b/packages/studio/src/hooks/useDomEditPersist.tsnew file mode 100644index 0000000000..08a75c69c2--- /dev/null+++ b/packages/studio/src/hooks/useDomEditPersist.ts@@ -0,0 +1,225 @@+import { useCallback, useRef } from "react";+import { findUnsafeDomPatchValues } from "@hyperframes/core/studio-api/finite-mutation";+import { trackStudioEvent } from "../utils/studioTelemetry";+import { buildDomEditPatchTarget, type DomEditSelection } from "../components/editor/domEditing";+import type { PersistDomEditOperations } from "./domEditCommitTypes";+import type { PatchOperation } from "../utils/sourcePatcher";+import {+ DomEditPersistUnsafeValueError,+ DomEditPersistUnresolvableError,+ warnDomEditPersistNoOp,+} from "./domEditPersistFailure";+import {+ formatUnsafeFieldList,+ postPatchElement,+ writePreparedContent,+} from "./useDomEditCommitsHelpers";+import type { CutoverResult } from "../utils/sdkCutover";+import { reseekPreviewRuntime } from "./timelineTrackVisibility";+import { serializeStudioFileMutations } from "../utils/studioFileMutationCoordinator";+import { readProjectFileContent } from "../utils/studioFileHistory";++export interface RecordEditInput {+ label: string;+ coalesceKey?: string;+ coalesceMs?: number;+ files: Record<string, { before: string; after: string }>;+}++export interface UseDomEditPersistParams {+ activeCompPath: string | null;+ previewIframeRef: React.MutableRefObject<HTMLIFrameElement | null>;+ showToast: (message: string, tone?: "error" | "info") => void;+ queueDomEditSave: <T>(save: () => Promise<T>) => Promise<T>;+ writeProjectFile: (path: string, content: string, expectedContent?: string) => Promise<void>;+ editHistory: { recordEdit: (entry: RecordEditInput) => Promise<void> };+ projectIdRef: React.MutableRefObject<string | null>;+ reloadPreview: () => void;+ forceReloadSdkSession?: () => void;+ onTrySdkPersist?: (+ selection: DomEditSelection,+ operations: PatchOperation[],+ originalContent: string,+ targetPath: string,+ options?: { label?: string; coalesceKey?: string; skipRefresh?: boolean },+ ) => Promise<CutoverResult>;+}++/** Studio's one DOM-edit writer: patches the source file, records history, then reloads or reseeks the preview. */+export function useDomEditPersist({+ activeCompPath,+ previewIframeRef,+ showToast,+ queueDomEditSave,+ writeProjectFile,+ editHistory,+ projectIdRef,+ reloadPreview,+ forceReloadSdkSession,+ onTrySdkPersist,+}: UseDomEditPersistParams): PersistDomEditOperations {+ const reportedUnresolvableRef = useRef(new Set<string>());++ // fallow-ignore-next-line complexity+ const performPersistDomEditOperations = useCallback(+ // fallow-ignore-next-line complexity+ async (+ selection: DomEditSelection,+ operations: PatchOperation[],+ options: Parameters<PersistDomEditOperations>[2],+ expectedProjectId: string,+ ) => {+ if (projectIdRef.current !== expectedProjectId) {+ throw new Error("Active project changed before the edit could be saved");+ }+ const pid = expectedProjectId;+ if (options?.shouldSave && !options.shouldSave()) return;++ const targetPath = selection.sourceFile || activeCompPath || "index.html";+ const completePersistence = <T>(result: T, changed: boolean): T => {+ if (options?.skipRefresh && changed) reseekPreviewRuntime(previewIframeRef.current);+ return result;+ };++ const readTarget = async (): Promise<string | null> => {+ const content = await readProjectFileContent(pid, targetPath);+ if (projectIdRef.current !== expectedProjectId) {+ throw new Error("Active project changed before the edit could be saved");+ }+ return options?.shouldSave && !options.shouldSave() ? null : content;+ };++ // Validate layout values BEFORE any persist path runs. The SDK cutover+ // path (onTrySdkPersist) returns early on success, so leaving this check+ // after it let invalid numeric values bypass the guard whenever the+ // cutover flag was on.+ const patchTarget = buildDomEditPatchTarget(selection);+ const patchBody = { target: patchTarget, operations };+ const unsafeFields = findUnsafeDomPatchValues(patchBody);+ if (unsafeFields.length > 0) {+ const fields = formatUnsafeFieldList(unsafeFields);+ showToast("Couldn't save edit because it contains invalid layout values", "error");+ throw new DomEditPersistUnsafeValueError(`DOM patch contains unsafe values: ${fields}`, {+ alreadyToasted: true,+ });+ }++ // Skip the SDK path when prepareContent is set (e.g. @font-face injection+ // for a custom font): sdkCutoverPersist serializes only the patched DOM+ // and would drop the injected content. Let the server path run prepareContent.+ // The SDK joins the file queue itself and re-reads there; this read is only its fallback.+ if (onTrySdkPersist && !options?.prepareContent) {+ const originalContent = await readTarget();+ if (originalContent === null) return;+ const cutover = await onTrySdkPersist(selection, operations, originalContent, targetPath, {+ label: options?.label,+ coalesceKey: options?.coalesceKey,+ skipRefresh: options?.skipRefresh,+ });+ if (cutover.status === "failed") throw cutover.error;+ if (cutover.status === "committed") {+ // SDK handled it — its in-memory doc is already current, so do NOT+ // forceReload (that would echo-reload the session we just wrote).+ return completePersistence(+ { sourceFile: targetPath, version: cutover.version, changed: true },+ true,+ );+ }+ }++ const history = {+ label: options?.label ?? "Edit layer",+ coalesceKey: options?.coalesceKey,+ coalesceMs: options?.coalesceMs,+ };+ const prepare = options?.prepareContent;+ // Read, server patch, follow-up write and history hold the file's queue, so no save lands between them.+ const saved = await serializeStudioFileMutations(writeProjectFile, [targetPath], async () => {+ const originalContent = await readTarget();+ if (originalContent === null) return null;+ const patchData = await postPatchElement(pid, targetPath, patchBody, showToast);+ if (!patchData.changed) return { patchData, patchedContent: null, finalContent: null };++ const patchedContent =+ typeof patchData.content === "string" ? patchData.content : originalContent;+ const finalContent = prepare+ ? await writePreparedContent(+ targetPath,+ patchedContent,+ prepare,+ writeProjectFile,+ showToast,+ )+ : patchedContent;++ await editHistory.recordEdit({+ ...history,+ files: { [targetPath]: { before: originalContent, after: finalContent } },+ });+ return { patchData, patchedContent, finalContent };+ });+ if (saved === null) return;+ const { patchData, patchedContent, finalContent } = saved;++ if (finalContent === null) {+ if (patchData.matched === false) {+ const targetKey = selection.selector ?? selection.id ?? "selection";+ if (!reportedUnresolvableRef.current.has(targetKey)) {+ reportedUnresolvableRef.current.add(targetKey);+ trackStudioEvent("save_skipped_unresolvable", {+ target_id: selection.id ?? undefined,+ target_selector: selection.selector ?? undefined,+ target_source_file: selection.sourceFile ?? undefined,+ composition: activeCompPath ?? undefined,+ });+ }+ throw new DomEditPersistUnresolvableError(targetPath);+ }+ warnDomEditPersistNoOp(selection, operations);+ return completePersistence(+ typeof patchData.path === "string" && typeof patchData.version === "string"+ ? { sourceFile: patchData.path, version: patchData.version, changed: false }+ : undefined,+ false,+ );+ }+ forceReloadSdkSession?.();++ if (!options?.skipRefresh) {+ reloadPreview();+ }+ return completePersistence(+ finalContent === patchedContent &&+ typeof patchData.path === "string" &&+ typeof patchData.version === "string"+ ? { sourceFile: patchData.path, version: patchData.version, changed: true }+ : undefined,+ true,+ );+ },+ [+ activeCompPath,+ editHistory,+ writeProjectFile,+ projectIdRef,+ reloadPreview,+ showToast,+ forceReloadSdkSession,+ onTrySdkPersist,+ previewIframeRef,+ ],+ );++ const persistDomEditOperations: PersistDomEditOperations = useCallback(+ (selection, operations, options) => {+ const expectedProjectId = projectIdRef.current;+ if (!expectedProjectId) return Promise.reject(new Error("No active project"));+ return queueDomEditSave(() =>+ performPersistDomEditOperations(selection, operations, options, expectedProjectId),+ );+ },+ [performPersistDomEditOperations, projectIdRef, queueDomEditSave],+ );++ return persistDomEditOperations;+}diff --git a/packages/studio/src/hooks/useDomEditTextCommits.ts b/packages/studio/src/hooks/useDomEditTextCommits.tsindex 0d771a82e1..83c3af5c90 100644--- a/packages/studio/src/hooks/useDomEditTextCommits.ts+++ b/packages/studio/src/hooks/useDomEditTextCommits.ts@@ -1,10 +1,5 @@import { useCallback, useRef } from "react";-import type { PatchOperation } from "../utils/sourcePatcher";-import {- isImageBackgroundValue,- isManualGeometryStyleProperty,- normalizeDomEditStyleValue,-} from "../utils/studioHelpers";+import { normalizeDomEditStyleValue } from "../utils/studioHelpers";import {injectPreviewGoogleFont,injectPreviewImportedFont,@@ -12,7 +7,6 @@ import {} from "../utils/studioFontHelpers";import {buildDomEditRichTextPatchOperation,- buildDomEditStylePatchOperation,findElementForSelection,getDomEditTargetKey,isTextEditableSelection,@@ -32,6 +26,7 @@ import {runReportedDomEditCommit,type DomEditCommitOutcome,} from "./domEditCommitRunner";+import { commitDomStyles } from "./domStyleCommit";import { useDomEditAttributeCommits } from "./useDomEditAttributeCommits";import type { InlineTextEditCommit } from "./useInlineTextEdit";@@ -70,24 +65,6 @@ function ownsCurrentPreviewElement(return element === selection.element && element.ownerDocument === document;}-function buildDomStyleCommitOperations(- property: string,- value: string,- isImageBackgroundCommit: boolean,-): PatchOperation[] {- const operations: PatchOperation[] = [- buildDomEditStylePatchOperation(property, normalizeDomEditStyleValue(property, value)),- ];- if (isImageBackgroundCommit) {- operations.push(- buildDomEditStylePatchOperation("background-position", "center"),- buildDomEditStylePatchOperation("background-repeat", "no-repeat"),- buildDomEditStylePatchOperation("background-size", "contain"),- );- }- return operations;-}-async function resyncDomTextSelectionFromPreview(doc: Document | null | undefined,selection: DomEditSelection,@@ -138,81 +115,20 @@ export function useDomEditTextCommits({});const handleDomStyleCommitForSelection = useCallback(- async (- selection: DomEditSelection,- property: string,- value: string,- ): Promise<DomEditCommitOutcome> => {- if (isManualGeometryStyleProperty(property))- return domEditCommitDeclined("geometry-property");- if (!selection.capabilities.canEditStyles) {- return domEditCommitDeclined("styles-not-editable");- }- const styleCommitKey = `${getDomEditTargetKey(selection)}:${property}`;- const isLatestStyleCommit = bumpDomEditCommitMapVersion(- domStyleCommitVersionRef.current,- styleCommitKey,- );- const importedFont = property === "font-family" ? resolveImportedFontAsset(value) : null;- const iframe = previewIframeRef.current;- const doc = iframe?.contentDocument;- const normalizedValue = normalizeDomEditStyleValue(property, value);- const isImageBackgroundCommit =- property === "background-image" && isImageBackgroundValue(value);- let editedElement: HTMLElement | null = null;- let previousInlineValue: string | null = null;- const operations = buildDomStyleCommitOperations(property, value, isImageBackgroundCommit);- // Inline-style commits never full-reload the preview (that blanks the iframe- // until it re-renders): the live element was already mutated optimistically in- // apply(). z-index is no exception — setting `element.style.zIndex` restacks the- // element in-browser immediately, so a reload would only cost a black blink.- const skipRefresh = true;-- return runReportedDomEditCommit({- capture: () => {- if (!doc) return;- const el = findElementForSelection(doc, selection, activeCompPath);- if (!el) return;- editedElement = el;- previousInlineValue = el.style.getPropertyValue(property);- },- apply: () => {- if (!editedElement) return;- editedElement.style.setProperty(property, normalizedValue);- if (property === "font-family" && doc) {- injectPreviewGoogleFont(doc, value);- if (importedFont) injectPreviewImportedFont(doc, importedFont);- }- if (isImageBackgroundCommit) {- editedElement.style.setProperty("background-position", "center");- editedElement.style.setProperty("background-repeat", "no-repeat");- editedElement.style.setProperty("background-size", "contain");- }- },- persist: () =>- persistDomEditOperations(selection, operations, {- label: "Edit layer style",- skipRefresh,- prepareContent: importedFont- ? (html, sourceFile) => ensureImportedFontFace(html, importedFont, sourceFile)- : undefined,- }),- shouldRevert: () => isLatestStyleCommit(),- revert: () => {- if (!editedElement || previousInlineValue === null) return;- // ponytail: background-image side-effect styles are not reverted here.- if (previousInlineValue === "") {- editedElement.style.removeProperty(property);- } else {- editedElement.style.setProperty(property, previousInlineValue);- }+ (selection: DomEditSelection, property: string, value: string): Promise<DomEditCommitOutcome> =>+ commitDomStyles(+ {+ activeCompPath,+ previewIframeRef,+ persistDomEditOperations,+ showToast,+ versions: domStyleCommitVersionRef.current,+ resolveImportedFontAsset,+ resync: refreshDomEditSelectionFromPreview,},- onError: (error) => reportDomEditPersistFailure(selection, operations, error, showToast),- shouldResync: isLatestStyleCommit,- resync: () => refreshDomEditSelectionFromPreview(selection),- onFinally: isLatestStyleCommit.release,- });- },+ selection,+ { [property]: value },+ ),[activeCompPath,persistDomEditOperations,diff --git a/packages/studio/src/hooks/useDomStyleCommit.test.tsx b/packages/studio/src/hooks/useDomStyleCommit.test.tsxnew file mode 100644index 0000000000..5424e9f81e--- /dev/null+++ b/packages/studio/src/hooks/useDomStyleCommit.test.tsx@@ -0,0 +1,155 @@+// @vitest-environment happy-dom+import { act, createElement, useRef } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, describe, expect, it, vi } from "vitest";+import { useDomStyleCommit, type UseDomStyleCommitOptions } from "../index";+import { makeSelection } from "./domSelectionTestHarness";++Reflect.set(globalThis, "IS_REACT_ACT_ENVIRONMENT", true);++vi.mock("../utils/studioTelemetry", () => ({ trackStudioEvent: vi.fn() }));++const SOURCE = '<div id="card" style="color: red">Card</div>';++/** Each patch answers with the next status in `failures` (none left: success). */+function stubServer(failures: number[] = []) {+ const patches: unknown[] = [];+ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input instanceof Request ? input.url : input);+ const json = (body: unknown) =>+ new Response(JSON.stringify(body), { headers: { "content-type": "application/json" } });+ if (url.includes("/api/projects/p1/files/")) return json({ content: SOURCE });+ if (url.includes("/api/projects/p1/file-mutations/patch-element/")) {+ patches.push(JSON.parse(String(init?.body)));+ const status = failures.shift();+ if (status) return new Response(JSON.stringify({ error: "refused" }), { status });+ return json({+ ok: true,+ changed: true,+ matched: true,+ content: "<div>saved</div>",+ path: "index.html",+ version: "v2",+ });+ }+ throw new Error(`Unexpected fetch: ${url}`);+ }),+ );+ return patches;+}++function renderHost(options: Partial<UseDomStyleCommitOptions> = {}) {+ const iframe = document.createElement("iframe");+ document.body.append(iframe);+ const doc = iframe.contentDocument;+ if (!doc) throw new Error("Expected iframe document");+ doc.body.innerHTML = SOURCE;+ const element = doc.getElementById("card") as HTMLElement;+ const recordEdit = vi.fn(async () => {});+ const api: { current: ReturnType<typeof useDomStyleCommit> | null } = { current: null };+ function Host() {+ const iframeRef = useRef<HTMLIFrameElement | null>(iframe);+ api.current = useDomStyleCommit({+ projectId: "p1",+ iframeRef,+ writeProjectFile: vi.fn(async () => {}),+ recordEdit,+ ...options,+ });+ return null;+ }+ const root = createRoot(document.createElement("div"));+ act(() => root.render(createElement(Host)));+ const hook = () => {+ if (!api.current) throw new Error("Expected the hook to render");+ return api.current;+ };+ return { element, recordEdit, hook, unmount: () => act(() => root.unmount()) };+}++afterEach(() => {+ vi.unstubAllGlobals();+ document.body.innerHTML = "";+});++describe("useDomStyleCommit, from the package entry", () => {+ it("applies several properties live and saves them as one patch and one undo step", async () => {+ const patches = stubServer();+ const { element, recordEdit, hook, unmount } = renderHost();++ const outcome = await hook().commitStyle(makeSelection("card", element), {+ color: "blue",+ "font-size": "40px",+ });+ await hook().waitForPendingSaves();++ expect(outcome.ok).toBe(true);+ expect(element.style.color).toBe("blue");+ expect(element.style.fontSize).toBe("40px");+ expect(patches).toHaveLength(1);+ expect((patches[0] as { operations: unknown[] }).operations).toHaveLength(2);+ expect(recordEdit).toHaveBeenCalledTimes(1);+ expect(recordEdit).toHaveBeenCalledWith(expect.objectContaining({ label: "Edit layer style" }));+ unmount();+ });++ it("refuses geometry and read-only selections with a reason, and writes nothing", async () => {+ const patches = stubServer();+ const { element, hook, unmount } = renderHost();+ const selection = makeSelection("card", element);++ await expect(hook().commitStyle(selection, { width: "10px" })).resolves.toEqual({+ ok: false,+ reason: "geometry-property",+ });+ const readOnly = {+ ...selection,+ capabilities: { ...selection.capabilities, canEditStyles: false },+ };+ await expect(hook().commitStyle(readOnly, { color: "blue" })).resolves.toEqual({+ ok: false,+ reason: "styles-not-editable",+ });+ expect(patches).toHaveLength(0);+ expect(element.style.color).toBe("red");+ unmount();+ });++ it("never lets a failed save revert a later edit's property", async () => {+ stubServer([500]);+ const { element, hook, unmount } = renderHost();+ const selection = makeSelection("card", element);++ const first = hook().commitStyle(selection, { color: "blue" });+ const second = hook().commitStyle(selection, { color: "green", "font-size": "40px" });++ expect((await first).ok).toBe(false);+ expect((await second).ok).toBe(true);+ expect(element.style.color).toBe("green");+ unmount();+ });++ it("saves again after a conflict paused the queue", async () => {+ stubServer([409]);+ const { element, hook, unmount } = renderHost();+ const selection = makeSelection("card", element);++ expect((await hook().commitStyle(selection, { color: "blue" })).ok).toBe(false);+ expect((await hook().commitStyle(selection, { color: "green" })).ok).toBe(true);+ unmount();+ });++ it("refuses without a project", async () => {+ stubServer();+ const { element, hook, unmount } = renderHost({ projectId: null });+ await expect(+ hook().commitStyle(makeSelection("card", element), { color: "blue" }),+ ).resolves.toEqual({+ ok: false,+ reason: "no-project",+ });+ unmount();+ });+});diff --git a/packages/studio/src/hooks/useDomStyleCommit.ts b/packages/studio/src/hooks/useDomStyleCommit.tsnew file mode 100644index 0000000000..98bc82e5dd--- /dev/null+++ b/packages/studio/src/hooks/useDomStyleCommit.ts@@ -0,0 +1,74 @@+import { useCallback, useMemo, useRef, useState } from "react";+import type { DomEditSelection } from "../components/editor/domEditing";+import { createDomEditSaveQueue, type DomEditSaveDrainResult } from "../utils/domEditSaveQueue";+import type { DomEditCommitOutcome } from "./domEditCommitRunner";+import { commitDomStyles } from "./domStyleCommit";+import { useDomEditPersist, type RecordEditInput } from "./useDomEditPersist";+import { useMountEffect } from "./useMountEffect";++export interface UseDomStyleCommitOptions {+ projectId: string | null;+ /** The preview the host already runs: the style applies there live, and it reseeks after a save. */+ iframeRef: React.MutableRefObject<HTMLIFrameElement | null>;+ /** The same function objects the host gives the timeline, so there is one writer and one undo list. */+ writeProjectFile: (path: string, content: string, expectedContent?: string) => Promise<void>;+ recordEdit: (entry: RecordEditInput) => Promise<void>;+ activeCompPath?: string | null;+ showToast?: (message: string, tone?: "error" | "info") => void;+}++const noop = () => {};++/** Saves style edits on a selection through Studio's own style commit, for a host without the editor. */+export function useDomStyleCommit({+ projectId,+ iframeRef,+ writeProjectFile,+ recordEdit,+ activeCompPath = null,+ showToast = noop,+}: UseDomStyleCommitOptions): {+ commitStyle: (+ selection: DomEditSelection,+ styles: Record<string, string>,+ ) => Promise<DomEditCommitOutcome>;+ waitForPendingSaves: () => Promise<DomEditSaveDrainResult>;+} {+ const projectIdRef = useRef(projectId);+ projectIdRef.current = projectId;+ const [queue] = useState(createDomEditSaveQueue);+ useMountEffect(() => () => queue.destroy());+ const versions = useRef(new Map<string, symbol>()).current;+ const editHistory = useMemo(() => ({ recordEdit }), [recordEdit]);+ const persistDomEditOperations = useDomEditPersist({+ activeCompPath,+ previewIframeRef: iframeRef,+ showToast,+ queueDomEditSave: queue.enqueue,+ writeProjectFile,+ editHistory,+ projectIdRef,+ reloadPreview: noop,+ });+ const commitStyle = useCallback(+ (selection: DomEditSelection, styles: Record<string, string>) => {+ // Each call is the user's own retry, so a pause left by an earlier failed save never blocks it.+ queue.reset();+ return projectIdRef.current+ ? commitDomStyles(+ {+ activeCompPath,+ previewIframeRef: iframeRef,+ persistDomEditOperations,+ showToast,+ versions,+ },+ selection,+ styles,+ )+ : Promise.resolve<DomEditCommitOutcome>({ ok: false, reason: "no-project" });+ },+ [activeCompPath, iframeRef, persistDomEditOperations, queue, showToast, versions],+ );+ return { commitStyle, waitForPendingSaves: queue.waitForIdle };+}diff --git a/packages/studio/src/index.ts b/packages/studio/src/index.tsindex 9b02856a9d..ab477d2ff4 100644--- a/packages/studio/src/index.ts+++ b/packages/studio/src/index.ts@@ -167,7 +167,7 @@ export type { AudioMeterStripProps } from "./components/nle/AudioMeterStrip";export { useClipboard } from "./hooks/useClipboard";export type { UseClipboardOptions } from "./hooks/useClipboard";-// DOM editing: the canvas session, persistence and overlay, for a host outside EditorShell.+// DOM editing for a host outside EditorShell; useDomStyleCommit saves styles without the session.export { useDomEditSession } from "./hooks/useDomEditSession";export type { UseDomEditSessionParams } from "./hooks/useDomEditSession";export { usePreviewPersistence } from "./hooks/usePreviewPersistence";@@ -177,6 +177,10 @@ export { PreviewReadOnlyProvider } from "./components/editor/previewReadOnlyContexport { ConnectedDomEditOverlay } from "./components/editor/ConnectedDomEditOverlay";export type { ConnectedDomEditOverlayProps } from "./components/editor/ConnectedDomEditOverlay";export type { DomEditCapabilities, DomEditSelection } from "./components/editor/domEditingTypes";+export { useDomStyleCommit } from "./hooks/useDomStyleCommit";+export type { UseDomStyleCommitOptions } from "./hooks/useDomStyleCommit";+export type { DomEditCommitDeclineReason, DomEditCommitOutcome } from "./hooks/domEditCommitRunner";+export { resolveDomEditSelection } from "./components/editor/domEditingLayers";export {playSeamTransitionLoop,