Skip to content

Commit 0af671c

Browse files
feat(studio): a host can save style edits on a selection through the Studio style commit (#4698)
* feat(studio): a host can save style edits on a selection through Studio's own style commit * fix(studio): drop an import the moved writer no longer needs * fix(studio): host style saves recover after a failure and never revert a later edit
1 parent a519927 commit 0af671c

7 files changed

Lines changed: 620 additions & 282 deletions

File tree

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
import type { PatchOperation } from "../utils/sourcePatcher";
2+
import {
3+
isImageBackgroundValue,
4+
isManualGeometryStyleProperty,
5+
normalizeDomEditStyleValue,
6+
} from "../utils/studioHelpers";
7+
import {
8+
injectPreviewGoogleFont,
9+
injectPreviewImportedFont,
10+
ensureImportedFontFace,
11+
} from "../utils/studioFontHelpers";
12+
import {
13+
buildDomEditStylePatchOperation,
14+
findElementForSelection,
15+
getDomEditTargetKey,
16+
type DomEditSelection,
17+
} from "../components/editor/domEditing";
18+
import type { ImportedFontAsset } from "../components/editor/fontAssets";
19+
import type { PersistDomEditOperations } from "./domEditCommitTypes";
20+
import { reportDomEditPersistFailure } from "./domEditPersistFailure";
21+
import {
22+
bumpDomEditCommitMapVersion,
23+
domEditCommitDeclined,
24+
runReportedDomEditCommit,
25+
type DomEditCommitOutcome,
26+
} from "./domEditCommitRunner";
27+
28+
const IMAGE_BACKGROUND_FIT: Array<[string, string]> = [
29+
["background-position", "center"],
30+
["background-repeat", "no-repeat"],
31+
["background-size", "contain"],
32+
];
33+
34+
export interface DomStyleCommitContext {
35+
activeCompPath: string | null;
36+
previewIframeRef: React.RefObject<HTMLIFrameElement | null>;
37+
persistDomEditOperations: PersistDomEditOperations;
38+
showToast: (message: string, tone?: "error" | "info") => void;
39+
/** Latest-commit versions per target and property set; keep one map per caller. */
40+
versions: Map<string, symbol>;
41+
resolveImportedFontAsset?: (fontFamilyValue: string) => ImportedFontAsset | null;
42+
resync?: (selection: DomEditSelection) => void;
43+
}
44+
45+
/** Applies inline styles live and saves them as one source patch and one undo step. */
46+
// fallow-ignore-next-line complexity
47+
export async function commitDomStyles(
48+
context: DomStyleCommitContext,
49+
selection: DomEditSelection,
50+
styles: Record<string, string>,
51+
): Promise<DomEditCommitOutcome> {
52+
const entries = Object.entries(styles);
53+
if (entries.length === 0) return domEditCommitDeclined("no-selection");
54+
if (entries.some(([property]) => isManualGeometryStyleProperty(property)))
55+
return domEditCommitDeclined("geometry-property");
56+
if (!selection.capabilities.canEditStyles) return domEditCommitDeclined("styles-not-editable");
57+
58+
const { activeCompPath, previewIframeRef, persistDomEditOperations, showToast } = context;
59+
// One version per element and property, so a failed save never reverts a later edit's property.
60+
const targetKey = getDomEditTargetKey(selection);
61+
const owned = entries.map(([property]) => ({
62+
property,
63+
isLatest: bumpDomEditCommitMapVersion(context.versions, `${targetKey}:${property}`),
64+
}));
65+
const ownsAny = () => owned.some(({ isLatest }) => isLatest());
66+
const fontFamily = styles["font-family"];
67+
const importedFont =
68+
fontFamily !== undefined ? (context.resolveImportedFontAsset?.(fontFamily) ?? null) : null;
69+
const doc = previewIframeRef.current?.contentDocument;
70+
const operations: PatchOperation[] = [];
71+
const liveStyles: Array<[string, string]> = [];
72+
for (const [property, value] of entries) {
73+
const normalized = normalizeDomEditStyleValue(property, value);
74+
operations.push(buildDomEditStylePatchOperation(property, normalized));
75+
liveStyles.push([property, normalized]);
76+
if (property === "background-image" && isImageBackgroundValue(value)) {
77+
for (const [fit, fitValue] of IMAGE_BACKGROUND_FIT) {
78+
if (fit in styles) continue;
79+
operations.push(buildDomEditStylePatchOperation(fit, fitValue));
80+
liveStyles.push([fit, fitValue]);
81+
}
82+
}
83+
}
84+
let editedElement: HTMLElement | null = null;
85+
const previousInline = new Map<string, string>();
86+
87+
return runReportedDomEditCommit({
88+
capture: () => {
89+
const el = doc ? findElementForSelection(doc, selection, activeCompPath) : null;
90+
if (!el) return;
91+
editedElement = el;
92+
for (const [property] of entries)
93+
previousInline.set(property, el.style.getPropertyValue(property));
94+
},
95+
apply: () => {
96+
if (!editedElement) return;
97+
for (const [property, value] of liveStyles) editedElement.style.setProperty(property, value);
98+
if (fontFamily !== undefined && doc) {
99+
injectPreviewGoogleFont(doc, fontFamily);
100+
if (importedFont) injectPreviewImportedFont(doc, importedFont);
101+
}
102+
},
103+
persist: () =>
104+
persistDomEditOperations(selection, operations, {
105+
label: "Edit layer style",
106+
// Inline styles are already live, so a reload would only blank the preview.
107+
skipRefresh: true,
108+
prepareContent: importedFont
109+
? (html, sourceFile) => ensureImportedFontFace(html, importedFont, sourceFile)
110+
: undefined,
111+
}),
112+
shouldRevert: ownsAny,
113+
revert: () => {
114+
const el = editedElement;
115+
if (!el) return;
116+
// ponytail: background-image fit styles are not reverted here.
117+
for (const { property, isLatest } of owned) {
118+
const previous = previousInline.get(property);
119+
if (previous === undefined || !isLatest()) continue;
120+
if (previous === "") el.style.removeProperty(property);
121+
else el.style.setProperty(property, previous);
122+
}
123+
},
124+
onError: (error) => reportDomEditPersistFailure(selection, operations, error, showToast),
125+
shouldResync: ownsAny,
126+
resync: () => context.resync?.(selection),
127+
onFinally: () => owned.forEach(({ isLatest }) => isLatest.release()),
128+
});
129+
}

‎packages/studio/src/hooks/useDomEditCommits.ts‎

Lines changed: 17 additions & 182 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,15 @@
11
import { buildProjectApiPath } from "../utils/projectRouting";
2-
import { useCallback, useRef } from "react";
2+
import { useCallback } from "react";
33
import { findUnsafeDomPatchValues } from "@hyperframes/core/studio-api/finite-mutation";
44
import { FONT_EXT } from "../utils/mediaTypes";
5-
6-
import { trackStudioEvent } from "../utils/studioTelemetry";
75
import { primaryFontFamilyValue } from "../utils/studioFontHelpers";
86
import { StudioSaveHttpError, trackStudioSaveFailure } from "../utils/studioSaveDiagnostics";
9-
import { buildDomEditPatchTarget, type DomEditSelection } from "../components/editor/domEditing";
7+
import type { DomEditSelection } from "../components/editor/domEditing";
108
import { fontFamilyFromAssetPath, type ImportedFontAsset } from "../components/editor/fontAssets";
11-
import type { CommitDomEditPatchBatches, PersistDomEditOperations } from "./domEditCommitTypes";
9+
import type { CommitDomEditPatchBatches } from "./domEditCommitTypes";
1210
import type { PatchOperation } from "../utils/sourcePatcher";
13-
import {
14-
DomEditPersistUnsafeValueError,
15-
DomEditPersistUnresolvableError,
16-
warnDomEditPersistNoOp,
17-
} from "./domEditPersistFailure";
11+
import { DomEditPersistUnsafeValueError } from "./domEditPersistFailure";
12+
import { useDomEditPersist, type RecordEditInput } from "./useDomEditPersist";
1813
import { useDomEditPositionPatchCommit } from "./useDomEditPositionPatchCommit";
1914
import { useDomEditTextCommits } from "./useDomEditTextCommits";
2015
import { useDomGeometryCommits } from "./useDomGeometryCommits";
@@ -24,19 +19,9 @@ import {
2419
batchesAreInlineStyleOnly,
2520
formatUnsafeFieldList,
2621
patchElementBatches,
27-
postPatchElement,
28-
writePreparedContent,
2922
} from "./useDomEditCommitsHelpers";
3023
import type { CutoverResult } from "../utils/sdkCutover";
31-
import { reseekPreviewRuntime } from "./timelineTrackVisibility";
3224
import { serializeStudioFileMutations } from "../utils/studioFileMutationCoordinator";
33-
import { readProjectFileContent } from "../utils/studioFileHistory";
34-
interface RecordEditInput {
35-
label: string;
36-
coalesceKey?: string;
37-
coalesceMs?: number;
38-
files: Record<string, { before: string; after: string }>;
39-
}
4025

4126
export interface UseDomEditCommitsParams {
4227
activeCompPath: string | null;
@@ -132,168 +117,18 @@ export function useDomEditCommits({
132117
[fileTree, projectId, importedFontAssetsRef],
133118
);
134119

135-
const reportedUnresolvableRef = useRef(new Set<string>());
136-
137-
// fallow-ignore-next-line complexity
138-
const performPersistDomEditOperations = useCallback(
139-
// fallow-ignore-next-line complexity
140-
async (
141-
selection: DomEditSelection,
142-
operations: PatchOperation[],
143-
options: Parameters<PersistDomEditOperations>[2],
144-
expectedProjectId: string,
145-
) => {
146-
if (projectIdRef.current !== expectedProjectId) {
147-
throw new Error("Active project changed before the edit could be saved");
148-
}
149-
const pid = expectedProjectId;
150-
if (options?.shouldSave && !options.shouldSave()) return;
151-
152-
const targetPath = selection.sourceFile || activeCompPath || "index.html";
153-
const completePersistence = <T>(result: T, changed: boolean): T => {
154-
if (options?.skipRefresh && changed) reseekPreviewRuntime(previewIframeRef.current);
155-
return result;
156-
};
157-
158-
const readTarget = async (): Promise<string | null> => {
159-
const content = await readProjectFileContent(pid, targetPath);
160-
if (projectIdRef.current !== expectedProjectId) {
161-
throw new Error("Active project changed before the edit could be saved");
162-
}
163-
return options?.shouldSave && !options.shouldSave() ? null : content;
164-
};
165-
166-
// Validate layout values BEFORE any persist path runs. The SDK cutover
167-
// path (onTrySdkPersist) returns early on success, so leaving this check
168-
// after it let invalid numeric values bypass the guard whenever the
169-
// cutover flag was on.
170-
const patchTarget = buildDomEditPatchTarget(selection);
171-
const patchBody = { target: patchTarget, operations };
172-
const unsafeFields = findUnsafeDomPatchValues(patchBody);
173-
if (unsafeFields.length > 0) {
174-
const fields = formatUnsafeFieldList(unsafeFields);
175-
showToast("Couldn't save edit because it contains invalid layout values", "error");
176-
throw new DomEditPersistUnsafeValueError(`DOM patch contains unsafe values: ${fields}`, {
177-
alreadyToasted: true,
178-
});
179-
}
180-
181-
// Skip the SDK path when prepareContent is set (e.g. @font-face injection
182-
// for a custom font): sdkCutoverPersist serializes only the patched DOM
183-
// and would drop the injected content. Let the server path run prepareContent.
184-
// The SDK joins the file queue itself and re-reads there; this read is only its fallback.
185-
if (onTrySdkPersist && !options?.prepareContent) {
186-
const originalContent = await readTarget();
187-
if (originalContent === null) return;
188-
const cutover = await onTrySdkPersist(selection, operations, originalContent, targetPath, {
189-
label: options?.label,
190-
coalesceKey: options?.coalesceKey,
191-
skipRefresh: options?.skipRefresh,
192-
});
193-
if (cutover.status === "failed") throw cutover.error;
194-
if (cutover.status === "committed") {
195-
// SDK handled it — its in-memory doc is already current, so do NOT
196-
// forceReload (that would echo-reload the session we just wrote).
197-
return completePersistence(
198-
{ sourceFile: targetPath, version: cutover.version, changed: true },
199-
true,
200-
);
201-
}
202-
}
203-
204-
const history = {
205-
label: options?.label ?? "Edit layer",
206-
coalesceKey: options?.coalesceKey,
207-
coalesceMs: options?.coalesceMs,
208-
};
209-
const prepare = options?.prepareContent;
210-
// Read, server patch, follow-up write and history hold the file's queue, so no save lands between them.
211-
const saved = await serializeStudioFileMutations(writeProjectFile, [targetPath], async () => {
212-
const originalContent = await readTarget();
213-
if (originalContent === null) return null;
214-
const patchData = await postPatchElement(pid, targetPath, patchBody, showToast);
215-
if (!patchData.changed) return { patchData, patchedContent: null, finalContent: null };
216-
217-
const patchedContent =
218-
typeof patchData.content === "string" ? patchData.content : originalContent;
219-
const finalContent = prepare
220-
? await writePreparedContent(
221-
targetPath,
222-
patchedContent,
223-
prepare,
224-
writeProjectFile,
225-
showToast,
226-
)
227-
: patchedContent;
228-
229-
await editHistory.recordEdit({
230-
...history,
231-
files: { [targetPath]: { before: originalContent, after: finalContent } },
232-
});
233-
return { patchData, patchedContent, finalContent };
234-
});
235-
if (saved === null) return;
236-
const { patchData, patchedContent, finalContent } = saved;
237-
238-
if (finalContent === null) {
239-
if (patchData.matched === false) {
240-
const targetKey = selection.selector ?? selection.id ?? "selection";
241-
if (!reportedUnresolvableRef.current.has(targetKey)) {
242-
reportedUnresolvableRef.current.add(targetKey);
243-
trackStudioEvent("save_skipped_unresolvable", {
244-
target_id: selection.id ?? undefined,
245-
target_selector: selection.selector ?? undefined,
246-
target_source_file: selection.sourceFile ?? undefined,
247-
composition: activeCompPath ?? undefined,
248-
});
249-
}
250-
throw new DomEditPersistUnresolvableError(targetPath);
251-
}
252-
warnDomEditPersistNoOp(selection, operations);
253-
return completePersistence(
254-
typeof patchData.path === "string" && typeof patchData.version === "string"
255-
? { sourceFile: patchData.path, version: patchData.version, changed: false }
256-
: undefined,
257-
false,
258-
);
259-
}
260-
forceReloadSdkSession?.();
261-
262-
if (!options?.skipRefresh) {
263-
reloadPreview();
264-
}
265-
return completePersistence(
266-
finalContent === patchedContent &&
267-
typeof patchData.path === "string" &&
268-
typeof patchData.version === "string"
269-
? { sourceFile: patchData.path, version: patchData.version, changed: true }
270-
: undefined,
271-
true,
272-
);
273-
},
274-
[
275-
activeCompPath,
276-
editHistory,
277-
writeProjectFile,
278-
projectIdRef,
279-
reloadPreview,
280-
showToast,
281-
forceReloadSdkSession,
282-
onTrySdkPersist,
283-
previewIframeRef,
284-
],
285-
);
286-
287-
const persistDomEditOperations: PersistDomEditOperations = useCallback(
288-
(selection, operations, options) => {
289-
const expectedProjectId = projectIdRef.current;
290-
if (!expectedProjectId) return Promise.reject(new Error("No active project"));
291-
return queueDomEditSave(() =>
292-
performPersistDomEditOperations(selection, operations, options, expectedProjectId),
293-
);
294-
},
295-
[performPersistDomEditOperations, projectIdRef, queueDomEditSave],
296-
);
120+
const persistDomEditOperations = useDomEditPersist({
121+
activeCompPath,
122+
previewIframeRef,
123+
showToast,
124+
queueDomEditSave,
125+
writeProjectFile,
126+
editHistory,
127+
projectIdRef,
128+
reloadPreview,
129+
forceReloadSdkSession,
130+
onTrySdkPersist,
131+
});
297132

298133
const commitDomEditPatchBatches: CommitDomEditPatchBatches = useCallback(
299134
(batches, options) => {

0 commit comments

Comments
 (0)