Skip to content

Write HTML. Render video. Built for agents.

feat: Persist Studio manual edits via manifest (#593)

Vance Ingallsd0abe90a826a
diff --git a/docs/contributing.mdx b/docs/contributing.mdx
index 8029fa01b1..0dc7845f42 100644
--- a/docs/contributing.mdx
+++ b/docs/contributing.mdx
@@ -53,6 +53,14 @@ bun run build # Build all packages
bun run --filter '*' typecheck # Type-check all packages
```
+### Studio Editing Work
+
+If you are changing Studio's visual editing surface, read
+[Studio Manual DOM Editing](/contributing/studio-manual-dom-editing) before
+editing code. The inspector intentionally exposes only interactions it can
+persist safely back to HTML, so changes should preserve the capability gates,
+source patching model, and documented limitations.
+
### Running Tests
<CodeGroup>
diff --git a/docs/contributing/studio-manual-dom-editing.mdx b/docs/contributing/studio-manual-dom-editing.mdx
new file mode 100644
index 0000000000..e2a343afe0
--- /dev/null
+++ b/docs/contributing/studio-manual-dom-editing.mdx
@@ -0,0 +1,315 @@
+---
+title: Studio Manual DOM Editing
+description: What the Studio manual DOM editing inspector ships today, including capabilities, UX, and constraints.
+---
+
+This page documents the current manual DOM editing surface in HyperFrames Studio. It reflects the implementation that ships in the Studio inspector today, not the earlier design draft that explored third-party transform engines.
+
+## What Shipped
+
+Studio now supports a direct DOM editing workflow inside the preview:
+
+- select supported elements directly in the preview
+- see an editor-owned overlay around the current selection
+- move and resize supported elements on canvas when geometry is safe
+- detach eligible layout-controlled layers with an explicit `Make movable` action
+- edit style properties from the right-side `Design` inspector
+- edit text layers for safe text-bearing selections, including empty text values
+- add and remove child text layers for multi-text selections
+- edit solid fills, gradients, project-asset image fills, external image fills, opacity, radius, flex metadata, typography, and blend mode
+- drill into nested compositions from master view instead of pretending every inner node is editable in place
+- generate an element-scoped `Ask agent` prompt bundle from the right inspector
+
+The important rule is conservative: Studio only exposes interactions it can round-trip back to authored HTML with deterministic behavior.
+
+## Current User Experience
+
+### Preview selection
+
+- Single click selects a patchable element in the preview.
+- The selection overlay is rendered in Studio chrome, not injected into authored content.
+- The overlay is cleared when:
+ - the `Inspector` panel is closed
+ - the user clicks an empty area in the preview
+ - the underlying element disappears after a source refresh
+
+### Overlay behavior
+
+The overlay provides:
+
+- selection bounds
+- drag behavior for supported elements
+- a resize handle when width and height are safely patchable
+- blocked-drag feedback for unsupported movement
+
+The overlay intentionally does not include a floating action toolbar. `Ask agent` lives in the right inspector header, and style controls live in the `Design` panel.
+
+The current implementation uses Studio-owned pointer handling in `DomEditOverlay.tsx`. It does **not** use `Moveable`.
+
+### Inspector behavior
+
+The `Design` panel currently includes:
+
+- `Layout`
+ - X / Y / W / H fields
+ - wheel and arrow-key numeric scrubbing
+ - `Make movable` for block-ish layout-controlled layers that can be detached safely
+- `Flex`
+ - direction, justify, align, gap, clip content
+- `Radius`
+ - slider + live readout
+- `Blending`
+ - opacity slider + live readout
+ - blend mode
+- `Fill`
+ - solid color
+ - multi-stop gradient editing
+ - project asset image fills
+ - inline image upload into the project assets list
+ - external image URL fill
+ - text color
+- `Color picker`
+ - viewport-clamped floating picker
+ - saturation / brightness crosshair
+ - hue and alpha sliders
+ - hex input
+- `Text`
+ - direct text layer editing when the selection is safe to patch
+ - add / remove text layers for child text selections
+ - font size, weight, and family controls
+- `Selection colors`
+ - a summary of detected colors for the current selection
+
+The inspector is intentionally split from `Renders` with a `Design / Renders` tab control in the right panel. Switching to `Renders` does not mean the header-level `Inspector` panel is closed.
+
+## What Counts As Editable
+
+Studio builds a `DomEditSelection` and `DomEditCapabilities` object for each selection.
+
+### Selection requirements
+
+A node is only useful to Studio if it can be identified with a stable patch target, for example:
+
+- `id`
+- stable selector
+- selector index scoped to the correct source file
+- composition host mapping when master view is involved
+
+### Move support
+
+Move is allowed only when the selected element:
+
+- has a stable patch target
+- is `absolute` or `fixed`
+- has `left` and `top` values that resolve to pixel values
+- is not transform-driven (`transform: none`)
+
+### Resize support
+
+Resize is allowed only when move is already allowed and Studio can also safely patch pixel `width` and/or `height`.
+
+### Detach from layout support
+
+Some block-ish layers are selectable and style-editable, but cannot be moved directly because flex, grid, or normal document flow owns their position.
+
+For those layers, Studio can expose `Make movable` instead of silently converting on drag. The action measures the current visual rect relative to the composition root and writes conservative inline geometry:
+
+- `position: absolute`
+- `left`, `top`, `width`, and `height` in pixels
+- `margin: 0`
+
+The UI explains that this detaches the layer from flex/grid flow and preserves the current visual position. Inline text nodes are not detached directly.
+
+### Text editing support
+
+Text editing is allowed only for safe text-bearing selections:
+
+- supported text-bearing tags such as `div`, `span`, `p`, `strong`, and headings
+- self text selections or leaf child text layers
+- empty text values after a user clears the content
+- not a composition host
+
+For multi-text selections, Studio shows a text-layer list. Users can select a specific text layer, edit content live, change size, weight, and font family, add a sibling text layer, or remove the active layer.
+
+### Unsupported examples
+
+Studio intentionally withholds direct geometry editing for:
+
+- flex/grid children whose position is emergent from layout, unless the user chooses `Make movable`
+- transform-driven geometry
+- nested composition internals while the user is still in master view
+- nodes without a stable patch target
+- inline text spans as geometry targets
+
+When geometry is blocked but style edits are still safe, the inspector shows the selection and the reason direct geometry editing is unavailable.
+
+If the user tries to drag a blocked layer, Studio shows a toast. Layout-owned layers point users to `Make movable`; transform-driven or unsafe targets explain that direct move/resize is limited to absolute or fixed pixel geometry with no transform-driven layout.
+
+## Nested Composition Rules
+
+Nested compositions are handled explicitly.
+
+### In master view
+
+- clicking content inside a nested composition maps back to the composition host
+- supported composition hosts can move as a whole when their host geometry is safe
+- Studio does not expose direct inner-node geometry edits from the master preview
+- double click drills into the subcomposition
+
+### After drill-down
+
+- Studio resolves selections inside that composition normally
+- direct move/resize becomes available again if the selected inner node meets the capability rules
+- text, fill, gradient, image, radius, opacity, and typography edits apply to the selected inner node
+
+This keeps Studio honest about what it can patch safely from the current editing context.
+
+## Source Patching Model
+
+Studio still uses authored HTML as the source of truth.
+
+The manual DOM editing flow patches source through the existing patch pipeline in `packages/studio/src/utils/sourcePatcher.ts`.
+
+Current patch types used by the inspector include:
+
+- inline style patches
+- attribute patches for timeline-linked editing paths
+- text-content patches
+- detach-from-layout style patches
+
+The flow is:
+
+1. user selects or manipulates an element in the preview
+2. Studio resolves a stable target
+3. the preview is updated optimistically for interaction feedback
+4. the patch is written back to source
+5. the preview refreshes and selection is reattached
+
+## Gradient Editing
+
+The current gradient editor is a structured Studio control, not a raw CSS text field.
+
+It supports:
+
+- `linear`, `radial`, and `conic` gradients
+- repeating variants
+- multiple stops
+- stop insertion by clicking the preview strip
+- stop removal
+- angle control
+- radial shape and size controls
+- radial/conic center controls
+
+The editor still serializes back to CSS `background-image`, but the inspector works with a parsed gradient model instead of forcing the user to type raw gradient syntax.
+
+## Image Fill Editing
+
+The image fill editor is no longer just a raw `background-image` input.
+
+It supports:
+
+- selecting an existing project image asset
+- uploading an image from the fill panel, which also adds it to the Assets tab
+- previewing the selected project asset in the panel
+- entering an external URL when the image is not a project asset
+
+Studio serializes project asset selections back to `background-image: url(...)`, and rewrites asset URLs so nested subcomposition previews still resolve the image correctly.
+
+## Color Editing
+
+The color editor is a custom Studio popover instead of the native browser color dialog.
+
+It supports:
+
+- opening from the whole color row
+- staying inside the viewport near the clicked color
+- saturation / brightness picking with visible crosshair guides
+- hue and alpha controls with visible handles
+- a current color swatch, readout, and hex input
+
+The picker writes CSS `rgb(...)` or `rgba(...)` values and preserves alpha through edits.
+
+## Numeric Scrubbing
+
+Numeric layout/detail inputs support lightweight design-tool-style nudging:
+
+- mouse wheel over the focused field
+- `ArrowUp` / `ArrowDown`
+- `Shift` for larger steps
+- `Alt` for finer steps
+
+This is currently used across the numeric commit fields in the inspector, including layout metrics and other numeric text inputs that parse cleanly as values plus units.
+
+## Files That Own The Feature
+
+The main implementation lives in:
+
+- `packages/studio/src/App.tsx`
+ - overall inspector wiring
+ - selection lifecycle
+ - preview hit testing
+ - persistence hooks
+ - detach-from-layout commit flow
+- `packages/studio/src/components/editor/DomEditOverlay.tsx`
+ - overlay box, drag, resize, blocked-drag feedback
+- `packages/studio/src/components/editor/PropertyPanel.tsx`
+ - right-side inspector UI
+- `packages/studio/src/components/editor/domEditing.ts`
+ - selection resolution
+ - capability gating
+ - text field modeling
+ - prompt generation
+- `packages/studio/src/components/editor/colorValue.ts`
+ - color parsing, HSV conversion, and CSS color serialization
+- `packages/studio/src/components/editor/floatingPanel.ts`
+ - viewport-safe floating panel placement for color picking
+- `packages/studio/src/components/editor/fontAssets.ts`
+ - imported font asset helpers
+- `packages/studio/src/components/editor/fontCatalog.ts`
+ - Google font catalog metadata and stylesheet URLs
+- `packages/studio/src/components/editor/gradientValue.ts`
+ - gradient parsing, serialization, and stop editing helpers
+- `packages/studio/src/utils/sourcePatcher.ts`
+ - source patch persistence
+
+Supporting Studio shell changes also landed in:
+
+- `packages/studio/src/components/nle/NLELayout.tsx`
+- `packages/studio/src/components/nle/NLEPreview.tsx`
+- `packages/studio/src/components/sidebar/CompositionsTab.tsx`
+- `packages/studio/src/components/sidebar/LeftSidebar.tsx`
+- `packages/studio/src/player/components/Player.tsx`
+- `packages/studio/src/player/components/Timeline.tsx`
+- `packages/studio/src/player/components/TimelineClip.tsx`
+- `packages/studio/src/player/hooks/useTimelinePlayer.ts`
+- `packages/studio/src/utils/mediaTypes.ts`
+
+## Current Constraints
+
+This feature is intentionally **not** a full general-purpose visual builder.
+
+Still out of scope today:
+
+- rotation
+- arbitrary transforms
+- snapping and alignment guides
+- multi-select
+- marquee selection
+- freeform editing of every DOM node regardless of layout model
+- editing nested subcomposition internals directly from the master preview without drill-down
+- automatic conversion to absolute positioning on drag without user confirmation
+- direct geometry editing of inline text spans
+
+## Bottom Line
+
+Studio manual DOM editing is now a narrow, deterministic visual editing layer over authored HTML.
+
+It does **not** try to make the whole DOM freely editable. Instead it:
+
+- keeps source HTML as the source of truth
+- exposes only patchable interactions
+- uses a Studio-owned overlay layer for direct manipulation
+- gives users a real inspector for safe style and text edits
+- treats nested compositions as drill-down boundaries instead of flattening them into an unsafe editing surface
+
+That tradeoff is the reason the current feature feels reliable instead of deceptive.
diff --git a/docs/docs.json b/docs/docs.json
index 3c7092e087..090a8e85d7 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -202,7 +202,8 @@
"pages": [
"contributing",
"contributing/release-channels",
- "contributing/testing-local-changes"
+ "contributing/testing-local-changes",
+ "contributing/studio-manual-dom-editing"
]
},
{
diff --git a/packages/cli/src/server/studioServer.ts b/packages/cli/src/server/studioServer.ts
index ccceccffb7..5c4e1df530 100644
--- a/packages/cli/src/server/studioServer.ts
+++ b/packages/cli/src/server/studioServer.ts
@@ -13,6 +13,7 @@ import { createProjectWatcher, type ProjectWatcher } from "./fileWatcher.js";
import { loadRuntimeSource } from "./runtimeSource.js";
import { VERSION as version } from "../version.js";
import {
+ createStudioManualEditsRenderBodyScript,
createStudioApi,
getMimeType,
type StudioApiAdapter,
@@ -22,6 +23,8 @@ import {
import { getElementScreenshotClip } from "@hyperframes/core/studio-api/screenshot-clip";
import type { ScreenshotClip } from "@hyperframes/core/studio-api/screenshot-clip";
+const STUDIO_MANUAL_EDITS_PATH = ".hyperframes/studio-manual-edits.json";
+
// ── Path resolution ─────────────────────────────────────────────────────────
function resolveDistDir(): string {
@@ -77,6 +80,38 @@ function resolveRuntimePath(): string {
return builtPath;
}
+function readStudioManualEditManifestContent(projectDir: string): string {
+ const manifestPath = join(projectDir, STUDIO_MANUAL_EDITS_PATH);
+ if (!existsSync(manifestPath)) return "";
+ try {
+ return readFileSync(manifestPath, "utf-8");
+ } catch {
+ return "";
+ }
+}
+
+async function applyStudioManualEditsToThumbnailPage(
+ page: import("puppeteer-core").Page,
+ manifestContent: string,
+ activeCompositionPath: string,
+): Promise<void> {
+ const script = createStudioManualEditsRenderBodyScript(manifestContent, {
+ activeCompositionPath,
+ });
+ if (!script) return;
+ await page.addScriptTag({ content: script });
+}
+
+async function reapplyStudioManualEditsToThumbnailPage(
+ page: import("puppeteer-core").Page,
+): Promise<void> {
+ await page.evaluate(() => {
+ const apply = (window as Window & { __hfStudioManualEditsApply?: () => number })
+ .__hfStudioManualEditsApply;
+ if (typeof apply === "function") apply();
+ });
+}
+
// ── Shared thumbnail browser (singleton per process) ────────────────────────
// One browser instance is reused across all composition thumbnail requests.
// Spawning a new Puppeteer process per request adds 2-5s overhead and causes
@@ -198,10 +233,13 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
// Continue without — acquireBrowser will try its own resolution
}
+ const manifestContent = readStudioManualEditManifestContent(opts.project.dir);
+ const manualEditsRenderScript = createStudioManualEditsRenderBodyScript(manifestContent);
const job = createRenderJob({
fps: opts.fps as 24 | 30 | 60,
quality: opts.quality as "draft" | "standard" | "high",
format: opts.format,
+ ...(manualEditsRenderScript ? { renderBodyScripts: [manualEditsRenderScript] } : {}),
});
const startTime = Date.now();
const onProgress = (j: { progress: number; currentStage?: string }) => {
@@ -258,11 +296,14 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
win.__timeline.seek(t);
}
}, opts.seekTime);
+ const manifestContent = readStudioManualEditManifestContent(opts.project.dir);
+ await applyStudioManualEditsToThumbnailPage(page, manifestContent, opts.compPath);
// Let the seek render settle.
await new Promise((r) => setTimeout(r, 200));
+ await reapplyStudioManualEditsToThumbnailPage(page);
let clip: ScreenshotClip | undefined;
if (opts.selector) {
- clip = await page.evaluate(getElementScreenshotClip, opts.selector);
+ clip = await page.evaluate(getElementScreenshotClip, opts.selector, opts.selectorIndex);
}
const screenshot = (await page.screenshot(
opts.format === "png"
@@ -318,8 +359,8 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
app.get("/api/events", (c) => {
return streamSSE(c, async (stream) => {
- const listener = () => {
- stream.writeSSE({ event: "file-change", data: "{}" }).catch(() => {});
+ const listener = (path: string) => {
+ stream.writeSSE({ event: "file-change", data: JSON.stringify({ path }) }).catch(() => {});
};
watcher.addListener(listener);
while (true) {
diff --git a/packages/core/package.json b/packages/core/package.json
index 614b34e642..fe9b4f7ecc 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -42,6 +42,10 @@
"import": "./src/studio-api/helpers/screenshotClip.ts",
"types": "./src/studio-api/helpers/screenshotClip.ts"
},
+ "./studio-api/manual-edits-render-script": {
+ "import": "./src/studio-api/helpers/manualEditsRenderScript.ts",
+ "types": "./src/studio-api/helpers/manualEditsRenderScript.ts"
+ },
"./text": {
"import": "./src/text/index.ts",
"types": "./src/text/index.ts"
@@ -81,6 +85,10 @@
"import": "./dist/studio-api/helpers/screenshotClip.js",
"types": "./dist/studio-api/helpers/screenshotClip.d.ts"
},
+ "./studio-api/manual-edits-render-script": {
+ "import": "./dist/studio-api/helpers/manualEditsRenderScript.js",
+ "types": "./dist/studio-api/helpers/manualEditsRenderScript.d.ts"
+ },
"./text": {
"import": "./dist/text/index.js",
"types": "./dist/text/index.d.ts"
diff --git a/packages/core/src/compiler/htmlBundler.test.ts b/packages/core/src/compiler/htmlBundler.test.ts
index e6a24ddb0c..527c3a4828 100644
--- a/packages/core/src/compiler/htmlBundler.test.ts
+++ b/packages/core/src/compiler/htmlBundler.test.ts
@@ -255,9 +255,11 @@ describe("bundleToSingleHtml", () => {
const host = document.querySelector("#scene-host");
expect(host?.getAttribute("data-composition-id")).toBe("scene");
+ expect(host?.getAttribute("data-composition-file")).toBe("compositions/scene.html");
expect(host?.getAttribute("data-start")).toBe("intro");
expect(host?.getAttribute("data-width")).toBe("1920");
expect(host?.querySelector(".title")?.textContent).toBe("Scene");
+ expect(host?.querySelector(".title")?.closest("[data-composition-file]")).toBe(host);
expect(
Array.from(host?.children ?? []).some(
(child) => child.getAttribute("data-composition-id") === "scene",
diff --git a/packages/core/src/compiler/htmlBundler.ts b/packages/core/src/compiler/htmlBundler.ts
index 3a80d58c91..c374672eb5 100644
--- a/packages/core/src/compiler/htmlBundler.ts
+++ b/packages/core/src/compiler/htmlBundler.ts
@@ -7,7 +7,11 @@ import {
parseHTMLContent,
stripEmbeddedRuntimeScripts,
} from "./htmlDocument";
-import { rewriteAssetPaths, rewriteCssAssetUrls } from "./rewriteSubCompPaths";
+import {
+ rewriteAssetPaths,
+ rewriteCssAssetUrls,
+ rewriteInlineStyleAssetUrls,
+} from "./rewriteSubCompPaths";
import { scopeCssToComposition, wrapScopedCompositionScript } from "./compositionScoping";
import { validateHyperframeHtmlContract } from "./staticGuard";
@@ -501,18 +505,31 @@ export async function bundleToSingleHtml(
el.setAttribute(attr, val);
},
);
+ const styledEls = innerRoot
+ ? innerRoot.querySelectorAll("[style]")
+ : contentDoc.querySelectorAll("[style]");
+ rewriteInlineStyleAssetUrls(
+ styledEls,
+ src,
+ (el: Element) => el.getAttribute("style"),
+ (el: Element, val: string) => {
+ el.setAttribute("style", val);
+ },
+ );
if (innerRoot) {
const innerW = innerRoot.getAttribute("data-width");
const innerH = innerRoot.getAttribute("data-height");
if (innerW && !hostEl.getAttribute("data-width")) hostEl.setAttribute("data-width", innerW);
if (innerH && !hostEl.getAttribute("data-height")) hostEl.setAttribute("data-height", innerH);
+ innerRoot.setAttribute("data-composition-file", src);
for (const child of [...innerRoot.querySelectorAll("style, script")]) child.remove();
hostEl.innerHTML = compId ? innerRoot.innerHTML || "" : innerRoot.outerHTML || "";
} else {
for (const child of [...contentDoc.querySelectorAll("style, script")]) child.remove();
hostEl.innerHTML = contentDoc.body.innerHTML || "";
}
+ hostEl.setAttribute("data-composition-file", src);
hostEl.removeAttribute("data-composition-src");
}
diff --git a/packages/core/src/compiler/rewriteSubCompPaths.test.ts b/packages/core/src/compiler/rewriteSubCompPaths.test.ts
index d2048a1951..7de4f42f07 100644
--- a/packages/core/src/compiler/rewriteSubCompPaths.test.ts
+++ b/packages/core/src/compiler/rewriteSubCompPaths.test.ts
@@ -1,5 +1,9 @@
import { describe, expect, it } from "vitest";
-import { rewriteAssetPath, rewriteCssAssetUrls } from "./rewriteSubCompPaths.js";
+import {
+ rewriteAssetPath,
+ rewriteCssAssetUrls,
+ rewriteInlineStyleAssetUrls,
+} from "./rewriteSubCompPaths.js";
describe("rewriteAssetPath", () => {
it("rewrites `../` against the sub-composition dir", () => {
@@ -36,4 +40,19 @@ describe("rewriteAssetPath", () => {
expect(out).not.toMatch(/\\/);
expect(out).not.toMatch(/:\\/);
});
+
+ it("rewrites CSS urls inside inline style attributes", () => {
+ const elements = [{ style: `background-image: url("../cover.png")` }];
+
+ rewriteInlineStyleAssetUrls(
+ elements,
+ "compositions/scene.html",
+ (el) => el.style,
+ (el, value) => {
+ el.style = value;
+ },
+ );
+
+ expect(elements[0]?.style).toBe(`background-image: url("cover.png")`);
+ });
});
diff --git a/packages/core/src/compiler/rewriteSubCompPaths.ts b/packages/core/src/compiler/rewriteSubCompPaths.ts
index 23ea579e9c..72bc1ba23d 100644
--- a/packages/core/src/compiler/rewriteSubCompPaths.ts
+++ b/packages/core/src/compiler/rewriteSubCompPaths.ts
@@ -96,6 +96,28 @@ export function rewriteAssetPaths<T>(
}
}
+/**
+ * Rewrite CSS url(...) references inside inline style attributes.
+ */
+export function rewriteInlineStyleAssetUrls<T>(
+ elements: Iterable<T>,
+ compSrcPath: string,
+ getStyle: (el: T) => string | null | undefined,
+ setStyle: (el: T, value: string) => void,
+): void {
+ const compDir = dirname(compSrcPath);
+ if (!compDir || compDir === ".") return;
+
+ for (const el of elements) {
+ const style = getStyle(el);
+ if (!style) continue;
+ const rewritten = rewriteCssAssetUrls(style, compSrcPath);
+ if (rewritten !== style) {
+ setStyle(el, rewritten);
+ }
+ }
+}
+
/**
* Rewrite CSS url(...) references in a sub-composition's inline styles so
* ../foo.woff2 remains valid after the CSS is hoisted into the root document.
diff --git a/packages/core/src/lint/rules/captions.test.ts b/packages/core/src/lint/rules/captions.test.ts
index 3c0a59cbcd..9ae3c02c3a 100644
--- a/packages/core/src/lint/rules/captions.test.ts
+++ b/packages/core/src/lint/rules/captions.test.ts
@@ -50,6 +50,28 @@ describe("caption rules", () => {
expect(finding).toBeUndefined();
});
+ it("does not warn for generic GSAP opacity exits in non-caption loops", () => {
+ const html = `
+<html><body>
+ <div data-composition-id="main" data-width="1920" data-height="1080">
+ <script>
+ window.__timelines = window.__timelines || {};
+ var tl = gsap.timeline({ paused: true });
+ var sceneCaption = document.querySelector("#scene-caption");
+ CARDS.forEach(function(group, gi) {
+ var groupEl = document.createElement("div");
+ groupEl.id = "card-" + gi;
+ tl.to(groupEl, { opacity: 0, duration: 0.12 }, 2);
+ });
+ window.__timelines["main"] = tl;
+ </script>
+ </div>
+</body></html>`;
+ const result = lintHyperframeHtml(html);
+ const finding = result.findings.find((f) => f.code === "caption_exit_missing_hard_kill");
+ expect(finding).toBeUndefined();
+ });
+
it("warns when caption group has nowrap without max-width", () => {
const html = `
<html><body>
diff --git a/packages/core/src/lint/rules/captions.ts b/packages/core/src/lint/rules/captions.ts
index f8e0f531ad..94f09f7f49 100644
--- a/packages/core/src/lint/rules/captions.ts
+++ b/packages/core/src/lint/rules/captions.ts
@@ -12,7 +12,8 @@ export const captionRules: Array<(ctx: LintContext) => HyperframeLintFinding[]>
content,
);
const hasCaptionLoop =
- /forEach|\.forEach\s*\(/.test(content) && /createElement|caption|group|cg-/.test(content);
+ /forEach|\.forEach\s*\(/.test(content) &&
+ /karaoke|caption[-_]?(?:group|word|line|block)|cg-/.test(content);
if (hasCaptionLoop && hasExitTween && !hasHardKill) {
findings.push({
code: "caption_exit_missing_hard_kill",
diff --git a/packages/core/src/studio-api/createStudioApi.ts b/packages/core/src/studio-api/createStudioApi.ts
index a7a94bb62a..04492aad4b 100644
--- a/packages/core/src/studio-api/createStudioApi.ts
+++ b/packages/core/src/studio-api/createStudioApi.ts
@@ -7,6 +7,7 @@ import { registerLintRoutes } from "./routes/lint.js";
import { registerRenderRoutes } from "./routes/render.js";
import { registerThumbnailRoutes } from "./routes/thumbnail.js";
import { registerWaveformRoutes } from "./routes/waveform.js";
+import { registerFontRoutes } from "./routes/fonts.js";
/**
* Create a Hono sub-app with all studio API routes.
@@ -24,6 +25,7 @@ export function createStudioApi(adapter: StudioApiAdapter): Hono {
registerRenderRoutes(api, adapter);
registerThumbnailRoutes(api, adapter);
registerWaveformRoutes(api, adapter);
+ registerFontRoutes(api);
return api;
}
diff --git a/packages/core/src/studio-api/helpers/manualEditsRenderScript.test.ts b/packages/core/src/studio-api/helpers/manualEditsRenderScript.test.ts
new file mode 100644
index 0000000000..3e41a15f2a
--- /dev/null
+++ b/packages/core/src/studio-api/helpers/manualEditsRenderScript.test.ts
@@ -0,0 +1,382 @@
+import { describe, expect, it } from "vitest";
+import { Window } from "happy-dom";
+import { createStudioManualEditsRenderBodyScript } from "./manualEditsRenderScript";
+
+function runScript(
+ window: Window,
+ script: string,
+ getComputedStyle: typeof window.getComputedStyle = window.getComputedStyle.bind(window),
+ timers: {
+ setInterval?: typeof globalThis.setInterval;
+ clearInterval?: typeof globalThis.clearInterval;
+ } = {},
+): void {
+ const execute = new Function(
+ "window",
+ "document",
+ "HTMLElement",
+ "getComputedStyle",
+ "setInterval",
+ "clearInterval",
+ script,
+ );
+ execute(
+ window,
+ window.document,
+ window.HTMLElement,
+ getComputedStyle,
+ timers.setInterval ??
+ (((callback: TimerHandler) => {
+ void callback;
+ return 0 as never;
+ }) as typeof globalThis.setInterval),
+ timers.clearInterval ?? globalThis.clearInterval,
+ );
+}
+
+describe("createStudioManualEditsRenderBodyScript", () => {
+ it("returns null for an empty manifest", () => {
+ expect(createStudioManualEditsRenderBodyScript("")).toBeNull();
+ });
+
+ it("applies manual edits and reapplies them after render seeks", () => {
+ const window = new Window();
+ window.document.body.innerHTML = '<div id="card" style="width: 20px; height: 20px"></div>';
+ const card = window.document.getElementById("card");
+ if (!(card instanceof window.HTMLElement)) {
+ throw new Error("card fixture missing");
+ }
+
+ let seekCalls = 0;
+ (
+ window as unknown as {
+ __hf: { seek: (time: number) => void };
+ }
+ ).__hf = {
+ seek: () => {
+ seekCalls += 1;
+ card.style.removeProperty("translate");
+ },
+ };
+
+ const script = createStudioManualEditsRenderBodyScript(
+ JSON.stringify({
+ version: 1,
+ edits: [
+ {
+ kind: "path-offset",
+ target: { sourceFile: "index.html", id: "card" },
+ x: 12,
+ y: 24,
+ },
+ {
+ kind: "box-size",
+ target: { sourceFile: "index.html", id: "card" },
+ width: 120,
+ height: 64,
+ },
+ {
+ kind: "rotation",
+ target: { sourceFile: "index.html", id: "card" },
+ angle: 15,
+ },
+ ],
+ }),
+ );
+ if (!script) throw new Error("script fixture missing");
+
+ const computedStyle = (element: Element) =>
+ ({
+ display: element === card ? "block" : "block",
+ flexDirection: "row",
+ }) as CSSStyleDeclaration;
+
+ const intervalCallbacks: Array<() => void> = [];
+ runScript(window, script, computedStyle, {
+ setInterval: ((callback: TimerHandler) => {
+ if (typeof callback === "function") intervalCallbacks.push(callback as () => void);
+ return 0 as never;
+ }) as typeof globalThis.setInterval,
+ });
+
+ expect(card.style.getPropertyValue("translate")).toContain("--hf-studio-offset-x");
+ expect(card.style.getPropertyValue("width")).toBe("120px");
+ expect(card.style.getPropertyValue("height")).toBe("64px");
+ expect(card.style.getPropertyValue("rotate")).toContain("--hf-studio-rotation");
+ expect(card.style.getPropertyValue("transform-origin")).toBe("center center");
+
+ (
+ window as unknown as {
+ __hf: { seek: (time: number) => void };
+ }
+ ).__hf.seek(1);
+
+ expect(seekCalls).toBe(1);
+ expect(card.style.getPropertyValue("translate")).toContain("--hf-studio-offset-x");
+
+ (
+ window as unknown as {
+ __hf: { seek: (time: number) => void };
+ }
+ ).__hf.seek = () => {
+ card.style.removeProperty("rotate");
+ };
+ intervalCallbacks.forEach((callback) => callback());
+ (
+ window as unknown as {
+ __hf: { seek: (time: number) => void };
+ }
+ ).__hf.seek(2);
+ expect(card.style.getPropertyValue("rotate")).toContain("--hf-studio-rotation");
+
+ (
+ window as unknown as {
+ __player: { renderSeek: (time: number) => void };
+ }
+ ).__player = {
+ renderSeek: () => {
+ card.style.removeProperty("rotate");
+ },
+ };
+ intervalCallbacks.forEach((callback) => callback());
+ (
+ window as unknown as {
+ __player: { renderSeek: (time: number) => void };
+ }
+ ).__player.renderSeek(3);
+ expect(card.style.getPropertyValue("rotate")).toContain("--hf-studio-rotation");
+ });
+
+ it("applies render edits to the matching source file target", () => {
+ const window = new Window();
+ window.document.body.innerHTML = `
+ <div data-composition-id="root">
+ <div id="card"></div>
+ <div data-composition-id="nested" data-composition-file="scenes/nested.html">
+ <div id="card"></div>
+ </div>
+ </div>
+ `;
+ const cards = Array.from(window.document.getElementsByTagName("*")).filter(
+ (element): element is HTMLElement =>
+ element instanceof window.HTMLElement && element.id === "card",
+ );
+ const rootCard = cards[0];
+ const nestedCard = cards[1];
+ if (!rootCard || !nestedCard) {
+ throw new Error("source-scoped render fixture missing");
+ }
+
+ const script = createStudioManualEditsRenderBodyScript(
+ JSON.stringify({
+ version: 1,
+ edits: [
+ {
+ kind: "rotation",
+ target: { sourceFile: "scenes/nested.html", id: "card" },
+ angle: 21,
+ },
+ ],
+ }),
+ );
+ if (!script) throw new Error("script fixture missing");
+
+ runScript(window, script);
+
+ expect(rootCard.style.getPropertyValue("rotate")).toBe("");
+ expect(nestedCard.style.getPropertyValue("rotate")).toContain("--hf-studio-rotation");
+ });
+
+ it("applies render edits inside composition-file hosts without composition ids", () => {
+ const window = new Window();
+ window.document.body.innerHTML = `
+ <div data-composition-id="root">
+ <div id="card"></div>
+ <div data-composition-file="scenes/anonymous.html">
+ <div id="card"></div>
+ </div>
+ </div>
+ `;
+ const cards = Array.from(window.document.getElementsByTagName("*")).filter(
+ (element): element is HTMLElement =>
+ element instanceof window.HTMLElement && element.id === "card",
+ );
+ const rootCard = cards[0];
+ const nestedCard = cards[1];
+ if (!rootCard || !nestedCard) {
+ throw new Error("anonymous composition render fixture missing");
+ }
+
+ const script = createStudioManualEditsRenderBodyScript(
+ JSON.stringify({
+ version: 1,
+ edits: [
+ {
+ kind: "path-offset",
+ target: { sourceFile: "scenes/anonymous.html", id: "card" },
+ x: 12,
+ y: 24,
+ },
+ ],
+ }),
+ );
+ if (!script) throw new Error("script fixture missing");
+
+ runScript(window, script);
+
+ expect(rootCard.style.getPropertyValue("translate")).toBe("");
+ expect(nestedCard.style.getPropertyValue("translate")).toContain("--hf-studio-offset-x");
+ });
+
+ it("uses the active composition path as the unscoped document fallback", () => {
+ const window = new Window();
+ window.document.body.innerHTML = `<div id="card"></div>`;
+ const card = window.document.getElementById("card");
+ if (!(card instanceof window.HTMLElement)) {
+ throw new Error("card fixture missing");
+ }
+
+ const script = createStudioManualEditsRenderBodyScript(
+ JSON.stringify({
+ version: 1,
+ edits: [
+ {
+ kind: "path-offset",
+ target: { sourceFile: "compositions/scene-2.html", id: "card" },
+ x: 12,
+ y: 24,
+ },
+ ],
+ }),
+ { activeCompositionPath: "compositions/scene-2.html" },
+ );
+ if (!script) throw new Error("script fixture missing");
+
+ runScript(window, script);
+
+ expect(card.style.getPropertyValue("translate")).toContain("--hf-studio-offset-x");
+ });
+
+ it("preserves computed transform longhands as render edit bases", () => {
+ const window = new Window();
+ window.document.body.innerHTML = `<div id="card"></div>`;
+ const card = window.document.getElementById("card");
+ if (!(card instanceof window.HTMLElement)) {
+ throw new Error("card fixture missing");
+ }
+
+ const script = createStudioManualEditsRenderBodyScript(
+ JSON.stringify({
+ version: 1,
+ edits: [
+ {
+ kind: "path-offset",
+ target: { sourceFile: "index.html", id: "card" },
+ x: 12,
+ y: 24,
+ },
+ {
+ kind: "rotation",
+ target: { sourceFile: "index.html", id: "card" },
+ angle: 15,
+ },
+ ],
+ }),
+ );
+ if (!script) throw new Error("script fixture missing");
+
+ const computedStyle = (element: Element) =>
+ ({
+ getPropertyValue: (property: string) => {
+ if (element !== card) return "";
+ if (property === "translate") return "10px 20px";
+ if (property === "rotate") return "8deg";
+ return "";
+ },
+ }) as CSSStyleDeclaration;
+
+ runScript(window, script, computedStyle);
+
+ expect(card.style.getPropertyValue("translate")).toContain("calc(10px +");
+ expect(card.style.getPropertyValue("translate")).toContain("calc(20px +");
+ expect(card.style.getPropertyValue("rotate")).toContain("8deg");
+ expect(card.style.getPropertyValue("rotate")).toContain("--hf-studio-rotation");
+ expect(card.style.getPropertyValue("transform-origin")).toBe("center center");
+ });
+
+ it("does not compound stale studio variables during render reapply", () => {
+ const window = new Window();
+ window.document.body.innerHTML = `
+ <div id="card" style="
+ translate: var(--hf-studio-offset-x, 0px) var(--hf-studio-offset-y, 0px);
+ rotate: var(--hf-studio-rotation, 0deg);
+ "></div>
+ `;
+ const card = window.document.getElementById("card");
+ if (!(card instanceof window.HTMLElement)) {
+ throw new Error("card fixture missing");
+ }
+
+ const script = createStudioManualEditsRenderBodyScript(
+ JSON.stringify({
+ version: 1,
+ edits: [
+ {
+ kind: "path-offset",
+ target: { sourceFile: "index.html", id: "card" },
+ x: 12,
+ y: 24,
+ },
+ {
+ kind: "rotation",
+ target: { sourceFile: "index.html", id: "card" },
+ angle: 15,
+ },
+ ],
+ }),
+ );
+ if (!script) throw new Error("script fixture missing");
+
+ runScript(window, script);
+
+ expect(card.style.getPropertyValue("translate")).toBe(
+ "var(--hf-studio-offset-x, 0px) var(--hf-studio-offset-y, 0px)",
+ );
+ expect(card.style.getPropertyValue("rotate")).toBe("var(--hf-studio-rotation, 0deg)");
+ });
+
+ it("exposes a render reapply hook for thumbnails after layout settles", () => {
+ const window = new Window();
+ window.document.body.innerHTML = `<div id="card"></div>`;
+ const card = window.document.getElementById("card");
+ if (!(card instanceof window.HTMLElement)) {
+ throw new Error("card fixture missing");
+ }
+
+ const script = createStudioManualEditsRenderBodyScript(
+ JSON.stringify({
+ version: 1,
+ edits: [
+ {
+ kind: "path-offset",
+ target: { sourceFile: "index.html", id: "card" },
+ x: 12,
+ y: 24,
+ },
+ ],
+ }),
+ );
+ if (!script) throw new Error("script fixture missing");
+
+ runScript(window, script);
+ card.style.removeProperty("translate");
+
+ (
+ window as unknown as {
+ __hfStudioManualEditsApply?: () => number;
+ }
+ ).__hfStudioManualEditsApply?.();
+
+ expect(card.style.getPropertyValue("translate")).toContain("--hf-studio-offset-x");
+ });
+});
diff --git a/packages/core/src/studio-api/helpers/manualEditsRenderScript.ts b/packages/core/src/studio-api/helpers/manualEditsRenderScript.ts
new file mode 100644
index 0000000000..714b86de48
--- /dev/null
+++ b/packages/core/src/studio-api/helpers/manualEditsRenderScript.ts
@@ -0,0 +1,369 @@
+export interface StudioManualEditsRenderScriptOptions {
+ activeCompositionPath?: string | null;
+}
+
+export function createStudioManualEditsRenderBodyScript(
+ manifestContent: string,
+ options: StudioManualEditsRenderScriptOptions = {},
+): string | null {
+ if (!manifestContent.trim()) return null;
+ return `(${studioManualEditsRenderRuntime.toString()})(${JSON.stringify(manifestContent)}, ${JSON.stringify(options.activeCompositionPath ?? null)});`;
+}
+
+function studioManualEditsRenderRuntime(
+ manifestContent: string,
+ activeCompositionPath: string | null,
+): void {
+ const OFFSET_X_PROP = "--hf-studio-offset-x";
+ const OFFSET_Y_PROP = "--hf-studio-offset-y";
+ const WIDTH_PROP = "--hf-studio-width";
+ const HEIGHT_PROP = "--hf-studio-height";
+ const ROTATION_PROP = "--hf-studio-rotation";
+ const PATH_OFFSET_ATTR = "data-hf-studio-path-offset";
+ const BOX_SIZE_ATTR = "data-hf-studio-box-size";
+ const ROTATION_ATTR = "data-hf-studio-rotation";
+ const ORIGINAL_TRANSLATE_ATTR = "data-hf-studio-original-translate";
+ const ORIGINAL_ROTATE_ATTR = "data-hf-studio-original-rotate";
+ const WRAPPED_SEEK_PROP = "__hfStudioManualEditsWrapped";
+ const ROTATION_TRANSFORM_ORIGIN = "center center";
+
+ const finiteNumber = (value: unknown): number | null =>
+ typeof value === "number" && Number.isFinite(value) ? value : null;
+
+ const objectRecord = (value: unknown): Record<string, unknown> | null =>
+ value && typeof value === "object" ? (value as Record<string, unknown>) : null;
+
+ const runtimeWindow = window as Window & {
+ __hf?: { seek?: (time: number) => unknown };
+ __hfStudioManualEditsApply?: () => number;
+ __player?: { renderSeek?: (time: number) => unknown };
+ };
+
+ const parsedManifest = (() => {
+ try {
+ return objectRecord(JSON.parse(manifestContent));
+ } catch {
+ return null;
+ }
+ })();
+ const manifestEdits = Array.isArray(parsedManifest?.edits) ? parsedManifest.edits : [];
+ if (manifestEdits.length === 0) return;
+
+ const sourceFileForElement = (element: HTMLElement): string => {
+ let current: HTMLElement | null = element;
+ while (current) {
+ const sourceFile =
+ current.getAttribute("data-composition-file") ??
+ current.getAttribute("data-composition-src");
+ if (sourceFile) return sourceFile;
+ current = current.parentElement;
+ }
+ return activeCompositionPath ?? "index.html";
+ };
+
+ const elementMatchesSourceFile = (element: HTMLElement, sourceFile: string): boolean =>
+ sourceFileForElement(element) === sourceFile;
+
+ const styleUsesStudioOffset = (value: string): boolean =>
+ value.includes(OFFSET_X_PROP) || value.includes(OFFSET_Y_PROP);
+
+ const styleUsesStudioRotation = (value: string): boolean => value.includes(ROTATION_PROP);
+
+ const splitTopLevelWhitespace = (value: string): string[] => {
+ const parts: string[] = [];
+ let depth = 0;
+ let current = "";
+ for (const char of value.trim()) {
+ if (char === "(") depth += 1;
+ if (char === ")") depth = Math.max(0, depth - 1);
+ if (/\s/.test(char) && depth === 0) {
+ if (current) parts.push(current);
+ current = "";
+ } else {
+ current += char;
+ }
+ }
+ if (current) parts.push(current);
+ return parts;
+ };
+
+ const composeTranslate = (element: HTMLElement, x: string, y: string): string => {
+ const original = element.getAttribute(ORIGINAL_TRANSLATE_ATTR)?.trim();
+ if (!original || original === "none") return `${x} ${y}`;
+
+ const parts = splitTopLevelWhitespace(original);
+ if (parts.length === 1) return `calc(${parts[0]} + ${x}) ${y}`;
+ if (parts.length === 2) return `calc(${parts[0]} + ${x}) calc(${parts[1]} + ${y})`;
+ if (parts.length === 3) {
+ return `calc(${parts[0]} + ${x}) calc(${parts[1]} + ${y}) ${parts[2]}`;
+ }
+ return `${x} ${y}`;
+ };
+
+ const readStyleOrComputed = (element: HTMLElement, property: string): string => {
+ try {
+ return (
+ element.style.getPropertyValue(property) ||
+ getComputedStyle(element).getPropertyValue(property)
+ );
+ } catch {
+ return element.style.getPropertyValue(property);
+ }
+ };
+
+ const readTransformLonghandBase = (
+ element: HTMLElement,
+ property: "translate" | "rotate",
+ ): string => {
+ const value = readStyleOrComputed(element, property).trim();
+ return value === "none" ? "" : value;
+ };
+
+ const preparePathOffsetBase = (element: HTMLElement): void => {
+ const currentTranslate = readTransformLonghandBase(element, "translate");
+ const hasMarker = element.hasAttribute(PATH_OFFSET_ATTR);
+ const wasResetByAnimation = !styleUsesStudioOffset(currentTranslate);
+ if (!hasMarker) {
+ element.setAttribute(ORIGINAL_TRANSLATE_ATTR, wasResetByAnimation ? currentTranslate : "");
+ } else if (wasResetByAnimation) {
+ element.setAttribute(ORIGINAL_TRANSLATE_ATTR, currentTranslate);
+ }
+ };
+
+ const prepareRotationBase = (element: HTMLElement): void => {
+ const currentRotate = readTransformLonghandBase(element, "rotate");
+ const hasMarker = element.hasAttribute(ROTATION_ATTR);
+ const wasResetByAnimation = !styleUsesStudioRotation(currentRotate);
+ if (!hasMarker) {
+ element.setAttribute(ORIGINAL_ROTATE_ATTR, wasResetByAnimation ? currentRotate : "");
+ } else if (wasResetByAnimation) {
+ element.setAttribute(ORIGINAL_ROTATE_ATTR, currentRotate);
+ }
+ };
+
+ const querySelectorCandidates = (selector: string): HTMLElement[] => {
+ const isCandidate = (element: Element): element is HTMLElement =>
+ element instanceof HTMLElement;
+
+ const className = selector.match(/^\.([A-Za-z0-9_-]+)$/)?.[1];
+ if (className) {
+ return Array.from(document.getElementsByTagName("*")).filter(
+ (element): element is HTMLElement =>
+ isCandidate(element) && element.classList.contains(className),
+ );
+ }
+
+ if (/^[A-Za-z][A-Za-z0-9-]*$/.test(selector)) {
+ return Array.from(document.getElementsByTagName(selector)).filter(isCandidate);
+ }
+
+ return Array.from(document.querySelectorAll(selector)).filter(isCandidate);
+ };
+
+ const resolveTarget = (edit: Record<string, unknown>): HTMLElement | null => {
+ const targetRecord = objectRecord(edit.target);
+ if (!targetRecord) return null;
+
+ const sourceFile = typeof targetRecord.sourceFile === "string" ? targetRecord.sourceFile : "";
+ if (!sourceFile) return null;
+
+ const id = typeof targetRecord.id === "string" ? targetRecord.id : "";
+ if (id) {
+ const byId = document.getElementById(id);
+ if (byId instanceof HTMLElement && elementMatchesSourceFile(byId, sourceFile)) return byId;
+
+ const matchesById = [
+ document.documentElement,
+ ...Array.from(document.getElementsByTagName("*")),
+ ].filter(
+ (element): element is HTMLElement =>
+ element instanceof HTMLElement &&
+ element.id === id &&
+ elementMatchesSourceFile(element, sourceFile),
+ );
+ if (matchesById[0]) return matchesById[0];
+ }
+
+ const selector = typeof targetRecord.selector === "string" ? targetRecord.selector : "";
+ if (!selector) return null;
+
+ try {
+ const matches = querySelectorCandidates(selector).filter((element) =>
+ elementMatchesSourceFile(element, sourceFile),
+ );
+ const selectorIndex = finiteNumber(targetRecord.selectorIndex) ?? 0;
+ return matches[Math.max(0, Math.floor(selectorIndex))] ?? null;
+ } catch {
+ return null;
+ }
+ };
+
+ const roundRotationAngle = (angle: number): number => Math.round(angle * 10) / 10;
+
+ const isSimpleRotateAngle = (value: string): boolean =>
+ /^-?(?:\d+(?:\.\d+)?|\.\d+)(?:deg|rad|turn|grad)$/.test(value.trim());
+
+ const composeRotation = (element: HTMLElement, rotationValue: string): string => {
+ const original = element.getAttribute(ORIGINAL_ROTATE_ATTR)?.trim();
+ if (!original || original === "none" || !isSimpleRotateAngle(original)) {
+ return rotationValue;
+ }
+ return `calc(${original} + ${rotationValue})`;
+ };
+
+ const applyPathOffset = (element: HTMLElement, edit: Record<string, unknown>): void => {
+ const x = finiteNumber(edit.x);
+ const y = finiteNumber(edit.y);
+ if (x == null || y == null) return;
+ preparePathOffsetBase(element);
+ element.setAttribute(PATH_OFFSET_ATTR, "true");
+ element.style.setProperty(OFFSET_X_PROP, `${Math.round(x)}px`);
+ element.style.setProperty(OFFSET_Y_PROP, `${Math.round(y)}px`);
+ element.style.setProperty(
+ "translate",
+ composeTranslate(element, `var(${OFFSET_X_PROP}, 0px)`, `var(${OFFSET_Y_PROP}, 0px)`),
+ );
+ };
+
+ const readParentFlexBasisPixels = (
+ element: HTMLElement,
+ size: { width: number; height: number },
+ ): number | null => {
+ const parent = element.parentElement;
+ if (!parent) return null;
+ const styles = getComputedStyle(parent);
+ if (styles.display !== "flex" && styles.display !== "inline-flex") return null;
+ return Math.round(
+ Math.max(1, styles.flexDirection.startsWith("column") ? size.height : size.width),
+ );
+ };
+
+ const applyBoxSize = (element: HTMLElement, edit: Record<string, unknown>): void => {
+ const width = finiteNumber(edit.width);
+ const height = finiteNumber(edit.height);
+ if (width == null || height == null || width <= 0 || height <= 0) return;
+
+ const rounded = {
+ width: Math.round(Math.max(1, width)),
+ height: Math.round(Math.max(1, height)),
+ };
+ element.setAttribute(BOX_SIZE_ATTR, "true");
+ element.style.setProperty(WIDTH_PROP, `${rounded.width}px`);
+ element.style.setProperty(HEIGHT_PROP, `${rounded.height}px`);
+ element.style.setProperty("box-sizing", "border-box");
+ element.style.setProperty("width", `${rounded.width}px`);
+ element.style.setProperty("height", `${rounded.height}px`);
+ element.style.setProperty("min-width", "0px");
+ element.style.setProperty("min-height", "0px");
+ element.style.setProperty("max-width", "none");
+ element.style.setProperty("max-height", "none");
+
+ const flexBasis = readParentFlexBasisPixels(element, rounded);
+ if (flexBasis != null) {
+ element.style.setProperty("flex-basis", `${flexBasis}px`);
+ element.style.setProperty("flex-grow", "0");
+ element.style.setProperty("flex-shrink", "0");
+ }
+ if (getComputedStyle(element).display === "inline") {
+ element.style.setProperty("display", "inline-block");
+ }
+ };
+
+ const applyRotation = (element: HTMLElement, edit: Record<string, unknown>): void => {
+ const angle = finiteNumber(edit.angle);
+ if (angle == null) return;
+ prepareRotationBase(element);
+ element.setAttribute(ROTATION_ATTR, "true");
+ element.style.setProperty(ROTATION_PROP, `${roundRotationAngle(angle)}deg`);
+ element.style.setProperty("transform-origin", ROTATION_TRANSFORM_ORIGIN);
+ element.style.setProperty("rotate", composeRotation(element, `var(${ROTATION_PROP}, 0deg)`));
+ };
+
+ const applyManifest = (): number => {
+ let applied = 0;
+ for (const edit of manifestEdits) {
+ const editRecord = objectRecord(edit);
+ if (!editRecord) continue;
+ const element = resolveTarget(editRecord);
+ if (!element) continue;
+ if (editRecord.kind === "path-offset") applyPathOffset(element, editRecord);
+ if (editRecord.kind === "box-size") applyBoxSize(element, editRecord);
+ if (editRecord.kind === "rotation") applyRotation(element, editRecord);
+ applied += 1;
+ }
+ return applied;
+ };
+ runtimeWindow.__hfStudioManualEditsApply = applyManifest;
+
+ const markWrapped = (fn: (time: number) => unknown): void => {
+ try {
+ Object.defineProperty(fn, WRAPPED_SEEK_PROP, {
+ configurable: false,
+ enumerable: false,
+ value: true,
+ });
+ } catch {
+ try {
+ (fn as unknown as Record<string, unknown>)[WRAPPED_SEEK_PROP] = true;
+ } catch {
+ // Ignore non-extensible functions.
+ }
+ }
+ };
+
+ const isWrapped = (fn: (time: number) => unknown): boolean =>
+ Boolean((fn as unknown as Record<string, unknown>)[WRAPPED_SEEK_PROP]);
+
+ const wrapFunction = (
+ get: () => ((time: number) => unknown) | undefined,
+ set: (fn: (time: number) => unknown) => void,
+ ): boolean => {
+ const fn = get();
+ if (!fn) return false;
+ const seek = fn as (time: number) => unknown;
+ if (isWrapped(seek)) {
+ applyManifest();
+ return true;
+ }
+
+ const wrappedSeek = function (this: unknown, time: number): unknown {
+ const result = seek.call(this, time);
+ applyManifest();
+ return result;
+ };
+ markWrapped(wrappedSeek);
+ set(wrappedSeek);
+ applyManifest();
+ return true;
+ };
+
+ const wrapSeekFunctions = (): boolean => {
+ const wrappedHfSeek = wrapFunction(
+ () => runtimeWindow.__hf?.seek,
+ (fn) => {
+ if (runtimeWindow.__hf) runtimeWindow.__hf.seek = fn;
+ },
+ );
+ const wrappedPlayerRenderSeek = wrapFunction(
+ () => runtimeWindow.__player?.renderSeek,
+ (fn) => {
+ if (runtimeWindow.__player) runtimeWindow.__player.renderSeek = fn;
+ },
+ );
+ return wrappedHfSeek || wrappedPlayerRenderSeek;
+ };
+
+ if (document.readyState === "loading") {
+ document.addEventListener("DOMContentLoaded", () => applyManifest(), { once: true });
+ } else {
+ applyManifest();
+ }
+
+ wrapSeekFunctions();
+ let remainingSeekWrapAttempts = 120;
+ const seekWrapInterval = setInterval(() => {
+ wrapSeekFunctions();
+ remainingSeekWrapAttempts -= 1;
+ if (remainingSeekWrapAttempts <= 0) clearInterval(seekWrapInterval);
+ }, 50);
+}
diff --git a/packages/core/src/studio-api/helpers/screenshotClip.ts b/packages/core/src/studio-api/helpers/screenshotClip.ts
index 715132daf5..a1db59033e 100644
--- a/packages/core/src/studio-api/helpers/screenshotClip.ts
+++ b/packages/core/src/studio-api/helpers/screenshotClip.ts
@@ -5,8 +5,15 @@ export interface ScreenshotClip {
height: number;
}
-export function getElementScreenshotClip(selector: string): ScreenshotClip | undefined {
- const el = document.querySelector(selector);
+export function getElementScreenshotClip(
+ selector: string,
+ selectorIndex?: number,
+): ScreenshotClip | undefined {
+ const matches = Array.from(document.querySelectorAll(selector)).filter(
+ (el): el is HTMLElement => el instanceof HTMLElement,
+ );
+ const safeIndex = Math.max(0, Math.min(matches.length - 1, Math.floor(selectorIndex ?? 0)));
+ const el = matches[safeIndex] ?? null;
if (!(el instanceof HTMLElement)) return undefined;
const rect = el.getBoundingClientRect();
if (rect.width < 4 || rect.height < 4) return undefined;
diff --git a/packages/core/src/studio-api/helpers/subComposition.test.ts b/packages/core/src/studio-api/helpers/subComposition.test.ts
index 9d4378d73a..e2121b12f8 100644
--- a/packages/core/src/studio-api/helpers/subComposition.test.ts
+++ b/packages/core/src/studio-api/helpers/subComposition.test.ts
@@ -23,6 +23,7 @@ describe("buildSubCompositionHtml", () => {
"compositions/hero.html": `<template id="hero-template">
<div data-composition-id="hero" data-width="1920" data-height="1080">
<img src="../logo.png" alt="Logo" />
+ <div style="background-image: url('../poster.png')"></div>
<style>
@font-face {
font-family: "Brand Sans";
@@ -42,8 +43,10 @@ describe("buildSubCompositionHtml", () => {
expect(html).toContain('<base href="/api/projects/demo/preview/">');
expect(html).toContain('src="logo.png"');
+ expect(html).toContain("background-image: url('poster.png')");
expect(html).toContain('url("fonts/brand.woff2")');
expect(html).not.toContain('src="../logo.png"');
+ expect(html).not.toContain("url('../poster.png')");
expect(html).not.toContain('url("../fonts/brand.woff2")');
});
});
diff --git a/packages/core/src/studio-api/helpers/subComposition.ts b/packages/core/src/studio-api/helpers/subComposition.ts
index 5fb7cb5747..859779a3d7 100644
--- a/packages/core/src/studio-api/helpers/subComposition.ts
+++ b/packages/core/src/studio-api/helpers/subComposition.ts
@@ -1,7 +1,11 @@
import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { parseHTML } from "linkedom";
-import { rewriteAssetPaths, rewriteCssAssetUrls } from "../../compiler/rewriteSubCompPaths.js";
+import {
+ rewriteAssetPaths,
+ rewriteCssAssetUrls,
+ rewriteInlineStyleAssetUrls,
+} from "../../compiler/rewriteSubCompPaths.js";
/**
* Build a standalone HTML page for a sub-composition.
@@ -36,6 +40,14 @@ export function buildSubCompositionHtml(
el.setAttribute(attr, value);
},
);
+ rewriteInlineStyleAssetUrls(
+ contentDoc.querySelectorAll("[style]"),
+ compPath,
+ (el: Element) => el.getAttribute("style"),
+ (el: Element, value: string) => {
+ el.setAttribute("style", value);
+ },
+ );
for (const styleEl of contentDoc.querySelectorAll("style")) {
styleEl.textContent = rewriteCssAssetUrls(styleEl.textContent || "", compPath);
}
diff --git a/packages/core/src/studio-api/index.ts b/packages/core/src/studio-api/index.ts
index 897de4009d..011c8b0862 100644
--- a/packages/core/src/studio-api/index.ts
+++ b/packages/core/src/studio-api/index.ts
@@ -4,3 +4,7 @@ export { isSafePath, walkDir } from "./helpers/safePath.js";
export { getMimeType, MIME_TYPES } from "./helpers/mime.js";
export { buildSubCompositionHtml } from "./helpers/subComposition.js";
export { getElementScreenshotClip, type ScreenshotClip } from "./helpers/screenshotClip.js";
+export {
+ createStudioManualEditsRenderBodyScript,
+ type StudioManualEditsRenderScriptOptions,
+} from "./helpers/manualEditsRenderScript.js";
diff --git a/packages/core/src/studio-api/routes/fonts.ts b/packages/core/src/studio-api/routes/fonts.ts
new file mode 100644
index 0000000000..256a6acc91
--- /dev/null
+++ b/packages/core/src/studio-api/routes/fonts.ts
@@ -0,0 +1,247 @@
+import { execFileSync } from "node:child_process";
+import { existsSync, readdirSync, statSync } from "node:fs";
+import { homedir, platform } from "node:os";
+import { join } from "node:path";
+import type { Hono } from "hono";
+
+const FONT_EXT_RE = /\.(otf|ttf|ttc|woff2?)$/i;
+const MAX_FONT_RESULTS = 2000;
+const GOOGLE_FONTS_METADATA_URL = "https://fonts.google.com/metadata/fonts";
+const GOOGLE_FONTS_FETCH_TIMEOUT_MS = 3000;
+let cachedFonts: string[] | null = null;
+let cachedGoogleFonts: string[] | null = null;
+
+const STYLE_SUFFIXES = new Set([
+ "black",
+ "bold",
+ "book",
+ "condensed",
+ "demi",
+ "demibold",
+ "display",
+ "extra",
+ "extrabold",
+ "hairline",
+ "heavy",
+ "italic",
+ "light",
+ "medium",
+ "normal",
+ "regular",
+ "roman",
+ "semibold",
+ "thin",
+ "ultra",
+ "ultralight",
+]);
+
+const GOOGLE_FONT_FALLBACKS = [
+ "Inter",
+ "Roboto",
+ "Open Sans",
+ "Montserrat",
+ "Poppins",
+ "Lato",
+ "Oswald",
+ "Raleway",
+ "Nunito",
+ "Playfair Display",
+ "Merriweather",
+ "Source Sans 3",
+ "Source Serif 4",
+ "Source Code Pro",
+ "DM Sans",
+ "Space Grotesk",
+ "Space Mono",
+ "Bebas Neue",
+ "Outfit",
+ "JetBrains Mono",
+];
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null;
+}
+
+function fontDirectories(): string[] {
+ const home = homedir();
+ if (platform() === "darwin") {
+ return [
+ join(home, "Library", "Fonts"),
+ "/Library/Fonts",
+ "/System/Library/Fonts",
+ "/System/Library/Fonts/Supplemental",
+ ];
+ }
+ if (platform() === "win32") {
+ return [join(process.env.WINDIR || "C:\\Windows", "Fonts")];
+ }
+ return [
+ join(home, ".fonts"),
+ join(home, ".local", "share", "fonts"),
+ "/usr/local/share/fonts",
+ "/usr/share/fonts",
+ ];
+}
+
+function toFamilyName(fileName: string): string | null {
+ const withoutExt = fileName.replace(FONT_EXT_RE, "");
+ if (!withoutExt || withoutExt.startsWith(".")) return null;
+
+ const spaced = withoutExt
+ .replace(/[_-]+/g, " ")
+ .replace(/([a-z])([A-Z])/g, "$1 $2")
+ .replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2")
+ .replace(/\s+/g, " ")
+ .trim();
+ const words = spaced.split(" ").filter(Boolean);
+ while (words.length > 1 && STYLE_SUFFIXES.has((words.at(-1) ?? "").toLowerCase())) {
+ words.pop();
+ }
+
+ const family = words.join(" ").trim();
+ return family.length >= 2 ? family : null;
+}
+
+function collectMacSystemProfilerFonts(): string[] {
+ if (platform() !== "darwin") return [];
+
+ let parsed: unknown;
+ try {
+ const raw = execFileSync("system_profiler", ["SPFontsDataType", "-json"], {
+ encoding: "utf8",
+ maxBuffer: 12 * 1024 * 1024,
+ timeout: 5000,
+ });
+ parsed = JSON.parse(raw);
+ } catch {
+ return [];
+ }
+
+ if (!isRecord(parsed) || !Array.isArray(parsed.SPFontsDataType)) return [];
+ const fonts: string[] = [];
+
+ for (const fontEntry of parsed.SPFontsDataType) {
+ if (!isRecord(fontEntry)) continue;
+ const typefaces = fontEntry.typefaces;
+ if (!Array.isArray(typefaces)) continue;
+
+ for (const typeface of typefaces) {
+ if (!isRecord(typeface)) continue;
+ const family = typeface.family;
+ const fullName = typeface.fullname;
+ const name = typeface._name;
+ if (typeof family === "string" && family.trim()) {
+ fonts.push(family.trim());
+ } else if (typeof fullName === "string" && fullName.trim()) {
+ fonts.push(fullName.trim());
+ } else if (typeof name === "string" && name.trim()) {
+ fonts.push(name.trim());
+ }
+ }
+ }
+
+ return fonts;
+}
+
+function collectFontsFromDir(dir: string, depth = 0): string[] {
+ if (!existsSync(dir) || depth > 2) return [];
+ const fonts: string[] = [];
+
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ const fullPath = join(dir, entry.name);
+ if (entry.isDirectory()) {
+ fonts.push(...collectFontsFromDir(fullPath, depth + 1));
+ continue;
+ }
+ if (!entry.isFile() || !FONT_EXT_RE.test(entry.name)) continue;
+ try {
+ if (!statSync(fullPath).isFile()) continue;
+ } catch {
+ continue;
+ }
+ const family = toFamilyName(entry.name);
+ if (family) fonts.push(family);
+ }
+
+ return fonts;
+}
+
+function listInstalledFontFamilies(): string[] {
+ if (cachedFonts) return cachedFonts;
+ const families = new Set<string>();
+
+ for (const family of collectMacSystemProfilerFonts()) {
+ families.add(family);
+ if (families.size >= MAX_FONT_RESULTS) break;
+ }
+
+ for (const dir of fontDirectories()) {
+ for (const family of collectFontsFromDir(dir)) {
+ families.add(family);
+ if (families.size >= MAX_FONT_RESULTS) break;
+ }
+ if (families.size >= MAX_FONT_RESULTS) break;
+ }
+
+ cachedFonts = Array.from(families).sort((a, b) => a.localeCompare(b));
+ return cachedFonts;
+}
+
+function parseGoogleFontMetadata(value: unknown): string[] {
+ if (!isRecord(value) || !Array.isArray(value.familyMetadataList)) return [];
+ const families: string[] = [];
+ for (const entry of value.familyMetadataList) {
+ if (!isRecord(entry) || typeof entry.family !== "string") continue;
+ families.push(entry.family);
+ }
+ return families;
+}
+
+function stripGoogleJsonGuard(raw: string): string {
+ const prefix = ")]}'";
+ if (!raw.startsWith(prefix)) return raw;
+
+ let index = prefix.length;
+ while (
+ index < raw.length &&
+ (raw[index] === " " ||
+ raw[index] === "\n" ||
+ raw[index] === "\r" ||
+ raw[index] === "\t" ||
+ raw[index] === "\f")
+ ) {
+ index += 1;
+ }
+
+ return raw.slice(index);
+}
+
+async function listGoogleFontFamilies(): Promise<string[]> {
+ if (cachedGoogleFonts) return cachedGoogleFonts;
+
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), GOOGLE_FONTS_FETCH_TIMEOUT_MS);
+
+ try {
+ const response = await fetch(GOOGLE_FONTS_METADATA_URL, { signal: controller.signal });
+ if (!response.ok) {
+ cachedGoogleFonts = GOOGLE_FONT_FALLBACKS;
+ return cachedGoogleFonts;
+ }
+ const raw = await response.text();
+ const jsonText = stripGoogleJsonGuard(raw);
+ const families = parseGoogleFontMetadata(JSON.parse(jsonText));
+ cachedGoogleFonts = families.length > 0 ? families : GOOGLE_FONT_FALLBACKS;
+ } catch {
+ cachedGoogleFonts = GOOGLE_FONT_FALLBACKS;
+ } finally {
+ clearTimeout(timer);
+ }
+
+ return cachedGoogleFonts;
+}
+
+export function registerFontRoutes(api: Hono): void {
+ api.get("/fonts", (c) => c.json({ fonts: listInstalledFontFamilies() }));
+ api.get("/fonts/google", async (c) => c.json({ fonts: await listGoogleFontFamilies() }));
+}
diff --git a/packages/core/src/studio-api/routes/projects.ts b/packages/core/src/studio-api/routes/projects.ts
index 8df3104339..738775de84 100644
--- a/packages/core/src/studio-api/routes/projects.ts
+++ b/packages/core/src/studio-api/routes/projects.ts
@@ -25,6 +25,6 @@ export function registerProjectRoutes(api: Hono, adapter: StudioApiAdapter): voi
const project = await adapter.resolveProject(c.req.param("id"));
if (!project) return c.json({ error: "not found" }, 404);
const files = walkDir(project.dir);
- return c.json({ id: project.id, files });
+ return c.json({ id: project.id, dir: project.dir, title: project.title, files });
});
}
diff --git a/packages/core/src/studio-api/routes/thumbnail.test.ts b/packages/core/src/studio-api/routes/thumbnail.test.ts
index bb609f81ed..0c2697aa8c 100644
--- a/packages/core/src/studio-api/routes/thumbnail.test.ts
+++ b/packages/core/src/studio-api/routes/thumbnail.test.ts
@@ -1,6 +1,6 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { Hono } from "hono";
-import { mkdtempSync, rmSync } from "node:fs";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { registerThumbnailRoutes } from "./thumbnail";
@@ -94,4 +94,84 @@ describe("registerThumbnailRoutes", () => {
}),
);
});
+
+ it("forwards selector occurrence indexes to thumbnail generation", async () => {
+ const adapter = createAdapter();
+ const app = new Hono();
+ registerThumbnailRoutes(app, adapter);
+
+ const response = await app.request(
+ "http://localhost/projects/demo/thumbnail/index.html?t=1.2&selector=.card&selectorIndex=2",
+ );
+
+ expect(response.status).toBe(200);
+ expect(adapter.generateThumbnail).toHaveBeenCalledWith(
+ expect.objectContaining({
+ selector: ".card",
+ selectorIndex: 2,
+ }),
+ );
+ });
+
+ it("keeps url thumbnail versions separated in the disk cache", async () => {
+ const adapter = createAdapter();
+ const app = new Hono();
+ registerThumbnailRoutes(app, adapter);
+
+ await app.request("http://localhost/projects/demo/thumbnail/index.html?t=2&v=old");
+ await app.request("http://localhost/projects/demo/thumbnail/index.html?t=2&v=old");
+ await app.request("http://localhost/projects/demo/thumbnail/index.html?t=2&v=new");
+
+ expect(adapter.generateThumbnail).toHaveBeenCalledTimes(2);
+ });
+
+ it("keeps changed composition dimensions separated in the disk cache", async () => {
+ const adapter = createAdapter();
+ const project = await adapter.resolveProject("demo");
+ if (!project) throw new Error("missing project");
+ const app = new Hono();
+ registerThumbnailRoutes(app, adapter);
+
+ const indexPath = join(project.dir, "index.html");
+ writeFileSync(indexPath, `<div data-composition-id="main" data-width="640" data-height="360">`);
+ await app.request("http://localhost/projects/demo/thumbnail/index.html?t=2&v=test");
+
+ writeFileSync(
+ indexPath,
+ `<div data-composition-id="main" data-width="1280" data-height="720">`,
+ );
+ await app.request("http://localhost/projects/demo/thumbnail/index.html?t=2&v=test");
+
+ expect(adapter.generateThumbnail).toHaveBeenCalledTimes(2);
+ expect(adapter.generateThumbnail).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ width: 1280,
+ height: 720,
+ }),
+ );
+ });
+
+ it("keeps changed studio manual edits separated in the disk cache", async () => {
+ const adapter = createAdapter();
+ const project = await adapter.resolveProject("demo");
+ if (!project) throw new Error("missing project");
+ const app = new Hono();
+ registerThumbnailRoutes(app, adapter);
+
+ const indexPath = join(project.dir, "index.html");
+ writeFileSync(indexPath, `<div data-composition-id="main" data-width="640" data-height="360">`);
+ const manualEditsDir = join(project.dir, ".hyperframes");
+ mkdirSync(manualEditsDir, { recursive: true });
+ const manualEditsPath = join(manualEditsDir, "studio-manual-edits.json");
+ writeFileSync(manualEditsPath, `{"version":1,"edits":[]}`);
+
+ await app.request("http://localhost/projects/demo/thumbnail/index.html?t=2&v=test");
+ writeFileSync(
+ manualEditsPath,
+ `{"version":1,"edits":[{"kind":"rotation","target":{"sourceFile":"index.html","id":"card"},"angle":30}]}`,
+ );
+ await app.request("http://localhost/projects/demo/thumbnail/index.html?t=2&v=test");
+
+ expect(adapter.generateThumbnail).toHaveBeenCalledTimes(2);
+ });
});
diff --git a/packages/core/src/studio-api/routes/thumbnail.ts b/packages/core/src/studio-api/routes/thumbnail.ts
index ef4b4ec53b..dd8a0aeb08 100644
--- a/packages/core/src/studio-api/routes/thumbnail.ts
+++ b/packages/core/src/studio-api/routes/thumbnail.ts
@@ -1,9 +1,11 @@
import type { Hono } from "hono";
-import { existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
+import { existsSync, readFileSync, writeFileSync, mkdirSync, statSync } from "node:fs";
import { join } from "node:path";
+import { createHash } from "node:crypto";
import type { StudioApiAdapter } from "../types.js";
-const THUMBNAIL_CACHE_VERSION = "v3";
+const THUMBNAIL_CACHE_VERSION = "v4";
+const STUDIO_MANUAL_EDITS_PATH = ".hyperframes/studio-manual-edits.json";
export function registerThumbnailRoutes(api: Hono, adapter: StudioApiAdapter): void {
api.get("/projects/:id/thumbnail/*", async (c) => {
@@ -27,13 +29,19 @@ export function registerThumbnailRoutes(api: Hono, adapter: StudioApiAdapter): v
const selector = url.searchParams.get("selector") || undefined;
const format = url.searchParams.get("format") === "png" ? "png" : "jpeg";
const contentType = format === "png" ? "image/png" : "image/jpeg";
+ const rawSelectorIndex = Number.parseInt(url.searchParams.get("selectorIndex") || "0", 10);
+ const selectorIndex =
+ Number.isFinite(rawSelectorIndex) && rawSelectorIndex > 0 ? rawSelectorIndex : undefined;
+ const urlVersion = url.searchParams.get("v") || "";
// Determine composition dimensions from HTML
let compW = vpWidth || 1920;
let compH = vpHeight || 1080;
+ let sourceMtime = 0;
if (!vpWidth) {
const htmlFile = join(project.dir, compPath);
if (existsSync(htmlFile)) {
+ sourceMtime = Math.round(statSync(htmlFile).mtimeMs);
const html = readFileSync(htmlFile, "utf-8");
const wMatch = html.match(/data-width=["'](\d+)["']/);
const hMatch = html.match(/data-height=["'](\d+)["']/);
@@ -41,6 +49,13 @@ export function registerThumbnailRoutes(api: Hono, adapter: StudioApiAdapter): v
if (hMatch?.[1]) compH = parseInt(hMatch[1]);
}
}
+ const manualEditsFile = join(project.dir, STUDIO_MANUAL_EDITS_PATH);
+ let manualEditsKey = "";
+ if (existsSync(manualEditsFile)) {
+ const manualEditsContent = readFileSync(manualEditsFile, "utf-8");
+ manualEditsKey = `_${createHash("sha1").update(manualEditsContent).digest("hex").slice(0, 16)}`;
+ sourceMtime = Math.max(sourceMtime, Math.round(statSync(manualEditsFile).mtimeMs));
+ }
const previewUrl =
compPath === "index.html"
@@ -50,9 +65,12 @@ export function registerThumbnailRoutes(api: Hono, adapter: StudioApiAdapter): v
// Cache
const cacheDir = join(project.dir, ".thumbnails");
const selectorKey = selector
- ? `_${selector.replace(/[^a-zA-Z0-9_-]+/g, "_").slice(0, 80)}`
+ ? `_${selector.replace(/[^a-zA-Z0-9_-]+/g, "_").slice(0, 80)}_${selectorIndex ?? 0}`
+ : "";
+ const urlVersionKey = urlVersion
+ ? `_${urlVersion.replace(/[^a-zA-Z0-9_-]+/g, "_").slice(0, 32)}`
: "";
- const cacheKey = `${THUMBNAIL_CACHE_VERSION}_${format}_${compPath.replace(/\//g, "_")}_${seekTime.toFixed(2)}${selectorKey}.${format === "png" ? "png" : "jpg"}`;
+ const cacheKey = `${THUMBNAIL_CACHE_VERSION}${urlVersionKey}${manualEditsKey}_${format}_${compPath.replace(/\//g, "_")}_${compW}x${compH}_${sourceMtime}_${seekTime.toFixed(2)}${selectorKey}.${format === "png" ? "png" : "jpg"}`;
const cachePath = join(cacheDir, cacheKey);
if (existsSync(cachePath)) {
return new Response(new Uint8Array(readFileSync(cachePath)), {
@@ -70,6 +88,7 @@ export function registerThumbnailRoutes(api: Hono, adapter: StudioApiAdapter): v
previewUrl,
selector,
format,
+ selectorIndex,
});
if (!buffer) {
return c.json({ error: "Thumbnail generation returned null" }, 500);
diff --git a/packages/core/src/studio-api/types.ts b/packages/core/src/studio-api/types.ts
index 71aa963719..62c00eb2cf 100644
--- a/packages/core/src/studio-api/types.ts
+++ b/packages/core/src/studio-api/types.ts
@@ -73,6 +73,7 @@ export interface StudioApiAdapter {
previewUrl: string;
selector?: string;
format?: "jpeg" | "png";
+ selectorIndex?: number;
}) => Promise<Buffer | null>;
/** Optional: resolve session ID to project (multi-project mode). */
diff --git a/packages/producer/src/services/fileServer.test.ts b/packages/producer/src/services/fileServer.test.ts
index 426dfb31dc..643fc34dcf 100644
--- a/packages/producer/src/services/fileServer.test.ts
+++ b/packages/producer/src/services/fileServer.test.ts
@@ -153,6 +153,40 @@ describe("isPathInside", () => {
});
describe("createFileServer", () => {
+ it("appends additional body scripts after configured body scripts", async () => {
+ const projectDir = mkdtempSync(join(tmpdir(), "hf-file-server-extra-body-"));
+
+ try {
+ writeFileSync(
+ join(projectDir, "index.html"),
+ "<!doctype html><html><head></head><body></body></html>",
+ );
+
+ const server = await createFileServer({
+ projectDir,
+ preHeadScripts: [],
+ headScripts: [],
+ bodyScripts: ["window.__bodyScript = true;"],
+ additionalBodyScripts: ["window.__additionalBodyScript = true;"],
+ });
+
+ try {
+ const response = await fetch(`${server.url}/index.html`);
+ const html = await response.text();
+
+ expect(response.status).toBe(200);
+ expect(html.indexOf("window.__bodyScript = true;")).toBeGreaterThanOrEqual(0);
+ expect(html.indexOf("window.__additionalBodyScript = true;")).toBeGreaterThan(
+ html.indexOf("window.__bodyScript = true;"),
+ );
+ } finally {
+ server.close();
+ }
+ } finally {
+ rmSync(projectDir, { recursive: true, force: true });
+ }
+ });
+
it("serves asset files through project-root symlinked directories", async () => {
const workspaceDir = mkdtempSync(join(tmpdir(), "hf-file-server-symlink-assets-"));
const adsDir = join(workspaceDir, "Ads");
diff --git a/packages/producer/src/services/fileServer.ts b/packages/producer/src/services/fileServer.ts
index 2f96c6e9a0..bc36072c36 100644
--- a/packages/producer/src/services/fileServer.ts
+++ b/packages/producer/src/services/fileServer.ts
@@ -420,6 +420,8 @@ export interface FileServerOptions {
headScripts?: string[];
/** Scripts injected before </body> of index.html. Default: render mode extension. */
bodyScripts?: string[];
+ /** Scripts injected after bodyScripts before </body> of index.html. */
+ additionalBodyScripts?: string[];
/** Strip embedded runtime scripts from HTML before injection. Default: true. */
stripEmbeddedRuntime?: boolean;
}
@@ -442,7 +444,10 @@ export function createFileServer(options: FileServerOptions): Promise<FileServer
const preHeadScripts = [HF_EARLY_STUB, ...(options.preHeadScripts ?? [])];
// Default scripts: Hyperframe runtime in <head>, render mode in </body>
const headScripts = options.headScripts ?? [getVerifiedHyperframeRuntimeSource()];
- const bodyScripts = options.bodyScripts ?? [RENDER_MODE_SCRIPT, HF_BRIDGE_SCRIPT];
+ const bodyScripts = [
+ ...(options.bodyScripts ?? [RENDER_MODE_SCRIPT, HF_BRIDGE_SCRIPT]),
+ ...(options.additionalBodyScripts ?? []),
+ ];
const app = new Hono();
diff --git a/packages/producer/src/services/htmlCompiler.test.ts b/packages/producer/src/services/htmlCompiler.test.ts
index d7daa58c1f..ca89518a22 100644
--- a/packages/producer/src/services/htmlCompiler.test.ts
+++ b/packages/producer/src/services/htmlCompiler.test.ts
@@ -668,6 +668,7 @@ describe("template-wrapped sub-composition media offsets", () => {
const host = document.querySelector("#scene-host");
expect(host?.getAttribute("data-composition-id")).toBe("scene");
+ expect(host?.getAttribute("data-composition-file")).toBe("compositions/scene.html");
expect(host?.getAttribute("data-start")).toBe("20");
expect(host?.getAttribute("data-width")).toBe("640");
expect(host?.querySelector(".title")?.textContent).toBe("Scene");
@@ -715,6 +716,10 @@ describe("template-wrapped sub-composition media offsets", () => {
const host = document.querySelector("#scene-host");
expect(host?.getAttribute("data-composition-id")).toBeNull();
+ expect(host?.getAttribute("data-composition-file")).toBe("compositions/scene.html");
+ expect(
+ host?.querySelector('[data-composition-id="scene"]')?.getAttribute("data-composition-file"),
+ ).toBe("compositions/scene.html");
expect(host?.querySelector('[data-composition-id="scene"] .title')?.textContent).toBe("Scene");
expect(compiled.html).toContain('var __hfCompId = "scene";');
});
diff --git a/packages/producer/src/services/htmlCompiler.ts b/packages/producer/src/services/htmlCompiler.ts
index 7adeb2e825..307a0f3e44 100644
--- a/packages/producer/src/services/htmlCompiler.ts
+++ b/packages/producer/src/services/htmlCompiler.ts
@@ -681,6 +681,7 @@ function inlineSubCompositions(
const innerH = innerRoot.getAttribute("data-height");
if (innerW && !host.getAttribute("data-width")) host.setAttribute("data-width", innerW);
if (innerH && !host.getAttribute("data-height")) host.setAttribute("data-height", innerH);
+ innerRoot.setAttribute("data-composition-file", srcPath);
innerRoot.querySelectorAll("style, script").forEach((el) => el.remove());
host.innerHTML = compId ? innerRoot.innerHTML || "" : innerRoot.outerHTML || "";
} else {
@@ -688,6 +689,7 @@ function inlineSubCompositions(
host.innerHTML = contentDoc.toString();
}
+ host.setAttribute("data-composition-file", srcPath);
host.removeAttribute("data-composition-src");
// Set explicit pixel dimensions on the host element so children using
diff --git a/packages/producer/src/services/renderOrchestrator.ts b/packages/producer/src/services/renderOrchestrator.ts
index d97722e17e..cb1a59e988 100644
--- a/packages/producer/src/services/renderOrchestrator.ts
+++ b/packages/producer/src/services/renderOrchestrator.ts
@@ -258,6 +258,8 @@ export interface RenderConfig {
producerConfig?: EngineConfig;
/** Custom logger. Defaults to console-based defaultLogger. */
logger?: ProducerLogger;
+ /** Extra scripts injected after the render runtime before </body> in index.html. */
+ renderBodyScripts?: string[];
/** Override CRF for the video encoder. Mutually exclusive with `videoBitrate`. */
crf?: number;
/** Target video bitrate (e.g. "10M"). Mutually exclusive with `crf`. */
@@ -2039,6 +2041,7 @@ export async function executeRenderJob(
compiledDir: join(workDir, "compiled"),
port: 0,
preHeadScripts: [VIRTUAL_TIME_SHIM],
+ additionalBodyScripts: job.config.renderBodyScripts,
});
assertNotAborted();
@@ -2499,6 +2502,7 @@ export async function executeRenderJob(
compiledDir: join(workDir, "compiled"),
port: 0,
preHeadScripts: [VIRTUAL_TIME_SHIM],
+ additionalBodyScripts: job.config.renderBodyScripts,
});
assertNotAborted();
}
diff --git a/packages/studio/src/App.tsx b/packages/studio/src/App.tsx
index ce4afc1c6b..03a17e2dd9 100644
--- a/packages/studio/src/App.tsx
+++ b/packages/studio/src/App.tsx
@@ -19,13 +19,15 @@ import type { TimelineElement } from "./player";
import { LintModal } from "./components/LintModal";
import type { LintFinding } from "./components/LintModal";
import { MediaPreview } from "./components/MediaPreview";
-import { isMediaFile } from "./utils/mediaTypes";
+import { RotateCcw, RotateCw } from "./icons/SystemIcons";
+import { FONT_EXT, isMediaFile } from "./utils/mediaTypes";
import {
buildTimelineAssetId,
buildTimelineAssetInsertHtml,
buildTimelineFileDropPlacements,
getTimelineAssetKind,
insertTimelineAssetIntoSource,
+ resolveTimelineAssetInitialGeometry,
resolveTimelineAssetSrc,
type TimelineAssetKind,
} from "./utils/timelineAssetDrop";
@@ -35,7 +37,14 @@ import { CaptionTimeline } from "./captions/components/CaptionTimeline";
import { useCaptionStore } from "./captions/store";
import { useCaptionSync } from "./captions/hooks/useCaptionSync";
import { parseCaptionComposition } from "./captions/parser";
-import { applyPatchByTarget, readAttributeByTarget } from "./utils/sourcePatcher";
+import { copyTextToClipboard } from "./utils/clipboard";
+import { usePersistentEditHistory } from "./hooks/usePersistentEditHistory";
+import {
+ applyPatchByTarget,
+ readAttributeByTarget,
+ readTagSnippetByTarget,
+ type PatchOperation,
+} from "./utils/sourcePatcher";
import {
buildTrackZIndexMap,
formatTimelineAttributeNumber,
@@ -45,12 +54,55 @@ import {
getTimelineZoomPercent,
} from "./player/components/timelineZoom";
import {
+ TIMELINE_TOGGLE_SHORTCUT_LABEL,
+ getTimelineEditorHintDismissed,
getTimelineToggleTitle,
+ setTimelineEditorHintDismissed,
shouldHandleTimelineToggleHotkey,
} from "./utils/timelineDiscovery";
import { buildFrameCaptureFilename, buildFrameCaptureUrl } from "./utils/frameCapture";
import { buildProjectHash, parseProjectIdFromHash } from "./utils/projectRouting";
import { Camera } from "./icons/SystemIcons";
+import { PropertyPanel } from "./components/editor/PropertyPanel";
+import { googleFontStylesheetUrl } from "./components/editor/fontCatalog";
+import {
+ fontFamilyFromAssetPath,
+ importedFontFaceCss,
+ type ImportedFontAsset,
+} from "./components/editor/fontAssets";
+import {
+ DomEditOverlay,
+ type DomEditGroupPathOffsetCommit,
+} from "./components/editor/DomEditOverlay";
+import {
+ buildDefaultDomEditTextField,
+ buildDomEditStylePatchOperation,
+ buildDomEditTextPatchOperation,
+ buildElementAgentPrompt,
+ findElementForSelection,
+ getDomEditTargetKey,
+ isTextEditableSelection,
+ serializeDomEditTextFields,
+ resolveDomEditSelection,
+ type DomEditTextField,
+ type DomEditSelection,
+} from "./components/editor/domEditing";
+import {
+ STUDIO_MANUAL_EDITS_PATH,
+ applyStudioManualEditManifest,
+ emptyStudioManualEditManifest,
+ installStudioManualEditSeekReapply,
+ isStudioManualEditManifestPath,
+ parseStudioManualEditManifest,
+ readStudioFileChangePath,
+ removeStudioManualEditsForSelection,
+ serializeStudioManualEditManifest,
+ type StudioManualEditManifest,
+ upsertStudioBoxSizeEdit,
+ upsertStudioPathOffsetEdit,
+ upsertStudioRotationEdit,
+} from "./components/editor/manualEdits";
+import { saveProjectFilesWithHistory } from "./utils/studioFileHistory";
interface EditingFile {
path: string;
@@ -66,6 +118,430 @@ function getTimelineElementLabel(element: TimelineElement): string {
return element.label || element.id || element.tag;
}
+type RightPanelTab = "design" | "renders";
+
+const GENERIC_FONT_FAMILIES = new Set([
+ "inherit",
+ "initial",
+ "revert",
+ "revert-layer",
+ "serif",
+ "sans-serif",
+ "monospace",
+ "cursive",
+ "fantasy",
+ "system-ui",
+ "ui-sans-serif",
+ "ui-serif",
+ "ui-monospace",
+ "ui-rounded",
+ "emoji",
+ "math",
+ "fangsong",
+]);
+
+function primaryFontFamilyFromCss(value: string): string {
+ const first = value.split(",")[0] ?? "";
+ return first.trim().replace(/^["']|["']$/g, "");
+}
+
+function injectPreviewGoogleFont(doc: Document, fontFamilyValue: string): void {
+ const family = primaryFontFamilyFromCss(fontFamilyValue);
+ if (!family || GENERIC_FONT_FAMILIES.has(family.toLowerCase())) return;
+
+ const id = `studio-preview-google-font-${family.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`;
+ if (doc.getElementById(id)) return;
+
+ const link = doc.createElement("link");
+ link.id = id;
+ link.rel = "stylesheet";
+ link.href = googleFontStylesheetUrl(family);
+ doc.head.appendChild(link);
+}
+
+function primaryFontFamilyValue(value: string): string {
+ return (
+ value
+ .split(",")[0]
+ ?.trim()
+ .replace(/^["']|["']$/g, "")
+ .trim() ?? ""
+ );
+}
+
+function injectPreviewImportedFont(doc: Document, asset: ImportedFontAsset): void {
+ const id = `studio-imported-font-${asset.family.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`;
+ if (doc.getElementById(id)) return;
+ const style = doc.createElement("style");
+ style.id = id;
+ style.textContent = importedFontFaceCss(asset);
+ doc.head.appendChild(style);
+}
+
+function normalizeProjectAssetPath(value: string): string {
+ const trimmed = value.trim();
+ const maybeUrl = /^[a-z]+:\/\//i.test(trimmed) ? new URL(trimmed).pathname : trimmed;
+ return decodeURIComponent(maybeUrl)
+ .replace(/\\/g, "/")
+ .replace(/^\.?\//, "");
+}
+
+function toRelativeProjectAssetPath(sourceFile: string, assetPath: string): string {
+ const fromParts = normalizeProjectAssetPath(sourceFile).split("/").filter(Boolean);
+ const targetParts = normalizeProjectAssetPath(assetPath).split("/").filter(Boolean);
+
+ fromParts.pop();
+
+ while (fromParts.length > 0 && targetParts.length > 0 && fromParts[0] === targetParts[0]) {
+ fromParts.shift();
+ targetParts.shift();
+ }
+
+ return [...fromParts.map(() => ".."), ...targetParts].join("/") || assetPath;
+}
+
+function isAbsoluteFilePath(value: string): boolean {
+ return /^(?:\/|[A-Za-z]:[\\/]|\\\\)/.test(value);
+}
+
+function toProjectAbsolutePath(projectDir: string | null, sourceFile: string): string | undefined {
+ const trimmedSource = sourceFile.trim();
+ if (!trimmedSource) return undefined;
+
+ const normalizedSource = trimmedSource.replace(/\\/g, "/");
+ if (isAbsoluteFilePath(normalizedSource)) return normalizedSource;
+
+ const normalizedRoot = projectDir?.trim().replace(/\\/g, "/").replace(/\/+$/, "");
+ if (!normalizedRoot) return undefined;
+
+ return `${normalizedRoot}/${normalizedSource.replace(/^\.?\//, "")}`;
+}
+
+function ensureImportedFontFace(
+ html: string,
+ asset: ImportedFontAsset,
+ sourceFile: string,
+): string {
+ const css = importedFontFaceCss(asset, toRelativeProjectAssetPath(sourceFile, asset.path));
+ if (html.includes(css)) return html;
+
+ const styleRe = /<style\b[^>]*data-hf-studio-fonts=(["'])true\1[^>]*>([\s\S]*?)<\/style>/i;
+ const styleMatch = styleRe.exec(html);
+ if (styleMatch) {
+ const nextCss = `${styleMatch[2].trim()}\n${css}`.trim();
+ return html.replace(styleMatch[0], `<style data-hf-studio-fonts="true">\n${nextCss}\n</style>`);
+ }
+
+ const styleTag = `<style data-hf-studio-fonts="true">\n${css}\n</style>`;
+ if (/<\/head>/i.test(html)) {
+ return html.replace(/<\/head>/i, ` ${styleTag}\n </head>`);
+ }
+ return `${styleTag}\n${html}`;
+}
+function normalizeDomEditStyleValue(property: string, value: string): string {
+ const trimmed = value.trim();
+ if (!trimmed) return trimmed;
+
+ if (["border-radius", "font-size"].includes(property) && /^-?\d+(\.\d+)?$/.test(trimmed)) {
+ return `${trimmed}px`;
+ }
+
+ return trimmed;
+}
+
+function isImageBackgroundValue(value: string): boolean {
+ return /^url\(/i.test(value.trim());
+}
+
+function getEventTargetElement(target: EventTarget | null): HTMLElement | null {
+ if (!target || typeof target !== "object") return null;
+ const maybeNode = target as {
+ nodeType?: number;
+ parentElement?: Element | null;
+ };
+ if (maybeNode.nodeType === 1) return target as HTMLElement;
+ if (maybeNode.nodeType === 3 && maybeNode.parentElement) {
+ return maybeNode.parentElement as HTMLElement;
+ }
+ return null;
+}
+
+function shouldIgnoreHistoryShortcut(target: EventTarget | null): boolean {
+ const el = getEventTargetElement(target);
+ if (!el) return false;
+ return Boolean(
+ el.closest("input, textarea, select, [contenteditable='true'], [role='textbox'], .cm-editor"),
+ );
+}
+
+function getHistoryShortcutLabel(action: "undo" | "redo"): string {
+ const isMac =
+ typeof navigator !== "undefined" && /Mac|iPhone|iPad|iPod/i.test(navigator.platform);
+ const modifier = isMac ? "Cmd" : "Ctrl";
+ return action === "undo" ? `${modifier}+Z` : `${modifier}+Shift+Z`;
+}
+
+function findMatchingTimelineElementId(
+ selection: Pick<
+ DomEditSelection,
+ "id" | "selector" | "selectorIndex" | "sourceFile" | "compositionSrc" | "isCompositionHost"
+ >,
+ elements: TimelineElement[],
+): string | null {
+ const selectionSourceFile = selection.sourceFile || "index.html";
+ for (const element of elements) {
+ const elementSourceFile = element.sourceFile || "index.html";
+ if (
+ selection.id &&
+ element.domId === selection.id &&
+ elementSourceFile === selectionSourceFile
+ ) {
+ return element.key ?? element.id;
+ }
+ if (
+ selection.isCompositionHost &&
+ selection.compositionSrc &&
+ element.compositionSrc === selection.compositionSrc
+ ) {
+ return element.key ?? element.id;
+ }
+ if (
+ selection.selector &&
+ element.selector === selection.selector &&
+ (element.selectorIndex ?? 0) === (selection.selectorIndex ?? 0) &&
+ (element.sourceFile ?? "index.html") === selection.sourceFile
+ ) {
+ return element.key ?? element.id;
+ }
+ }
+
+ return null;
+}
+
+function isManualGeometryStyleProperty(property: string): boolean {
+ return property === "left" || property === "top" || property === "width" || property === "height";
+}
+
+function getPreviewTargetFromPointer(
+ iframe: HTMLIFrameElement,
+ clientX: number,
+ clientY: number,
+): HTMLElement | null {
+ let doc: Document | null = null;
+ let win: Window | null = null;
+ try {
+ doc = iframe.contentDocument;
+ win = iframe.contentWindow;
+ } catch {
+ return null;
+ }
+ if (!doc || !win) return null;
+
+ const iframeRect = iframe.getBoundingClientRect();
+ const root =
+ doc.querySelector<HTMLElement>("[data-composition-id]") ?? doc.documentElement ?? null;
+ const rootRect = root?.getBoundingClientRect();
+ const rootWidth = rootRect?.width || win.innerWidth;
+ const rootHeight = rootRect?.height || win.innerHeight;
+ if (!rootWidth || !rootHeight) return null;
+
+ const scaleX = iframeRect.width / rootWidth;
+ const scaleY = iframeRect.height / rootHeight;
+ const localX = (clientX - iframeRect.left) / scaleX;
+ const localY = (clientY - iframeRect.top) / scaleY;
+
+ return getEventTargetElement(doc.elementFromPoint(localX, localY));
+}
+
+function domEditSelectionsTargetSame(
+ a: DomEditSelection | null,
+ b: DomEditSelection | null,
+): boolean {
+ if (a === b) return true;
+ if (!a || !b) return false;
+ return getDomEditTargetKey(a) === getDomEditTargetKey(b);
+}
+
+function domEditSelectionInGroup(
+ group: DomEditSelection[],
+ selection: DomEditSelection | null,
+): boolean {
+ if (!selection) return false;
+ return group.some((entry) => domEditSelectionsTargetSame(entry, selection));
+}
+
+function toggleDomEditGroupSelection(
+ group: DomEditSelection[],
+ selection: DomEditSelection,
+): DomEditSelection[] {
+ if (domEditSelectionInGroup(group, selection)) {
+ return group.filter((entry) => !domEditSelectionsTargetSame(entry, selection));
+ }
+ return [...group, selection];
+}
+
+function replaceDomEditGroupSelection(
+ group: DomEditSelection[],
+ selection: DomEditSelection,
+): DomEditSelection[] {
+ let replaced = false;
+ const nextGroup = group.map((entry) => {
+ if (!domEditSelectionsTargetSame(entry, selection)) return entry;
+ replaced = true;
+ return selection;
+ });
+ return replaced ? nextGroup : [...group, selection];
+}
+
+function seedDomEditGroupWithSelection(
+ group: DomEditSelection[],
+ selection: DomEditSelection | null,
+): DomEditSelection[] {
+ if (!selection || domEditSelectionInGroup(group, selection)) return group;
+ return [selection, ...group];
+}
+
+function objectLike(value: unknown): object | null {
+ return value && (typeof value === "object" || typeof value === "function") ? value : null;
+}
+
+function callPlaybackMethod(target: object | null, key: string): void {
+ const method = target ? Reflect.get(target, key) : null;
+ if (typeof method !== "function") return;
+ try {
+ method.call(target);
+ } catch {
+ // Best-effort playback freeze; drag should still work if playback control is unavailable.
+ }
+}
+
+function readPlaybackTime(target: object | null, key: string): number | null {
+ const method = target ? Reflect.get(target, key) : null;
+ if (typeof method !== "function") return null;
+ try {
+ const value = method.call(target);
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
+ } catch {
+ return null;
+ }
+}
+
+function pauseStudioPreviewPlayback(iframe: HTMLIFrameElement | null): number | null {
+ const win = iframe?.contentWindow;
+ if (!win) return null;
+
+ try {
+ let pausedTime: number | null = null;
+ const player = objectLike(Reflect.get(win, "__player"));
+ pausedTime = readPlaybackTime(player, "getTime") ?? pausedTime;
+ callPlaybackMethod(player, "pause");
+
+ const timeline = objectLike(Reflect.get(win, "__timeline"));
+ pausedTime = pausedTime ?? readPlaybackTime(timeline, "time");
+ callPlaybackMethod(timeline, "pause");
+
+ const timelines = objectLike(Reflect.get(win, "__timelines"));
+ if (timelines) {
+ for (const value of Object.values(timelines)) {
+ const timelineRecord = objectLike(value);
+ pausedTime = pausedTime ?? readPlaybackTime(timelineRecord, "time");
+ callPlaybackMethod(timelineRecord, "pause");
+ }
+ }
+
+ return pausedTime;
+ } catch {
+ return null;
+ }
+}
+
+// ── Ask Agent Modal ──
+
+function AskAgentModal({
+ selectionLabel,
+ onSubmit,
+ onClose,
+}: {
+ selectionLabel: string;
+ onSubmit: (instruction: string) => void;
+ onClose: () => void;
+}) {
+ const [value, setValue] = useState("");
+ const inputRef = useRef<HTMLTextAreaElement>(null);
+
+ useMountEffect(() => {
+ requestAnimationFrame(() => inputRef.current?.focus());
+ });
+
+ const handleSubmit = () => {
+ if (!value.trim()) return;
+ onSubmit(value.trim());
+ };
+
+ return (
+ <div
+ className="fixed inset-0 z-[100] flex items-center justify-center bg-black/60 backdrop-blur-sm"
+ onClick={onClose}
+ >
+ <div
+ className="w-[480px] rounded-2xl border border-neutral-800 bg-neutral-950 shadow-2xl"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <div className="flex items-center justify-between px-5 py-4 border-b border-neutral-800/60">
+ <div>
+ <h3 className="text-sm font-medium text-neutral-200">Ask agent</h3>
+ <p className="text-xs text-neutral-500 mt-0.5">
+ {selectionLabel.length > 50 ? `${selectionLabel.slice(0, 49)}…` : selectionLabel}
+ </p>
+ </div>
+ <button
+ className="p-1 rounded-md text-neutral-500 hover:text-neutral-300 hover:bg-neutral-800/50"
+ onClick={onClose}
+ >
+ <svg
+ width="14"
+ height="14"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ >
+ <line x1="18" y1="6" x2="6" y2="18" />
+ <line x1="6" y1="6" x2="18" y2="18" />
+ </svg>
+ </button>
+ </div>
+ <div className="px-5 py-4">
+ <textarea
+ ref={inputRef}
+ className="w-full h-24 px-3 py-2 rounded-lg border border-neutral-800 bg-neutral-900/60 text-sm text-neutral-200 placeholder-neutral-600 resize-none focus:outline-none focus:border-studio-accent/60 focus:ring-1 focus:ring-studio-accent/30"
+ placeholder="Describe what you want to change…"
+ value={value}
+ onChange={(e) => setValue(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) handleSubmit();
+ if (e.key === "Escape") onClose();
+ }}
+ />
+ </div>
+ <div className="flex items-center justify-between px-5 py-3 border-t border-neutral-800/60">
+ <span className="text-[11px] text-neutral-600">
+ {navigator.platform.includes("Mac") ? "⌘" : "Ctrl"}+Enter to copy
+ </span>
+ <button
+ className="px-4 py-1.5 rounded-lg bg-studio-accent/90 text-xs font-medium text-neutral-950 hover:bg-studio-accent disabled:opacity-40 disabled:cursor-not-allowed"
+ disabled={!value.trim()}
+ onClick={handleSubmit}
+ >
+ Copy prompt
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+}
+
const DEFAULT_TIMELINE_ASSET_DURATION: Record<TimelineAssetKind, number> = {
image: 3,
video: 5,
@@ -144,6 +620,7 @@ export function StudioApp() {
});
const [editingFile, setEditingFile] = useState<EditingFile | null>(null);
+ const [projectDir, setProjectDir] = useState<string | null>(null);
const [activeCompPath, setActiveCompPath] = useState<string | null>(null);
const [fileTree, setFileTree] = useState<string[]>([]);
const [compIdToSrc, setCompIdToSrc] = useState<Map<string, string>>(new Map());
@@ -157,6 +634,14 @@ export function StudioApp() {
const [rightWidth, setRightWidth] = useState(400);
const [leftCollapsed, setLeftCollapsed] = useState(false);
const [rightCollapsed, setRightCollapsed] = useState(true);
+ const [rightPanelTab, setRightPanelTab] = useState<RightPanelTab>("renders");
+ const [domEditSelection, setDomEditSelection] = useState<DomEditSelection | null>(null);
+ const [domEditGroupSelections, setDomEditGroupSelections] = useState<DomEditSelection[]>([]);
+ const [domEditHoverSelection, setDomEditHoverSelection] = useState<DomEditSelection | null>(null);
+ const [agentPromptTagSnippet, setAgentPromptTagSnippet] = useState<string | undefined>();
+ const [copiedAgentPrompt, setCopiedAgentPrompt] = useState(false);
+ const [agentModalOpen, setAgentModalOpen] = useState(false);
+ const [previewIframe, setPreviewIframe] = useState<HTMLIFrameElement | null>(null);
// Auto-enter caption edit mode when the iframe contains .caption-group elements.
// This is a subscription to external events (postMessage from runtime) — useEffect
// is appropriate here. The runtime fires "state"/"timeline" messages after all
@@ -280,10 +765,16 @@ export function StudioApp() {
const [appToast, setAppToast] = useState<AppToast | null>(null);
const [timelineVisible, setTimelineVisible] = useState(true);
const [captureFrameTime, setCaptureFrameTime] = useState(0);
+ const [timelineEditorHintDismissed, setTimelineEditorHintState] = useState(
+ getTimelineEditorHintDismissed,
+ );
const dragCounterRef = useRef(0);
const toastTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const lastBlockedTimelineToastAtRef = useRef(0);
+ const lastBlockedDomMoveToastAtRef = useRef(0);
+ const importedFontAssetsRef = useRef<ImportedFontAsset[]>([]);
const previewHotkeyWindowRef = useRef<Window | null>(null);
+ const previewHistoryHotkeyCleanupRef = useRef<(() => void) | null>(null);
const panelDragRef = useRef<{
side: "left" | "right";
startX: number;
@@ -294,11 +785,14 @@ export function StudioApp() {
const activePreviewUrl = activeCompPath
? `/api/projects/${projectId}/preview/comp/${activeCompPath}`
: null;
+ const isMasterView = !activeCompPath || activeCompPath === "index.html";
const zoomMode = usePlayerStore((s) => s.zoomMode);
const manualZoomPercent = usePlayerStore((s) => s.manualZoomPercent);
const setZoomMode = usePlayerStore((s) => s.setZoomMode);
const setManualZoomPercent = usePlayerStore((s) => s.setManualZoomPercent);
+ const currentTime = usePlayerStore((s) => s.currentTime);
const timelineElements = usePlayerStore((s) => s.elements);
+ const setSelectedTimelineElementId = usePlayerStore((s) => s.setSelectedElementId);
const timelineDuration = usePlayerStore((s) => s.duration);
const effectiveTimelineDuration = useMemo(() => {
const maxEnd =
@@ -337,6 +831,10 @@ export function StudioApp() {
useMountEffect(() => () => {
if (toastTimerRef.current) clearTimeout(toastTimerRef.current);
});
+ const dismissTimelineEditorHint = useCallback(() => {
+ setTimelineEditorHintState(true);
+ setTimelineEditorHintDismissed(true);
+ }, []);
const handleTimelineToggleHotkey = useCallback(
(event: KeyboardEvent) => {
if (!shouldHandleTimelineToggleHotkey(event)) return;
@@ -400,7 +898,6 @@ export function StudioApp() {
label={getTimelineElementLabel(el)}
labelColor={style.label}
accentColor={style.clip}
- selector={el.selector}
seekTime={0}
duration={el.duration}
/>
@@ -417,6 +914,7 @@ export function StudioApp() {
labelColor={style.label}
accentColor={style.clip}
selector={el.selector}
+ selectorIndex={el.selectorIndex}
seekTime={el.start}
duration={el.duration}
/>
@@ -478,6 +976,7 @@ export function StudioApp() {
labelColor={style.label}
accentColor={style.clip}
selector={el.selector}
+ selectorIndex={el.selectorIndex}
seekTime={el.start}
duration={el.duration}
/>
@@ -490,6 +989,31 @@ export function StudioApp() {
);
const timelineToolbar = (
<div className="border-b border-neutral-800/40 bg-neutral-950/96">
+ {timelineVisible && timelineElements.length > 0 && !timelineEditorHintDismissed && (
+ <div className="px-3 pt-3">
+ <div className="flex items-start justify-between gap-3 rounded-xl border border-studio-accent/20 bg-studio-accent/[0.07] px-3 py-3">
+ <div className="min-w-0">
+ <div className="text-[11px] font-semibold text-neutral-100">Timeline editor</div>
+ <p className="mt-1 text-[11px] leading-5 text-neutral-300">
+ Drag clips to move timing, and drag clip edges to resize them when handles are
+ available. Hide the panel anytime and bring it back with{" "}
+ <span className="font-mono text-[10px] text-studio-accent">
+ {TIMELINE_TOGGLE_SHORTCUT_LABEL}
+ </span>
+ .
+ </p>
+ </div>
+ <button
+ type="button"
+ onClick={dismissTimelineEditorHint}
+ className="flex-shrink-0 rounded-md border border-neutral-700 px-2 py-1 text-[10px] font-medium text-neutral-300 transition-colors hover:border-neutral-500 hover:text-neutral-100"
+ >
+ Dismiss
+ </button>
+ </div>
+ </div>
+ )}
+
<div className="flex items-center justify-between px-3 py-2">
<div className="text-[10px] font-medium uppercase tracking-[0.16em] text-neutral-500">
Timeline
@@ -567,11 +1091,58 @@ export function StudioApp() {
const projectIdRef = useRef(projectId);
const previewIframeRef = useRef<HTMLIFrameElement | null>(null);
const consoleErrorsRef = useRef<LintFinding[]>([]);
+ const copiedAgentTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const domEditSelectionRef = useRef<DomEditSelection | null>(domEditSelection);
+ const domEditGroupSelectionsRef = useRef<DomEditSelection[]>(domEditGroupSelections);
+ const domEditHoverSelectionRef = useRef<DomEditSelection | null>(domEditHoverSelection);
+ const domEditSaveTimestampRef = useRef(0);
+ const domTextCommitVersionRef = useRef(0);
+ const domEditSaveQueueRef = useRef(Promise.resolve());
+ const studioManualEditManifestRef = useRef<StudioManualEditManifest>(
+ emptyStudioManualEditManifest(),
+ );
+ const studioManualEditRevisionRef = useRef(0);
+ const applyStudioManualEditsToPreviewRef = useRef<
+ (
+ iframe?: HTMLIFrameElement | null,
+ options?: { forceFromDisk?: boolean; readFromDiskFirst?: boolean },
+ ) => Promise<void>
+ >(async () => {});
+ const studioManualEditProjectRef = useRef<string | null>(projectId);
+ const activeCompPathRef = useRef(activeCompPath);
+ activeCompPathRef.current = activeCompPath;
+
+ const queueDomEditSave = useCallback((save: () => Promise<void>) => {
+ const queuedSave = domEditSaveQueueRef.current.catch(() => undefined).then(save);
+ domEditSaveQueueRef.current = queuedSave.then(
+ () => undefined,
+ () => undefined,
+ );
+ return queuedSave;
+ }, []);
+
+ const waitForPendingDomEditSaves = useCallback(async () => {
+ await domEditSaveQueueRef.current.catch(() => undefined);
+ }, []);
// Listen for external file changes (user editing HTML outside the editor).
// In dev: use Vite HMR. In embedded/production: use SSE from /api/events.
+ // Suppress file-change events that echo back from a recent DOM edit save —
+ // those changes are already applied to the iframe DOM and a full reload
+ // would flash the preview.
useMountEffect(() => {
- const handler = () => {
+ const handler = (payload?: unknown) => {
+ const changedPath = readStudioFileChangePath(payload);
+ const recentDomEditSave = Date.now() - domEditSaveTimestampRef.current < 1200;
+ if (isStudioManualEditManifestPath(changedPath)) {
+ if (!recentDomEditSave) {
+ void applyStudioManualEditsToPreviewRef.current(previewIframeRef.current, {
+ forceFromDisk: true,
+ });
+ }
+ return;
+ }
+ if (recentDomEditSave) return;
if (refreshTimerRef.current) clearTimeout(refreshTimerRef.current);
refreshTimerRef.current = setTimeout(() => setRefreshKey((k) => k + 1), 400);
};
@@ -585,6 +1156,18 @@ export function StudioApp() {
return () => es.close();
});
projectIdRef.current = projectId;
+ domEditSelectionRef.current = domEditSelection;
+ domEditGroupSelectionsRef.current = domEditGroupSelections;
+ domEditHoverSelectionRef.current = domEditHoverSelection;
+
+ // eslint-disable-next-line no-restricted-syntax
+ useEffect(() => {
+ const previousProjectId = studioManualEditProjectRef.current;
+ studioManualEditProjectRef.current = projectId;
+ if (!previousProjectId || previousProjectId === projectId) return;
+ studioManualEditManifestRef.current = emptyStudioManualEditManifest();
+ studioManualEditRevisionRef.current += 1;
+ }, [projectId]);
// Load file tree when projectId changes.
// Note: This is one of the few places where useEffect with deps is acceptable —
@@ -596,10 +1179,13 @@ export function StudioApp() {
let cancelled = false;
fetch(`/api/projects/${projectId}`)
.then((r) => r.json())
- .then((data: { files?: string[] }) => {
+ .then((data: { files?: string[]; dir?: string }) => {
if (!cancelled && data.files) setFileTree(data.files);
+ if (!cancelled) setProjectDir(typeof data.dir === "string" ? data.dir : null);
})
- .catch(() => {});
+ .catch(() => {
+ if (!cancelled) setProjectDir(null);
+ });
return () => {
cancelled = true;
};
@@ -627,29 +1213,72 @@ export function StudioApp() {
const editingPathRef = useRef(editingFile?.path);
editingPathRef.current = editingFile?.path;
+ const editHistory = usePersistentEditHistory({ projectId });
- const handleContentChange = useCallback((content: string) => {
+ const readProjectFile = useCallback(async (path: string): Promise<string> => {
const pid = projectIdRef.current;
- if (!pid) return;
- const path = editingPathRef.current;
- if (!path) return;
-
- // Debounce the server write (600ms)
- if (saveTimerRef.current) clearTimeout(saveTimerRef.current);
- saveTimerRef.current = setTimeout(() => {
- fetch(`/api/projects/${pid}/files/${encodeURIComponent(path)}`, {
- method: "PUT",
- headers: { "Content-Type": "text/plain" },
- body: content,
- })
- .then(() => {
- if (refreshTimerRef.current) clearTimeout(refreshTimerRef.current);
- refreshTimerRef.current = setTimeout(() => setRefreshKey((k) => k + 1), 600);
- })
- .catch(() => {});
- }, 600);
+ if (!pid) throw new Error("No active project");
+ const response = await fetch(`/api/projects/${pid}/files/${encodeURIComponent(path)}`);
+ if (!response.ok) throw new Error(`Failed to read ${path}`);
+ const data = (await response.json()) as { content?: string };
+ if (typeof data.content !== "string") throw new Error(`Missing file contents for ${path}`);
+ return data.content;
+ }, []);
+
+ const writeProjectFile = useCallback(async (path: string, content: string): Promise<void> => {
+ const pid = projectIdRef.current;
+ if (!pid) throw new Error("No active project");
+ const response = await fetch(`/api/projects/${pid}/files/${encodeURIComponent(path)}`, {
+ method: "PUT",
+ headers: { "Content-Type": "text/plain" },
+ body: content,
+ });
+ if (!response.ok) throw new Error(`Failed to save ${path}`);
+ if (editingPathRef.current === path) {
+ setEditingFile({ path, content });
+ }
+ }, []);
+
+ const readOptionalProjectFile = useCallback(async (path: string): Promise<string> => {
+ const pid = projectIdRef.current;
+ if (!pid) throw new Error("No active project");
+ const response = await fetch(`/api/projects/${pid}/files/${encodeURIComponent(path)}`);
+ if (response.status === 404) return "";
+ if (!response.ok) throw new Error(`Failed to read ${path}`);
+ const data = (await response.json()) as { content?: string };
+ return typeof data.content === "string" ? data.content : "";
}, []);
+ const handleContentChange = useCallback(
+ (content: string) => {
+ const pid = projectIdRef.current;
+ if (!pid) return;
+ const path = editingPathRef.current;
+ if (!path) return;
+
+ // Debounce the server write (600ms)
+ if (saveTimerRef.current) clearTimeout(saveTimerRef.current);
+ saveTimerRef.current = setTimeout(() => {
+ saveProjectFilesWithHistory({
+ projectId: pid,
+ label: "Edit source",
+ kind: "source",
+ coalesceKey: `source:${path}`,
+ files: { [path]: content },
+ readFile: readProjectFile,
+ writeFile: writeProjectFile,
+ recordEdit: editHistory.recordEdit,
+ })
+ .then(() => {
+ if (refreshTimerRef.current) clearTimeout(refreshTimerRef.current);
+ refreshTimerRef.current = setTimeout(() => setRefreshKey((k) => k + 1), 600);
+ })
+ .catch(() => {});
+ }, 600);
+ },
+ [editHistory.recordEdit, readProjectFile, writeProjectFile],
+ );
+
const handleTimelineElementMove = useCallback(
async (element: TimelineElement, updates: Pick<TimelineElement, "start" | "track">) => {
const pid = projectIdRef.current;
@@ -728,25 +1357,19 @@ export function StudioApp() {
throw new Error(`Unable to patch timeline element ${element.id} in ${targetPath}`);
}
- const saveResponse = await fetch(
- `/api/projects/${pid}/files/${encodeURIComponent(targetPath)}`,
- {
- method: "PUT",
- headers: { "Content-Type": "text/plain" },
- body: patchedContent,
- },
- );
- if (!saveResponse.ok) {
- throw new Error(`Failed to save ${targetPath}`);
- }
-
- if (editingPathRef.current === targetPath) {
- setEditingFile({ path: targetPath, content: patchedContent });
- }
+ await saveProjectFilesWithHistory({
+ projectId: pid,
+ label: "Move timeline clip",
+ kind: "timeline",
+ files: { [targetPath]: patchedContent },
+ readFile: async () => originalContent,
+ writeFile: writeProjectFile,
+ recordEdit: editHistory.recordEdit,
+ });
setRefreshKey((k) => k + 1);
},
- [activeCompPath, timelineElements],
+ [activeCompPath, editHistory.recordEdit, timelineElements, writeProjectFile],
);
const handleTimelineElementResize = useCallback(
@@ -818,25 +1441,19 @@ export function StudioApp() {
throw new Error(`Unable to patch timeline element ${element.id} in ${targetPath}`);
}
- const saveResponse = await fetch(
- `/api/projects/${pid}/files/${encodeURIComponent(targetPath)}`,
- {
- method: "PUT",
- headers: { "Content-Type": "text/plain" },
- body: patchedContent,
- },
- );
- if (!saveResponse.ok) {
- throw new Error(`Failed to save ${targetPath}`);
- }
-
- if (editingPathRef.current === targetPath) {
- setEditingFile({ path: targetPath, content: patchedContent });
- }
+ await saveProjectFilesWithHistory({
+ projectId: pid,
+ label: "Resize timeline clip",
+ kind: "timeline",
+ files: { [targetPath]: patchedContent },
+ readFile: async () => originalContent,
+ writeFile: writeProjectFile,
+ recordEdit: editHistory.recordEdit,
+ });
setRefreshKey((k) => k + 1);
},
- [activeCompPath],
+ [activeCompPath, editHistory.recordEdit, writeProjectFile],
);
const showToast = useCallback((message: string, tone: AppToast["tone"] = "error") => {
@@ -852,6 +1469,7 @@ export function StudioApp() {
const currentTime = usePlayerStore.getState().currentTime;
setCaptureFrameTime(currentTime);
+ await waitForPendingDomEditSaves();
const href = buildFrameCaptureUrl({
projectId,
compositionPath: activeCompPath,
@@ -878,7 +1496,7 @@ export function StudioApp() {
showToast(message);
}
},
- [activeCompPath, projectId, showToast],
+ [activeCompPath, projectId, showToast, waitForPendingDomEditSaves],
);
const handleTimelineElementDelete = useCallback(
@@ -961,21 +1579,15 @@ export function StudioApp() {
});
}
- const saveResponse = await fetch(
- `/api/projects/${pid}/files/${encodeURIComponent(targetPath)}`,
- {
- method: "PUT",
- headers: { "Content-Type": "text/plain" },
- body: patchedContent,
- },
- );
- if (!saveResponse.ok) {
- throw new Error(`Failed to save ${targetPath}`);
- }
-
- if (editingPathRef.current === targetPath) {
- setEditingFile({ path: targetPath, content: patchedContent });
- }
+ await saveProjectFilesWithHistory({
+ projectId: pid,
+ label: "Delete timeline clip",
+ kind: "timeline",
+ files: { [targetPath]: patchedContent },
+ readFile: async () => originalContent,
+ writeFile: writeProjectFile,
+ recordEdit: editHistory.recordEdit,
+ });
usePlayerStore
.getState()
@@ -992,7 +1604,7 @@ export function StudioApp() {
showToast(message);
}
},
- [activeCompPath, showToast, timelineElements],
+ [activeCompPath, editHistory.recordEdit, showToast, timelineElements, writeProjectFile],
);
const handleBlockedTimelineEdit = useCallback(
@@ -1005,64 +1617,1195 @@ export function StudioApp() {
[showToast],
);
- const refreshFileTree = useCallback(async () => {
- const pid = projectIdRef.current;
- if (!pid) return;
- const res = await fetch(`/api/projects/${pid}`);
- const data = await res.json();
- if (data.files) setFileTree(data.files);
- }, []);
-
- const uploadProjectFiles = useCallback(
- async (files: Iterable<File>, dir?: string): Promise<string[]> => {
- const pid = projectIdRef.current;
- const fileList = Array.from(files);
- if (!pid || fileList.length === 0) return [];
+ const handleBlockedDomMove = useCallback(
+ (selection: DomEditSelection) => {
+ const now = Date.now();
+ if (now - lastBlockedDomMoveToastAtRef.current < 1500) return;
+ lastBlockedDomMoveToastAtRef.current = now;
+ showToast(
+ selection.capabilities.reasonIfDisabled ??
+ "This element can’t be adjusted directly from the preview.",
+ "info",
+ );
+ },
+ [showToast],
+ );
- const formData = new FormData();
- for (const file of fileList) {
- formData.append("file", file);
+ const applyDomSelection = useCallback(
+ (
+ selection: DomEditSelection | null,
+ options?: { revealPanel?: boolean; additive?: boolean; preserveGroup?: boolean },
+ ) => {
+ setAgentPromptTagSnippet(undefined);
+ setCopiedAgentPrompt(false);
+ if (!selection) {
+ domEditSelectionRef.current = null;
+ domEditGroupSelectionsRef.current = [];
+ setDomEditSelection(null);
+ setDomEditGroupSelections([]);
+ setSelectedTimelineElementId(null);
+ return;
}
- const qs = dir ? `?dir=${encodeURIComponent(dir)}` : "";
- try {
- const res = await fetch(`/api/projects/${pid}/upload${qs}`, {
- method: "POST",
- body: formData,
- });
- if (res.ok) {
- const data = await res.json();
- if (data.skipped?.length) {
- showToast(`Skipped (too large): ${data.skipped.join(", ")}`);
- }
- if (data.invalid?.length) {
- const names = data.invalid.map((entry: { name: string }) => entry.name).join(", ");
- showToast(`Unsupported media skipped: ${names}`);
- }
- await refreshFileTree();
- setRefreshKey((k) => k + 1);
- return Array.isArray(data.files) ? data.files : [];
- } else if (res.status === 413) {
- showToast("Upload rejected: payload too large");
- } else {
- showToast(`Upload failed (${res.status})`);
+ const isAdditiveSelection = Boolean(options?.additive);
+ const currentSelection = domEditSelectionRef.current;
+ const previousGroup = domEditGroupSelectionsRef.current;
+ const currentGroup = isAdditiveSelection
+ ? seedDomEditGroupWithSelection(previousGroup, currentSelection)
+ : previousGroup;
+ const wasInGroup = domEditSelectionInGroup(currentGroup, selection);
+ const nextGroup = options?.preserveGroup
+ ? replaceDomEditGroupSelection(currentGroup, selection)
+ : isAdditiveSelection
+ ? toggleDomEditGroupSelection(currentGroup, selection)
+ : [selection];
+ const nextSelection = options?.preserveGroup
+ ? selection
+ : isAdditiveSelection && wasInGroup
+ ? domEditSelectionsTargetSame(currentSelection, selection)
+ ? (nextGroup[0] ?? null)
+ : domEditSelectionInGroup(nextGroup, currentSelection)
+ ? currentSelection
+ : (nextGroup[0] ?? null)
+ : selection;
+
+ domEditSelectionRef.current = nextSelection;
+ domEditGroupSelectionsRef.current = nextGroup;
+ setDomEditSelection(nextSelection);
+ setDomEditGroupSelections(nextGroup);
+
+ if (nextSelection) {
+ if (options?.revealPanel !== false) {
+ setRightCollapsed(false);
+ setRightPanelTab("design");
}
- } catch {
- showToast("Upload failed: network error");
+ const nextSelectedTimelineId = findMatchingTimelineElementId(
+ nextSelection,
+ timelineElements,
+ );
+ setSelectedTimelineElementId(nextSelectedTimelineId);
+ return;
}
- return [];
+
+ setSelectedTimelineElementId(null);
},
- [refreshFileTree, showToast],
+ [setSelectedTimelineElementId, timelineElements],
);
- const handleTimelineAssetDrop = useCallback(
- async (
- assetPath: string,
- placement: Pick<TimelineElement, "start" | "track">,
- durationOverride?: number,
- ) => {
- const pid = projectIdRef.current;
- if (!pid) throw new Error("No active project");
+ const clearDomSelection = useCallback(() => {
+ applyDomSelection(null, { revealPanel: false });
+ }, [applyDomSelection]);
+
+ const readHistoryProjectFile = useCallback(
+ async (path: string): Promise<string> => {
+ return path === STUDIO_MANUAL_EDITS_PATH
+ ? readOptionalProjectFile(path)
+ : readProjectFile(path);
+ },
+ [readOptionalProjectFile, readProjectFile],
+ );
+
+ const writeHistoryProjectFile = useCallback(
+ async (path: string, content: string): Promise<void> => {
+ await writeProjectFile(path, content);
+ if (path === STUDIO_MANUAL_EDITS_PATH) {
+ domEditSaveTimestampRef.current = Date.now();
+ }
+ },
+ [writeProjectFile],
+ );
+
+ const applyCurrentStudioManualEditsToPreview = useCallback(
+ (iframe: HTMLIFrameElement | null = previewIframeRef.current) => {
+ if (!iframe) return;
+ let doc: Document | null = null;
+ try {
+ doc = iframe.contentDocument;
+ } catch {
+ return;
+ }
+ if (!doc) return;
+ const previewDoc = doc;
+
+ const applyManifest = () => {
+ applyStudioManualEditManifest(
+ previewDoc,
+ studioManualEditManifestRef.current,
+ activeCompPathRef.current,
+ );
+ };
+ const applyAndInstallSeekHooks = () => {
+ applyManifest();
+ if (iframe.contentWindow) {
+ installStudioManualEditSeekReapply(iframe.contentWindow, applyManifest);
+ }
+ };
+
+ const win = iframe.contentWindow;
+ applyAndInstallSeekHooks();
+ win?.requestAnimationFrame?.(applyAndInstallSeekHooks);
+ win?.setTimeout?.(applyAndInstallSeekHooks, 80);
+ win?.setTimeout?.(applyAndInstallSeekHooks, 250);
+ win?.setTimeout?.(applyAndInstallSeekHooks, 500);
+ win?.setTimeout?.(applyAndInstallSeekHooks, 1000);
+ win?.setTimeout?.(applyAndInstallSeekHooks, 2000);
+ },
+ [],
+ );
+
+ const applyStudioManualEditsToPreview = useCallback(
+ async (
+ iframe: HTMLIFrameElement | null = previewIframeRef.current,
+ options?: { forceFromDisk?: boolean; readFromDiskFirst?: boolean },
+ ) => {
+ const readRevision = studioManualEditRevisionRef.current;
+ const readFromDiskFirst = Boolean(options?.forceFromDisk || options?.readFromDiskFirst);
+ if (!readFromDiskFirst) {
+ applyCurrentStudioManualEditsToPreview(iframe);
+ }
+ let content: string;
+ try {
+ content = await readOptionalProjectFile(STUDIO_MANUAL_EDITS_PATH);
+ } catch (error) {
+ const message =
+ error instanceof Error ? error.message : "Failed to read manual edit manifest";
+ showToast(message);
+ if (readFromDiskFirst) {
+ applyCurrentStudioManualEditsToPreview(iframe);
+ }
+ return;
+ }
+ if (options?.forceFromDisk || readRevision === studioManualEditRevisionRef.current) {
+ studioManualEditManifestRef.current = parseStudioManualEditManifest(content);
+ if (options?.forceFromDisk) studioManualEditRevisionRef.current += 1;
+ applyCurrentStudioManualEditsToPreview(iframe);
+ return;
+ }
+ if (readFromDiskFirst) {
+ applyCurrentStudioManualEditsToPreview(iframe);
+ }
+ },
+ [applyCurrentStudioManualEditsToPreview, readOptionalProjectFile, showToast],
+ );
+ applyStudioManualEditsToPreviewRef.current = applyStudioManualEditsToPreview;
+
+ const applyStudioManualEditsToPreviewAfterRefresh = useCallback(
+ (iframe: HTMLIFrameElement | null = previewIframeRef.current) =>
+ applyStudioManualEditsToPreview(iframe, { readFromDiskFirst: true }),
+ [applyStudioManualEditsToPreview],
+ );
+
+ const commitStudioManualEditManifestOptimistically = useCallback(
+ (
+ updateManifest: (manifest: StudioManualEditManifest) => StudioManualEditManifest,
+ options: { label: string; coalesceKey: string },
+ ) => {
+ const previousManifest = studioManualEditManifestRef.current;
+ const nextManifest = updateManifest(previousManifest);
+ const previousContent = serializeStudioManualEditManifest(previousManifest);
+ const nextContent = serializeStudioManualEditManifest(nextManifest);
+ if (nextContent === previousContent) {
+ return;
+ }
+
+ const revision = studioManualEditRevisionRef.current + 1;
+ studioManualEditRevisionRef.current = revision;
+ studioManualEditManifestRef.current = nextManifest;
+ applyCurrentStudioManualEditsToPreview(previewIframeRef.current);
+
+ const save = async () => {
+ const originalContent = await readOptionalProjectFile(STUDIO_MANUAL_EDITS_PATH);
+ const diskManifest = parseStudioManualEditManifest(originalContent);
+ const nextDiskManifest = updateManifest(diskManifest);
+ const nextDiskContent = serializeStudioManualEditManifest(nextDiskManifest);
+ if (nextDiskContent === originalContent) {
+ return;
+ }
+
+ const pid = projectIdRef.current;
+ if (!pid) throw new Error("No active project");
+ domEditSaveTimestampRef.current = Date.now();
+ await saveProjectFilesWithHistory({
+ projectId: pid,
+ label: options.label,
+ kind: "manual",
+ coalesceKey: options.coalesceKey,
+ files: { [STUDIO_MANUAL_EDITS_PATH]: nextDiskContent },
+ readFile: async () => originalContent,
+ writeFile: writeProjectFile,
+ recordEdit: editHistory.recordEdit,
+ });
+ domEditSaveTimestampRef.current = Date.now();
+
+ if (studioManualEditRevisionRef.current === revision) {
+ studioManualEditManifestRef.current = nextDiskManifest;
+ applyCurrentStudioManualEditsToPreview(previewIframeRef.current);
+ }
+ };
+
+ void queueDomEditSave(save).catch((error) => {
+ if (studioManualEditRevisionRef.current === revision) {
+ studioManualEditRevisionRef.current += 1;
+ studioManualEditManifestRef.current = previousManifest;
+ applyCurrentStudioManualEditsToPreview(previewIframeRef.current);
+ }
+ const message = error instanceof Error ? error.message : "Failed to save manual edit";
+ showToast(message);
+ });
+ },
+ [
+ applyCurrentStudioManualEditsToPreview,
+ editHistory.recordEdit,
+ queueDomEditSave,
+ readOptionalProjectFile,
+ showToast,
+ writeProjectFile,
+ ],
+ );
+
+ const syncHistoryPreviewAfterApply = useCallback(
+ async (paths: string[] | undefined) => {
+ const changedPaths = paths ?? [];
+ const manualManifestOnly =
+ changedPaths.length > 0 && changedPaths.every((path) => path === STUDIO_MANUAL_EDITS_PATH);
+
+ if (manualManifestOnly) {
+ await applyStudioManualEditsToPreview(previewIframeRef.current, { forceFromDisk: true });
+ return;
+ }
+
+ setRefreshKey((key) => key + 1);
+ },
+ [applyStudioManualEditsToPreview],
+ );
+
+ const handleUndo = useCallback(async () => {
+ await waitForPendingDomEditSaves();
+ const result = await editHistory.undo({
+ readFile: readHistoryProjectFile,
+ writeFile: writeHistoryProjectFile,
+ });
+ if (!result.ok && result.reason === "content-mismatch") {
+ showToast("File changed outside Studio. Undo history was not applied.", "info");
+ return;
+ }
+ if (result.ok && result.label) {
+ clearDomSelection();
+ await syncHistoryPreviewAfterApply(result.paths);
+ showToast(`Undid ${result.label}`, "info");
+ }
+ }, [
+ clearDomSelection,
+ editHistory,
+ readHistoryProjectFile,
+ showToast,
+ syncHistoryPreviewAfterApply,
+ waitForPendingDomEditSaves,
+ writeHistoryProjectFile,
+ ]);
+
+ const handleRedo = useCallback(async () => {
+ await waitForPendingDomEditSaves();
+ const result = await editHistory.redo({
+ readFile: readHistoryProjectFile,
+ writeFile: writeHistoryProjectFile,
+ });
+ if (!result.ok && result.reason === "content-mismatch") {
+ showToast("File changed outside Studio. Redo history was not applied.", "info");
+ return;
+ }
+ if (result.ok && result.label) {
+ clearDomSelection();
+ await syncHistoryPreviewAfterApply(result.paths);
+ showToast(`Redid ${result.label}`, "info");
+ }
+ }, [
+ clearDomSelection,
+ editHistory,
+ readHistoryProjectFile,
+ showToast,
+ syncHistoryPreviewAfterApply,
+ waitForPendingDomEditSaves,
+ writeHistoryProjectFile,
+ ]);
+
+ const handleUndoRef = useRef(handleUndo);
+ const handleRedoRef = useRef(handleRedo);
+ handleUndoRef.current = handleUndo;
+ handleRedoRef.current = handleRedo;
+
+ const handleHistoryHotkey = useCallback((event: KeyboardEvent) => {
+ if (!(event.metaKey || event.ctrlKey)) return;
+ if (shouldIgnoreHistoryShortcut(event.target)) return;
+ const key = event.key.toLowerCase();
+ if (key === "z" && !event.shiftKey) {
+ event.preventDefault();
+ void handleUndoRef.current();
+ return;
+ }
+ if ((key === "z" && event.shiftKey) || (event.ctrlKey && !event.metaKey && key === "y")) {
+ event.preventDefault();
+ void handleRedoRef.current();
+ }
+ }, []);
+
+ // eslint-disable-next-line no-restricted-syntax
+ useEffect(() => {
+ window.addEventListener("keydown", handleHistoryHotkey, true);
+ return () => window.removeEventListener("keydown", handleHistoryHotkey, true);
+ }, [handleHistoryHotkey]);
+
+ const syncPreviewHistoryHotkey = useCallback(
+ (iframe: HTMLIFrameElement | null) => {
+ previewHistoryHotkeyCleanupRef.current?.();
+ previewHistoryHotkeyCleanupRef.current = null;
+
+ const win = iframe?.contentWindow ?? null;
+ let doc: Document | null = null;
+ try {
+ doc = iframe?.contentDocument ?? null;
+ } catch {
+ doc = null;
+ }
+ if (!win && !doc) return;
+
+ win?.addEventListener("keydown", handleHistoryHotkey, true);
+ doc?.addEventListener("keydown", handleHistoryHotkey, true);
+ previewHistoryHotkeyCleanupRef.current = () => {
+ win?.removeEventListener("keydown", handleHistoryHotkey, true);
+ doc?.removeEventListener("keydown", handleHistoryHotkey, true);
+ };
+ },
+ [handleHistoryHotkey],
+ );
+
+ useEffect(
+ () => () => {
+ previewHistoryHotkeyCleanupRef.current?.();
+ previewHistoryHotkeyCleanupRef.current = null;
+ },
+ [],
+ );
+
+ const buildDomSelectionFromTarget = useCallback(
+ (target: HTMLElement, options?: { preferClipAncestor?: boolean }) => {
+ return resolveDomEditSelection(target, {
+ activeCompositionPath: activeCompPath,
+ isMasterView,
+ preferClipAncestor: options?.preferClipAncestor,
+ });
+ },
+ [activeCompPath, isMasterView],
+ );
+
+ const resolveDomSelectionFromPreviewPoint = useCallback(
+ (clientX: number, clientY: number, options?: { preferClipAncestor?: boolean }) => {
+ const iframe = previewIframeRef.current;
+ if (!iframe || captionEditMode) return null;
+ const target = getPreviewTargetFromPointer(iframe, clientX, clientY);
+ if (!target) return null;
+ return buildDomSelectionFromTarget(target, {
+ preferClipAncestor: options?.preferClipAncestor,
+ });
+ },
+ [buildDomSelectionFromTarget, captionEditMode],
+ );
+
+ const updateDomEditHoverSelection = useCallback((selection: DomEditSelection | null) => {
+ if (domEditSelectionsTargetSame(domEditHoverSelectionRef.current, selection)) return;
+ domEditHoverSelectionRef.current = selection;
+ setDomEditHoverSelection(selection);
+ }, []);
+
+ const preloadAgentPromptSnippet = useCallback(
+ async (selection: DomEditSelection) => {
+ const pid = projectIdRef.current;
+ if (!pid) return;
+
+ const targetPath = selection.sourceFile || activeCompPath || "index.html";
+ try {
+ const response = await fetch(
+ `/api/projects/${pid}/files/${encodeURIComponent(targetPath)}`,
+ );
+ if (!response.ok) return;
+
+ const data = (await response.json()) as { content?: string };
+ const html = data.content;
+ const tagSnippet =
+ typeof html === "string" ? readTagSnippetByTarget(html, selection) : undefined;
+
+ setAgentPromptTagSnippet((current) => {
+ if (domEditSelectionRef.current !== selection) return current;
+ return tagSnippet;
+ });
+ } catch {
+ // Runtime outerHTML is still available as a synchronous copy fallback.
+ }
+ },
+ [activeCompPath],
+ );
+
+ const resolveImportedFontAsset = useCallback(
+ (fontFamilyValue: string): ImportedFontAsset | null => {
+ const family = primaryFontFamilyValue(fontFamilyValue);
+ if (!family) return null;
+ const imported = importedFontAssetsRef.current.find(
+ (font) => font.family.toLowerCase() === family.toLowerCase(),
+ );
+ if (imported) return imported;
+ const asset = fileTree.find(
+ (path) =>
+ FONT_EXT.test(path) &&
+ fontFamilyFromAssetPath(path).toLowerCase() === family.toLowerCase(),
+ );
+ if (!asset) return null;
+ return {
+ family: fontFamilyFromAssetPath(asset),
+ path: asset,
+ url: `/api/projects/${projectId}/preview/${asset}`,
+ };
+ },
+ [fileTree, projectId],
+ );
+
+ const persistDomEditOperations = useCallback(
+ async (
+ selection: DomEditSelection,
+ operations: Parameters<typeof applyPatchByTarget>[2][],
+ options?: {
+ label?: string;
+ coalesceKey?: string;
+ skipRefresh?: boolean;
+ prepareContent?: (html: string, sourceFile: string) => string;
+ shouldSave?: () => boolean;
+ },
+ ) => {
+ const pid = projectIdRef.current;
+ if (!pid) throw new Error("No active project");
+ if (options?.shouldSave && !options.shouldSave()) return;
+
+ const targetPath = selection.sourceFile || activeCompPath || "index.html";
+ const response = await fetch(`/api/projects/${pid}/files/${encodeURIComponent(targetPath)}`);
+ if (!response.ok) {
+ throw new Error(`Failed to read ${targetPath}`);
+ }
+
+ const data = (await response.json()) as { content?: string };
+ const originalContent = data.content;
+ if (typeof originalContent !== "string") {
+ throw new Error(`Missing file contents for ${targetPath}`);
+ }
+
+ let patchedContent = originalContent;
+ for (const operation of operations) {
+ patchedContent = applyPatchByTarget(patchedContent, selection, operation);
+ }
+ if (options?.prepareContent) {
+ patchedContent = options.prepareContent(patchedContent, targetPath);
+ }
+ if (options?.shouldSave && !options.shouldSave()) return;
+
+ if (patchedContent === originalContent) {
+ throw new Error(`Unable to patch ${selection.selector ?? selection.id ?? "selection"}`);
+ }
+
+ await saveProjectFilesWithHistory({
+ projectId: pid,
+ label: options?.label ?? "Edit layer",
+ kind: "manual",
+ coalesceKey: options?.coalesceKey,
+ files: { [targetPath]: patchedContent },
+ readFile: async () => originalContent,
+ writeFile: writeProjectFile,
+ recordEdit: editHistory.recordEdit,
+ });
+
+ if (options?.skipRefresh) {
+ domEditSaveTimestampRef.current = Date.now();
+ } else {
+ setRefreshKey((k) => k + 1);
+ }
+ },
+ [activeCompPath, editHistory.recordEdit, writeProjectFile],
+ );
+
+ const refreshDomEditSelectionFromPreview = useCallback(
+ (selection: DomEditSelection) => {
+ const iframe = previewIframeRef.current;
+ let doc: Document | null = null;
+ try {
+ doc = iframe?.contentDocument ?? null;
+ } catch {
+ return;
+ }
+ if (!doc) return;
+
+ const element = findElementForSelection(doc, selection, activeCompPath);
+ if (!element) return;
+
+ const nextSelection = buildDomSelectionFromTarget(element);
+ if (nextSelection) {
+ applyDomSelection(nextSelection, { revealPanel: false, preserveGroup: true });
+ }
+ },
+ [activeCompPath, applyDomSelection, buildDomSelectionFromTarget],
+ );
+
+ const refreshDomEditGroupSelectionsFromPreview = useCallback(
+ (selections: DomEditSelection[]) => {
+ const iframe = previewIframeRef.current;
+ let doc: Document | null = null;
+ try {
+ doc = iframe?.contentDocument ?? null;
+ } catch {
+ return;
+ }
+ if (!doc) return;
+
+ const nextGroup: DomEditSelection[] = [];
+ for (const selection of selections) {
+ const element = findElementForSelection(doc, selection, activeCompPath);
+ if (!element) continue;
+ const nextSelection = buildDomSelectionFromTarget(element);
+ if (nextSelection) nextGroup.push(nextSelection);
+ }
+ if (nextGroup.length === 0) return;
+
+ const currentSelection = domEditSelectionRef.current;
+ const nextSelection =
+ nextGroup.find((selection) => domEditSelectionsTargetSame(selection, currentSelection)) ??
+ nextGroup[0] ??
+ null;
+
+ setAgentPromptTagSnippet(undefined);
+ setCopiedAgentPrompt(false);
+ domEditSelectionRef.current = nextSelection;
+ domEditGroupSelectionsRef.current = nextGroup;
+ setDomEditSelection(nextSelection);
+ setDomEditGroupSelections(nextGroup);
+
+ if (nextSelection) {
+ setSelectedTimelineElementId(
+ findMatchingTimelineElementId(nextSelection, timelineElements),
+ );
+ } else {
+ setSelectedTimelineElementId(null);
+ }
+ },
+ [activeCompPath, buildDomSelectionFromTarget, setSelectedTimelineElementId, timelineElements],
+ );
+
+ const handleDomManualDragStart = useCallback(() => {
+ const pausedTime = pauseStudioPreviewPlayback(previewIframeRef.current);
+ const playerStore = usePlayerStore.getState();
+ playerStore.setIsPlaying(false);
+ if (pausedTime != null) {
+ playerStore.setCurrentTime(pausedTime);
+ liveTime.notify(pausedTime);
+ }
+ }, []);
+
+ const handleDomPathOffsetCommit = useCallback(
+ (selection: DomEditSelection, next: { x: number; y: number }) => {
+ commitStudioManualEditManifestOptimistically(
+ (manifest) => upsertStudioPathOffsetEdit(manifest, selection, next),
+ {
+ label: "Move layer",
+ coalesceKey: `path-offset:${getDomEditTargetKey(selection)}`,
+ },
+ );
+ refreshDomEditSelectionFromPreview(selection);
+ },
+ [commitStudioManualEditManifestOptimistically, refreshDomEditSelectionFromPreview],
+ );
+
+ const handleDomGroupPathOffsetCommit = useCallback(
+ (updates: DomEditGroupPathOffsetCommit[]) => {
+ if (updates.length === 0) return;
+ const coalesceKey = updates
+ .map((update) => getDomEditTargetKey(update.selection))
+ .sort()
+ .join(":");
+ commitStudioManualEditManifestOptimistically(
+ (manifest) =>
+ updates.reduce(
+ (nextManifest, update) =>
+ upsertStudioPathOffsetEdit(nextManifest, update.selection, update.next),
+ manifest,
+ ),
+ {
+ label: `Move ${updates.length} layers`,
+ coalesceKey: `group-path-offset:${coalesceKey}`,
+ },
+ );
+ refreshDomEditGroupSelectionsFromPreview(domEditGroupSelectionsRef.current);
+ },
+ [commitStudioManualEditManifestOptimistically, refreshDomEditGroupSelectionsFromPreview],
+ );
+
+ const handleDomBoxSizeCommit = useCallback(
+ (selection: DomEditSelection, next: { width: number; height: number }) => {
+ commitStudioManualEditManifestOptimistically(
+ (manifest) => upsertStudioBoxSizeEdit(manifest, selection, next),
+ {
+ label: "Resize layer box",
+ coalesceKey: `box-size:${getDomEditTargetKey(selection)}`,
+ },
+ );
+ refreshDomEditSelectionFromPreview(selection);
+ },
+ [commitStudioManualEditManifestOptimistically, refreshDomEditSelectionFromPreview],
+ );
+
+ const handleDomRotationCommit = useCallback(
+ (selection: DomEditSelection, next: { angle: number }) => {
+ commitStudioManualEditManifestOptimistically(
+ (manifest) => upsertStudioRotationEdit(manifest, selection, next),
+ {
+ label: "Rotate layer",
+ coalesceKey: `rotation:${getDomEditTargetKey(selection)}`,
+ },
+ );
+ refreshDomEditSelectionFromPreview(selection);
+ },
+ [commitStudioManualEditManifestOptimistically, refreshDomEditSelectionFromPreview],
+ );
+
+ const handleDomManualEditsReset = useCallback(
+ (selection: DomEditSelection) => {
+ commitStudioManualEditManifestOptimistically(
+ (manifest) => removeStudioManualEditsForSelection(manifest, selection),
+ {
+ label: "Reset layer edits",
+ coalesceKey: `manual-reset:${getDomEditTargetKey(selection)}`,
+ },
+ );
+ applyCurrentStudioManualEditsToPreview(previewIframeRef.current);
+ refreshDomEditSelectionFromPreview(selection);
+ },
+ [
+ applyCurrentStudioManualEditsToPreview,
+ commitStudioManualEditManifestOptimistically,
+ refreshDomEditSelectionFromPreview,
+ ],
+ );
+
+ const handleDomStyleCommit = useCallback(
+ async (property: string, value: string) => {
+ if (!domEditSelection) return;
+ if (isManualGeometryStyleProperty(property)) return;
+ if (!domEditSelection.capabilities.canEditStyles) return;
+ const importedFont = property === "font-family" ? resolveImportedFontAsset(value) : null;
+ const iframe = previewIframeRef.current;
+ const doc = iframe?.contentDocument;
+ if (doc) {
+ const el = findElementForSelection(doc, domEditSelection, activeCompPath);
+ if (el) {
+ el.style.setProperty(property, normalizeDomEditStyleValue(property, value));
+ if (property === "font-family") {
+ injectPreviewGoogleFont(doc, value);
+ if (importedFont) injectPreviewImportedFont(doc, importedFont);
+ }
+ if (property === "background-image" && isImageBackgroundValue(value)) {
+ el.style.setProperty("background-position", "center");
+ el.style.setProperty("background-repeat", "no-repeat");
+ el.style.setProperty("background-size", "contain");
+ }
+ }
+ }
+ const operations: PatchOperation[] = [
+ buildDomEditStylePatchOperation(property, normalizeDomEditStyleValue(property, value)),
+ ];
+ if (property === "background-image" && isImageBackgroundValue(value)) {
+ operations.push(
+ buildDomEditStylePatchOperation("background-position", "center"),
+ buildDomEditStylePatchOperation("background-repeat", "no-repeat"),
+ buildDomEditStylePatchOperation("background-size", "contain"),
+ );
+ }
+ await persistDomEditOperations(domEditSelection, operations, {
+ label: "Edit layer style",
+ skipRefresh: true,
+ prepareContent: importedFont
+ ? (html, sourceFile) => ensureImportedFontFace(html, importedFont, sourceFile)
+ : undefined,
+ });
+ },
+ [activeCompPath, domEditSelection, persistDomEditOperations, resolveImportedFontAsset],
+ );
+
+ const handleDomTextCommit = useCallback(
+ async (value: string, fieldKey?: string) => {
+ if (!domEditSelection) return;
+ if (!isTextEditableSelection(domEditSelection)) return;
+ const commitVersion = domTextCommitVersionRef.current + 1;
+ domTextCommitVersionRef.current = commitVersion;
+ const nextTextFields =
+ domEditSelection.textFields.length > 0
+ ? domEditSelection.textFields.map((field) =>
+ field.key === fieldKey ? { ...field, value } : field,
+ )
+ : [];
+ const nextContent =
+ nextTextFields.length > 1 || nextTextFields.some((field) => field.source === "child")
+ ? serializeDomEditTextFields(nextTextFields)
+ : value;
+ const iframe = previewIframeRef.current;
+ const doc = iframe?.contentDocument;
+ if (doc) {
+ const el = findElementForSelection(doc, domEditSelection, activeCompPath);
+ if (el) {
+ if (
+ nextTextFields.length > 1 ||
+ nextTextFields.some((field) => field.source === "child")
+ ) {
+ el.innerHTML = nextContent;
+ } else {
+ el.textContent = value;
+ }
+ }
+ }
+ await persistDomEditOperations(
+ domEditSelection,
+ [buildDomEditTextPatchOperation(nextContent)],
+ {
+ label: "Edit text",
+ skipRefresh: true,
+ shouldSave: () => domTextCommitVersionRef.current === commitVersion,
+ },
+ );
+ if (domTextCommitVersionRef.current !== commitVersion) return;
+
+ if (doc) {
+ const refreshed = findElementForSelection(doc, domEditSelection, activeCompPath);
+ if (refreshed) {
+ const nextSelection = buildDomSelectionFromTarget(refreshed);
+ if (nextSelection) {
+ applyDomSelection(nextSelection, { revealPanel: false, preserveGroup: true });
+ }
+ }
+ }
+ },
+ [
+ activeCompPath,
+ applyDomSelection,
+ buildDomSelectionFromTarget,
+ domEditSelection,
+ persistDomEditOperations,
+ ],
+ );
+
+ const commitDomTextFields = useCallback(
+ async (
+ selection: DomEditSelection,
+ nextTextFields: DomEditTextField[],
+ options?: { importedFont?: ImportedFontAsset | null },
+ ) => {
+ const nextContent =
+ nextTextFields.length > 1 || nextTextFields.some((field) => field.source === "child")
+ ? serializeDomEditTextFields(nextTextFields)
+ : (nextTextFields[0]?.value ?? "");
+
+ const iframe = previewIframeRef.current;
+ const doc = iframe?.contentDocument;
+ if (doc) {
+ const el = findElementForSelection(doc, selection, activeCompPath);
+ if (el) {
+ if (
+ nextTextFields.length > 1 ||
+ nextTextFields.some((field) => field.source === "child")
+ ) {
+ el.innerHTML = nextContent;
+ } else {
+ el.textContent = nextContent;
+ }
+ }
+ }
+
+ const importedFont = options?.importedFont ?? null;
+ await persistDomEditOperations(selection, [buildDomEditTextPatchOperation(nextContent)], {
+ label: "Edit text",
+ skipRefresh: true,
+ prepareContent: importedFont
+ ? (html, sourceFile) => ensureImportedFontFace(html, importedFont, sourceFile)
+ : undefined,
+ });
+
+ if (doc) {
+ const refreshed = findElementForSelection(doc, selection, activeCompPath);
+ if (refreshed) {
+ const nextSelection = buildDomSelectionFromTarget(refreshed);
+ if (nextSelection) {
+ applyDomSelection(nextSelection, { revealPanel: false, preserveGroup: true });
+ }
+ }
+ }
+ },
+ [activeCompPath, applyDomSelection, buildDomSelectionFromTarget, persistDomEditOperations],
+ );
+
+ const handleDomTextFieldStyleCommit = useCallback(
+ async (fieldKey: string, property: string, value: string) => {
+ if (!domEditSelection) return;
+ const field = domEditSelection.textFields.find((entry) => entry.key === fieldKey);
+ if (!field) return;
+
+ if (field.source === "self") {
+ await handleDomStyleCommit(property, value);
+ return;
+ }
+
+ const normalizedValue = normalizeDomEditStyleValue(property, value);
+ const importedFont = property === "font-family" ? resolveImportedFontAsset(value) : null;
+ if (property === "font-family") {
+ const doc = previewIframeRef.current?.contentDocument;
+ if (doc) {
+ injectPreviewGoogleFont(doc, normalizedValue);
+ if (importedFont) injectPreviewImportedFont(doc, importedFont);
+ }
+ }
+ const nextTextFields = domEditSelection.textFields.map((entry) =>
+ entry.key === fieldKey
+ ? {
+ ...entry,
+ inlineStyles: {
+ ...entry.inlineStyles,
+ [property]: normalizedValue,
+ },
+ computedStyles: {
+ ...entry.computedStyles,
+ [property]: normalizedValue,
+ },
+ }
+ : entry,
+ );
+
+ await commitDomTextFields(domEditSelection, nextTextFields, { importedFont });
+ },
+ [commitDomTextFields, domEditSelection, handleDomStyleCommit, resolveImportedFontAsset],
+ );
+
+ const handleDomAddTextField = useCallback(
+ async (afterFieldKey?: string) => {
+ if (!domEditSelection) return null;
+ if (!domEditSelection.textFields.some((field) => field.source === "child")) return null;
+
+ const insertionIndex = domEditSelection.textFields.findIndex(
+ (field) => field.key === afterFieldKey,
+ );
+ const baseField =
+ domEditSelection.textFields[insertionIndex >= 0 ? insertionIndex : 0] ??
+ domEditSelection.textFields[0];
+ const nextField = buildDefaultDomEditTextField(baseField);
+ const nextTextFields = [...domEditSelection.textFields];
+ nextTextFields.splice(
+ insertionIndex >= 0 ? insertionIndex + 1 : nextTextFields.length,
+ 0,
+ nextField,
+ );
+
+ await commitDomTextFields(domEditSelection, nextTextFields);
+ return nextField.key;
+ },
+ [commitDomTextFields, domEditSelection],
+ );
+
+ const handleDomRemoveTextField = useCallback(
+ async (fieldKey: string) => {
+ if (!domEditSelection) return;
+ const field = domEditSelection.textFields.find((entry) => entry.key === fieldKey);
+ if (!field) return;
+
+ if (field.source === "self") {
+ await handleDomTextCommit("", fieldKey);
+ return;
+ }
+
+ const nextTextFields = domEditSelection.textFields.filter((entry) => entry.key !== fieldKey);
+ await commitDomTextFields(domEditSelection, nextTextFields);
+ },
+ [commitDomTextFields, domEditSelection, handleDomTextCommit],
+ );
+
+ const handleAskAgent = useCallback(() => {
+ if (!domEditSelection) return;
+ setAgentPromptTagSnippet(undefined);
+ void preloadAgentPromptSnippet(domEditSelection);
+ setAgentModalOpen(true);
+ }, [domEditSelection, preloadAgentPromptSnippet]);
+
+ const handleAgentModalSubmit = useCallback(
+ async (userInstruction: string) => {
+ if (!domEditSelection) return;
+
+ const targetPath = domEditSelection.sourceFile || activeCompPath || "index.html";
+ const tagSnippet = agentPromptTagSnippet ?? domEditSelection.element.outerHTML;
+ const prompt = buildElementAgentPrompt({
+ selection: domEditSelection,
+ currentTime,
+ tagSnippet,
+ userInstruction,
+ sourceFilePath: toProjectAbsolutePath(projectDir, targetPath),
+ });
+
+ const copied = await copyTextToClipboard(prompt);
+ if (!copied) {
+ showToast("Could not copy prompt to clipboard.", "error");
+ return;
+ }
+
+ setAgentModalOpen(false);
+ if (copiedAgentTimerRef.current) clearTimeout(copiedAgentTimerRef.current);
+ setCopiedAgentPrompt(true);
+ copiedAgentTimerRef.current = setTimeout(() => setCopiedAgentPrompt(false), 1600);
+ },
+ [activeCompPath, agentPromptTagSnippet, currentTime, domEditSelection, projectDir, showToast],
+ );
+
+ const handlePreviewIframeRef = useCallback(
+ (iframe: HTMLIFrameElement | null) => {
+ previewIframeRef.current = iframe;
+ setPreviewIframe(iframe);
+ syncPreviewTimelineHotkey(iframe);
+ syncPreviewHistoryHotkey(iframe);
+ consoleErrorsRef.current = [];
+ setConsoleErrors(null);
+ },
+ [syncPreviewHistoryHotkey, syncPreviewTimelineHotkey],
+ );
+
+ const handlePreviewCanvasMouseDown = useCallback(
+ (e: React.MouseEvent<HTMLDivElement>, options?: { preferClipAncestor?: boolean }) => {
+ if (captionEditMode) return;
+ const nextSelection = resolveDomSelectionFromPreviewPoint(e.clientX, e.clientY, {
+ preferClipAncestor: options?.preferClipAncestor ?? true,
+ });
+ if (!nextSelection) {
+ if (!e.shiftKey) applyDomSelection(null, { revealPanel: false });
+ return;
+ }
+ e.preventDefault();
+ e.stopPropagation();
+ applyDomSelection(nextSelection, { additive: e.shiftKey });
+ },
+ [applyDomSelection, captionEditMode, resolveDomSelectionFromPreviewPoint],
+ );
+
+ const handlePreviewCanvasPointerMove = useCallback(
+ (e: React.PointerEvent<HTMLDivElement>, options?: { preferClipAncestor?: boolean }) => {
+ if (captionEditMode) {
+ updateDomEditHoverSelection(null);
+ return null;
+ }
+
+ const nextSelection = resolveDomSelectionFromPreviewPoint(e.clientX, e.clientY, {
+ preferClipAncestor: options?.preferClipAncestor ?? false,
+ });
+ updateDomEditHoverSelection(nextSelection);
+ return nextSelection;
+ },
+ [captionEditMode, resolveDomSelectionFromPreviewPoint, updateDomEditHoverSelection],
+ );
+
+ const handlePreviewCanvasPointerLeave = useCallback(() => {
+ updateDomEditHoverSelection(null);
+ }, [updateDomEditHoverSelection]);
+
+ // eslint-disable-next-line no-restricted-syntax
+ useEffect(() => {
+ if (captionEditMode) updateDomEditHoverSelection(null);
+ }, [captionEditMode, updateDomEditHoverSelection]);
+
+ // eslint-disable-next-line no-restricted-syntax
+ useEffect(() => {
+ updateDomEditHoverSelection(null);
+ }, [activeCompPath, projectId, previewIframe, refreshKey, updateDomEditHoverSelection]);
+
+ // eslint-disable-next-line no-restricted-syntax
+ useEffect(() => {
+ if (!domEditHoverSelection) return;
+ const hoverMatchesSelection = domEditSelectionsTargetSame(
+ domEditHoverSelection,
+ domEditSelection,
+ );
+ const hoverMatchesGroup = domEditSelectionInGroup(
+ domEditGroupSelections,
+ domEditHoverSelection,
+ );
+ if (!hoverMatchesSelection && !hoverMatchesGroup) return;
+ updateDomEditHoverSelection(null);
+ }, [
+ domEditGroupSelections,
+ domEditHoverSelection,
+ domEditSelection,
+ updateDomEditHoverSelection,
+ ]);
+
+ // eslint-disable-next-line no-restricted-syntax
+ useEffect(() => {
+ if (!domEditHoverSelection) return;
+ if (domEditHoverSelection.element.isConnected) return;
+ updateDomEditHoverSelection(null);
+ }, [domEditHoverSelection, updateDomEditHoverSelection]);
+
+ // eslint-disable-next-line no-restricted-syntax
+ useEffect(() => {
+ if (!previewIframe) return;
+
+ const syncSelectionFromDocument = () => {
+ if (captionEditMode) return;
+ const currentSelection = domEditSelectionRef.current;
+ if (!currentSelection) return;
+ let doc: Document | null = null;
+ try {
+ doc = previewIframe.contentDocument;
+ } catch {
+ return;
+ }
+ if (!doc) return;
+
+ const nextElement = findElementForSelection(doc, currentSelection, activeCompPath);
+ if (!nextElement) {
+ applyDomSelection(null, { revealPanel: false });
+ return;
+ }
+
+ const nextSelection = buildDomSelectionFromTarget(nextElement);
+ if (nextSelection) {
+ applyDomSelection(nextSelection, { revealPanel: false, preserveGroup: true });
+ }
+ };
+
+ const attachErrorCapture = () => {
+ try {
+ const win = previewIframe.contentWindow as (Window & typeof globalThis) | null;
+ if (!win) return;
+ if ((win as unknown as Record<string, unknown>).__hfErrorCapture) return;
+ (win as unknown as Record<string, unknown>).__hfErrorCapture = true;
+ const origError = win.console.error.bind(win.console);
+ win.console.error = function (...args: unknown[]) {
+ origError(...args);
+ const text = args.map((a) => (a instanceof Error ? a.message : String(a))).join(" ");
+ if (text.includes("favicon")) return;
+ consoleErrorsRef.current = [
+ ...consoleErrorsRef.current,
+ { severity: "error", message: text },
+ ];
+ setConsoleErrors([...consoleErrorsRef.current]);
+ };
+ win.addEventListener("error", (e: ErrorEvent) => {
+ const text = e.message || String(e);
+ consoleErrorsRef.current = [
+ ...consoleErrorsRef.current,
+ { severity: "error", message: text },
+ ];
+ setConsoleErrors([...consoleErrorsRef.current]);
+ });
+ } catch {
+ // same-origin only
+ }
+ };
+
+ attachErrorCapture();
+ syncPreviewHistoryHotkey(previewIframe);
+ void applyStudioManualEditsToPreviewAfterRefresh(previewIframe);
+ syncSelectionFromDocument();
+
+ const handleLoad = () => {
+ consoleErrorsRef.current = [];
+ setConsoleErrors(null);
+ attachErrorCapture();
+ syncPreviewHistoryHotkey(previewIframe);
+ void applyStudioManualEditsToPreviewAfterRefresh(previewIframe);
+ syncSelectionFromDocument();
+ };
+
+ previewIframe.addEventListener("load", handleLoad);
+ return () => {
+ previewIframe.removeEventListener("load", handleLoad);
+ };
+ }, [
+ activeCompPath,
+ applyDomSelection,
+ applyStudioManualEditsToPreviewAfterRefresh,
+ buildDomSelectionFromTarget,
+ captionEditMode,
+ previewIframe,
+ syncPreviewHistoryHotkey,
+ ]);
+
+ // eslint-disable-next-line no-restricted-syntax
+ useEffect(() => {
+ if (!captionEditMode) return;
+ applyDomSelection(null, { revealPanel: false });
+ }, [applyDomSelection, captionEditMode]);
+
+ // eslint-disable-next-line no-restricted-syntax
+ useEffect(
+ () => () => {
+ if (copiedAgentTimerRef.current) clearTimeout(copiedAgentTimerRef.current);
+ },
+ [],
+ );
+
+ const refreshFileTree = useCallback(async () => {
+ const pid = projectIdRef.current;
+ if (!pid) return;
+ const res = await fetch(`/api/projects/${pid}`);
+ const data = await res.json();
+ if (data.files) setFileTree(data.files);
+ }, []);
+
+ const uploadProjectFiles = useCallback(
+ async (files: Iterable<File>, dir?: string): Promise<string[]> => {
+ const pid = projectIdRef.current;
+ const fileList = Array.from(files);
+ if (!pid || fileList.length === 0) return [];
+
+ const formData = new FormData();
+ for (const file of fileList) {
+ formData.append("file", file);
+ }
+
+ const qs = dir ? `?dir=${encodeURIComponent(dir)}` : "";
+ try {
+ const res = await fetch(`/api/projects/${pid}/upload${qs}`, {
+ method: "POST",
+ body: formData,
+ });
+ if (res.ok) {
+ const data = await res.json();
+ if (data.skipped?.length) {
+ showToast(`Skipped (too large): ${data.skipped.join(", ")}`);
+ }
+ if (data.invalid?.length) {
+ const names = data.invalid.map((entry: { name: string }) => entry.name).join(", ");
+ showToast(`Unsupported media skipped: ${names}`);
+ }
+ await refreshFileTree();
+ setRefreshKey((k) => k + 1);
+ return Array.isArray(data.files) ? data.files : [];
+ } else if (res.status === 413) {
+ showToast("Upload rejected: payload too large");
+ } else {
+ showToast(`Upload failed (${res.status})`);
+ }
+ } catch {
+ showToast("Upload failed: network error");
+ }
+ return [];
+ },
+ [refreshFileTree, showToast],
+ );
+
+ const handleTimelineAssetDrop = useCallback(
+ async (
+ assetPath: string,
+ placement: Pick<TimelineElement, "start" | "track">,
+ durationOverride?: number,
+ ) => {
+ const pid = projectIdRef.current;
+ if (!pid) throw new Error("No active project");
const kind = getTimelineAssetKind(assetPath);
if (!kind) {
@@ -1138,24 +2881,19 @@ export function StudioApp() {
duration: normalizedDuration,
track: placement.track,
zIndex: trackZIndices.get(placement.track) ?? 1,
+ geometry: resolveTimelineAssetInitialGeometry(originalContent),
}),
);
- const saveResponse = await fetch(
- `/api/projects/${pid}/files/${encodeURIComponent(targetPath)}`,
- {
- method: "PUT",
- headers: { "Content-Type": "text/plain" },
- body: patchedContent,
- },
- );
- if (!saveResponse.ok) {
- throw new Error(`Failed to save ${targetPath}`);
- }
-
- if (editingPathRef.current === targetPath) {
- setEditingFile({ path: targetPath, content: patchedContent });
- }
+ await saveProjectFilesWithHistory({
+ projectId: pid,
+ label: "Add timeline asset",
+ kind: "timeline",
+ files: { [targetPath]: patchedContent },
+ readFile: async () => originalContent,
+ writeFile: writeProjectFile,
+ recordEdit: editHistory.recordEdit,
+ });
setRefreshKey((k) => k + 1);
} catch (error) {
@@ -1164,7 +2902,7 @@ export function StudioApp() {
showToast(message);
}
},
- [activeCompPath, showToast, timelineElements],
+ [activeCompPath, editHistory.recordEdit, showToast, timelineElements, writeProjectFile],
);
const handleTimelineFileDrop = useCallback(
@@ -1322,7 +3060,33 @@ export function StudioApp() {
const handleImportFiles = useCallback(
async (files: FileList | File[], dir?: string) => {
- void uploadProjectFiles(Array.from(files), dir);
+ return uploadProjectFiles(Array.from(files), dir);
+ },
+ [uploadProjectFiles],
+ );
+
+ const handleImportFonts = useCallback(
+ async (files: FileList | File[]) => {
+ const uploaded = await uploadProjectFiles(
+ Array.from(files).filter((file) => FONT_EXT.test(file.name)),
+ "assets/fonts",
+ );
+ const pid = projectIdRef.current;
+ const imported = uploaded
+ .filter((asset) => FONT_EXT.test(asset))
+ .map((asset) => ({
+ family: fontFamilyFromAssetPath(asset),
+ path: asset,
+ url: `/api/projects/${pid}/preview/${asset}`,
+ }));
+ importedFontAssetsRef.current = [
+ ...imported,
+ ...importedFontAssetsRef.current.filter(
+ (existing) =>
+ !imported.some((font) => font.family.toLowerCase() === existing.family.toLowerCase()),
+ ),
+ ];
+ return imported;
},
[uploadProjectFiles],
);
@@ -1394,6 +3158,17 @@ export function StudioApp() {
fileTree.filter((f) => !f.endsWith(".html") && !f.endsWith(".md") && !f.endsWith(".json")),
[fileTree],
);
+ const fontAssets = useMemo<ImportedFontAsset[]>(
+ () =>
+ assets
+ .filter((asset) => FONT_EXT.test(asset))
+ .map((asset) => ({
+ family: fontFamilyFromAssetPath(asset),
+ path: asset,
+ url: `/api/projects/${projectId}/preview/${asset}`,
+ })),
+ [assets, projectId],
+ );
if (resolving || !projectId) {
return (
@@ -1439,6 +3214,42 @@ export function StudioApp() {
</div>
{/* Right: toolbar buttons */}
<div className="flex items-center gap-1.5">
+ <button
+ type="button"
+ onClick={() => void handleUndo()}
+ disabled={!editHistory.canUndo}
+ className={`h-7 w-7 flex items-center justify-center rounded-md border transition-colors ${
+ editHistory.canUndo
+ ? "border-neutral-700 text-neutral-300 hover:border-neutral-500 hover:bg-neutral-800"
+ : "border-neutral-900 text-neutral-700"
+ }`}
+ title={
+ editHistory.undoLabel
+ ? `Undo ${editHistory.undoLabel} (${getHistoryShortcutLabel("undo")})`
+ : `Undo (${getHistoryShortcutLabel("undo")})`
+ }
+ aria-label="Undo"
+ >
+ <RotateCcw size={14} />
+ </button>
+ <button
+ type="button"
+ onClick={() => void handleRedo()}
+ disabled={!editHistory.canRedo}
+ className={`h-7 w-7 flex items-center justify-center rounded-md border transition-colors ${
+ editHistory.canRedo
+ ? "border-neutral-700 text-neutral-300 hover:border-neutral-500 hover:bg-neutral-800"
+ : "border-neutral-900 text-neutral-700"
+ }`}
+ title={
+ editHistory.redoLabel
+ ? `Redo ${editHistory.redoLabel} (${getHistoryShortcutLabel("redo")})`
+ : `Redo (${getHistoryShortcutLabel("redo")})`
+ }
+ aria-label="Redo"
+ >
+ <RotateCw size={14} />
+ </button>
<a
href={captureFrameHref}
download={captureFrameFilename}
@@ -1453,7 +3264,15 @@ export function StudioApp() {
<span>Capture</span>
</a>
<button
- onClick={() => setRightCollapsed((v) => !v)}
+ onClick={() => {
+ if (rightCollapsed || rightPanelTab !== "design") {
+ setRightPanelTab("design");
+ setRightCollapsed(false);
+ return;
+ }
+ clearDomSelection();
+ setRightCollapsed(true);
+ }}
className={`h-7 flex items-center gap-1.5 px-2.5 rounded-md text-[11px] font-medium border transition-colors ${
!rightCollapsed
? "text-studio-accent bg-studio-accent/10 border-studio-accent/30"
@@ -1471,8 +3290,7 @@ export function StudioApp() {
<circle cx="12" cy="12" r="10" />
<polygon points="10 8 16 12 10 16" fill="currentColor" stroke="none" />
</svg>
- Renders
- {renderQueue.jobs.length > 0 ? ` (${renderQueue.jobs.length})` : ""}
+ Inspector
</button>
</div>
</div>
@@ -1589,56 +3407,34 @@ export function StudioApp() {
// or navigates back via breadcrumb — keeps sidebar + thumbnails in sync.
setActiveCompPath(compPath);
}}
- onIframeRef={(iframe) => {
- previewIframeRef.current = iframe;
- syncPreviewTimelineHotkey(iframe);
- consoleErrorsRef.current = [];
- setConsoleErrors(null);
- if (!iframe) return;
-
- // Attach error capture after each iframe load (content resets on navigation)
- const attachErrorCapture = () => {
- try {
- const win = iframe.contentWindow as (Window & typeof globalThis) | null;
- if (!win) return;
- // Guard against double-patching
- if ((win as unknown as Record<string, unknown>).__hfErrorCapture) return;
- (win as unknown as Record<string, unknown>).__hfErrorCapture = true;
- const origError = win.console.error.bind(win.console);
- win.console.error = function (...args: unknown[]) {
- origError(...args);
- const text = args
- .map((a) => (a instanceof Error ? a.message : String(a)))
- .join(" ");
- if (text.includes("favicon")) return;
- consoleErrorsRef.current = [
- ...consoleErrorsRef.current,
- { severity: "error", message: text },
- ];
- setConsoleErrors([...consoleErrorsRef.current]);
- };
- win.addEventListener("error", (e: ErrorEvent) => {
- const text = e.message || String(e);
- consoleErrorsRef.current = [
- ...consoleErrorsRef.current,
- { severity: "error", message: text },
- ];
- setConsoleErrors([...consoleErrorsRef.current]);
- });
- } catch {
- // cross-origin — can't attach
- }
- };
- // Attach now (iframe may already be loaded) and on future loads
- attachErrorCapture();
- iframe.addEventListener("load", () => {
- consoleErrorsRef.current = [];
- setConsoleErrors(null);
- attachErrorCapture();
- });
- }}
+ onIframeRef={handlePreviewIframeRef}
previewOverlay={
- captionEditMode ? <CaptionOverlay iframeRef={previewIframeRef} /> : undefined
+ captionEditMode ? (
+ <CaptionOverlay iframeRef={previewIframeRef} />
+ ) : (
+ <DomEditOverlay
+ iframeRef={previewIframeRef}
+ activeCompositionPath={activeCompPath}
+ hoverSelection={captionEditMode ? null : domEditHoverSelection}
+ selection={
+ !rightCollapsed && rightPanelTab === "design" ? domEditSelection : null
+ }
+ groupSelections={
+ !rightCollapsed && rightPanelTab === "design" ? domEditGroupSelections : []
+ }
+ allowCanvasMovement
+ onCanvasMouseDown={handlePreviewCanvasMouseDown}
+ onCanvasPointerMove={handlePreviewCanvasPointerMove}
+ onCanvasPointerLeave={handlePreviewCanvasPointerLeave}
+ onSelectionChange={applyDomSelection}
+ onBlockedMove={handleBlockedDomMove}
+ onManualDragStart={handleDomManualDragStart}
+ onPathOffsetCommit={handleDomPathOffsetCommit}
+ onGroupPathOffsetCommit={handleDomGroupPathOffsetCommit}
+ onBoxSizeCommit={handleDomBoxSizeCommit}
+ onRotationCommit={handleDomRotationCommit}
+ />
+ )
}
timelineFooter={
captionEditMode ? (
@@ -1679,14 +3475,69 @@ export function StudioApp() {
{captionEditMode ? (
<CaptionPropertyPanel iframeRef={previewIframeRef} />
) : (
- <RenderQueue
- jobs={renderQueue.jobs}
- projectId={projectId}
- onDelete={renderQueue.deleteRender}
- onClearCompleted={renderQueue.clearCompleted}
- onStartRender={(format, quality) => renderQueue.startRender(30, quality, format)}
- isRendering={renderQueue.isRendering}
- />
+ <>
+ <div className="flex items-center gap-1 border-b border-neutral-800 px-3 py-2">
+ <button
+ type="button"
+ onClick={() => setRightPanelTab("design")}
+ className={`h-8 rounded-xl px-3 text-[11px] font-medium transition-colors ${
+ rightPanelTab === "design"
+ ? "bg-neutral-800 text-white"
+ : "text-neutral-500 hover:bg-neutral-800/70 hover:text-neutral-200"
+ }`}
+ >
+ Design
+ </button>
+ <button
+ type="button"
+ onClick={() => setRightPanelTab("renders")}
+ className={`h-8 rounded-xl px-3 text-[11px] font-medium transition-colors ${
+ rightPanelTab === "renders"
+ ? "bg-neutral-800 text-white"
+ : "text-neutral-500 hover:bg-neutral-800/70 hover:text-neutral-200"
+ }`}
+ >
+ {renderQueue.jobs.length > 0
+ ? `Renders (${renderQueue.jobs.length})`
+ : "Renders"}
+ </button>
+ </div>
+ <div className="min-h-0 flex-1">
+ {rightPanelTab === "design" ? (
+ <PropertyPanel
+ projectId={projectId}
+ assets={assets}
+ element={domEditGroupSelections.length > 1 ? null : domEditSelection}
+ copiedAgentPrompt={copiedAgentPrompt}
+ onClearSelection={clearDomSelection}
+ onSetStyle={handleDomStyleCommit}
+ onSetManualOffset={handleDomPathOffsetCommit}
+ onSetManualSize={handleDomBoxSizeCommit}
+ onSetText={handleDomTextCommit}
+ onSetTextFieldStyle={handleDomTextFieldStyleCommit}
+ onAddTextField={handleDomAddTextField}
+ onRemoveTextField={handleDomRemoveTextField}
+ onResetManualEdits={handleDomManualEditsReset}
+ onAskAgent={handleAskAgent}
+ onImportAssets={handleImportFiles}
+ fontAssets={fontAssets}
+ onImportFonts={handleImportFonts}
+ />
+ ) : (
+ <RenderQueue
+ jobs={renderQueue.jobs}
+ projectId={projectId}
+ onDelete={renderQueue.deleteRender}
+ onClearCompleted={renderQueue.clearCompleted}
+ onStartRender={async (format, quality) => {
+ await waitForPendingDomEditSaves();
+ await renderQueue.startRender(30, quality, format);
+ }}
+ isRendering={renderQueue.isRendering}
+ />
+ )}
+ </div>
+ </>
)}
</div>
</>
@@ -1707,6 +3558,15 @@ export function StudioApp() {
/>
)}
+ {/* Ask agent modal */}
+ {agentModalOpen && domEditSelection && (
+ <AskAgentModal
+ selectionLabel={domEditSelection.label}
+ onSubmit={handleAgentModalSubmit}
+ onClose={() => setAgentModalOpen(false)}
+ />
+ )}
+
{/* Global drag-drop overlay */}
{globalDragOver && (
<div className="absolute inset-0 z-[90] flex items-center justify-center bg-black/50 backdrop-blur-sm pointer-events-none">
diff --git a/packages/studio/src/components/LintModal.tsx b/packages/studio/src/components/LintModal.tsx
index c71d5ed1bb..5a7a343317 100644
--- a/packages/studio/src/components/LintModal.tsx
+++ b/packages/studio/src/components/LintModal.tsx
@@ -1,5 +1,6 @@
import { useState } from "react";
import { XIcon, WarningIcon, CheckCircleIcon, CaretRightIcon } from "@phosphor-icons/react";
+import { copyTextToClipboard } from "../utils/clipboard";
export interface LintFinding {
severity: "error" | "warning";
@@ -30,12 +31,10 @@ export function LintModal({
return line;
});
const text = `Fix these HyperFrames lint issues for project "${projectId}":\n\nProject path: ${window.location.href}\n\n${lines.join("\n\n")}`;
- try {
- await navigator.clipboard.writeText(text);
+ const copiedText = await copyTextToClipboard(text);
+ if (copiedText) {
setCopied(true);
setTimeout(() => setCopied(false), 2000);
- } catch {
- // ignore
}
};
diff --git a/packages/studio/src/components/editor/DomEditOverlay.test.ts b/packages/studio/src/components/editor/DomEditOverlay.test.ts
new file mode 100644
index 0000000000..b609a1f149
--- /dev/null
+++ b/packages/studio/src/components/editor/DomEditOverlay.test.ts
@@ -0,0 +1,241 @@
+import { describe, expect, it } from "vitest";
+import { Window } from "happy-dom";
+import {
+ filterNestedDomEditGroupItems,
+ focusDomEditOverlayElement,
+ hasDomEditRotationChanged,
+ resolveDomEditCoordinateScale,
+ resolveDomEditGroupOverlayRect,
+ resolveDomEditResizeGesture,
+ resolveDomEditRotationGesture,
+} from "./DomEditOverlay";
+
+describe("focusDomEditOverlayElement", () => {
+ it("focuses the canvas overlay without scrolling", () => {
+ const calls: Array<FocusOptions | undefined> = [];
+ focusDomEditOverlayElement({
+ focus: (options?: FocusOptions) => calls.push(options),
+ });
+
+ expect(calls).toEqual([{ preventScroll: true }]);
+ });
+});
+
+describe("resolveDomEditCoordinateScale", () => {
+ it("uses the top-level preview scale when no source boundary dimensions are available", () => {
+ expect(
+ resolveDomEditCoordinateScale({
+ rootScaleX: 0.5,
+ rootScaleY: 0.5,
+ }),
+ ).toEqual({
+ scaleX: 0.5,
+ scaleY: 0.5,
+ });
+ });
+
+ it("converts source-local pixels through a scaled nested composition host", () => {
+ expect(
+ resolveDomEditCoordinateScale({
+ rootScaleX: 0.5,
+ rootScaleY: 0.5,
+ sourceRectWidth: 960,
+ sourceRectHeight: 540,
+ sourceWidth: 1920,
+ sourceHeight: 1080,
+ }),
+ ).toEqual({
+ scaleX: 0.25,
+ scaleY: 0.25,
+ });
+ });
+});
+
+describe("resolveDomEditGroupOverlayRect", () => {
+ it("returns a bounding box that contains every selected element", () => {
+ expect(
+ resolveDomEditGroupOverlayRect([
+ { left: 40, top: 30, width: 80, height: 50, editScaleX: 1, editScaleY: 1 },
+ { left: 150, top: 10, width: 30, height: 120, editScaleX: 0.5, editScaleY: 0.5 },
+ { left: 20, top: 90, width: 50, height: 20, editScaleX: 2, editScaleY: 2 },
+ ]),
+ ).toEqual({
+ left: 20,
+ top: 10,
+ width: 160,
+ height: 120,
+ editScaleX: 1,
+ editScaleY: 1,
+ });
+ });
+
+ it("returns null for an empty group", () => {
+ expect(resolveDomEditGroupOverlayRect([])).toBeNull();
+ });
+});
+
+describe("filterNestedDomEditGroupItems", () => {
+ it("keeps top-level selected elements so descendants are not moved twice", () => {
+ const window = new Window();
+ const parent = window.document.createElement("div");
+ const child = window.document.createElement("div");
+ const sibling = window.document.createElement("div");
+ parent.append(child);
+
+ expect(
+ filterNestedDomEditGroupItems([
+ { key: "parent", element: parent },
+ { key: "child", element: child },
+ { key: "sibling", element: sibling },
+ ]).map((item) => item.key),
+ ).toEqual(["parent", "sibling"]);
+ });
+});
+
+describe("resolveDomEditResizeGesture", () => {
+ it("resizes width and height independently by default", () => {
+ expect(
+ resolveDomEditResizeGesture({
+ originWidth: 240,
+ originHeight: 120,
+ actualWidth: 240,
+ actualHeight: 120,
+ scaleX: 1,
+ scaleY: 1,
+ dx: 30,
+ dy: 12,
+ uniform: false,
+ }),
+ ).toEqual({
+ overlayWidth: 270,
+ overlayHeight: 132,
+ width: 270,
+ height: 132,
+ });
+ });
+
+ it("snaps width and height to the same value when Shift is held", () => {
+ expect(
+ resolveDomEditResizeGesture({
+ originWidth: 240,
+ originHeight: 120,
+ actualWidth: 240,
+ actualHeight: 120,
+ scaleX: 1,
+ scaleY: 1,
+ dx: 30,
+ dy: 12,
+ uniform: true,
+ }),
+ ).toEqual({
+ overlayWidth: 270,
+ overlayHeight: 270,
+ width: 270,
+ height: 270,
+ });
+ });
+
+ it("uses the dominant pointer delta for uniform shrink", () => {
+ expect(
+ resolveDomEditResizeGesture({
+ originWidth: 300,
+ originHeight: 180,
+ actualWidth: 300,
+ actualHeight: 180,
+ scaleX: 1,
+ scaleY: 1,
+ dx: 8,
+ dy: -40,
+ uniform: true,
+ }),
+ ).toMatchObject({
+ width: 260,
+ height: 260,
+ });
+ });
+
+ it("writes source-local dimensions when the edited source is scaled down in master view", () => {
+ expect(
+ resolveDomEditResizeGesture({
+ originWidth: 100,
+ originHeight: 50,
+ actualWidth: 400,
+ actualHeight: 200,
+ scaleX: 0.25,
+ scaleY: 0.25,
+ dx: 25,
+ dy: 10,
+ uniform: false,
+ }),
+ ).toEqual({
+ overlayWidth: 125,
+ overlayHeight: 60,
+ width: 500,
+ height: 240,
+ });
+ });
+});
+
+describe("resolveDomEditRotationGesture", () => {
+ it("rotates by the pointer angle around the element center", () => {
+ expect(
+ resolveDomEditRotationGesture({
+ centerX: 0,
+ centerY: 0,
+ startX: 0,
+ startY: -10,
+ currentX: 10,
+ currentY: 0,
+ actualAngle: 5,
+ snap: false,
+ }),
+ ).toEqual({ angle: 95 });
+ });
+
+ it("uses the shortest delta across the 180 degree boundary", () => {
+ expect(
+ resolveDomEditRotationGesture({
+ centerX: 0,
+ centerY: 0,
+ startX: -10,
+ startY: 1.76,
+ currentX: -10,
+ currentY: -1.76,
+ actualAngle: 0,
+ snap: false,
+ }).angle,
+ ).toBeCloseTo(20, 1);
+ });
+
+ it("snaps to 15 degree increments when requested", () => {
+ expect(
+ resolveDomEditRotationGesture({
+ centerX: 0,
+ centerY: 0,
+ startX: 10,
+ startY: 0,
+ currentX: 10,
+ currentY: 3.25,
+ actualAngle: 0,
+ snap: true,
+ }),
+ ).toEqual({ angle: 15 });
+ });
+
+ it("allows small pointer movements when the rounded angle changes", () => {
+ const nextRotation = resolveDomEditRotationGesture({
+ centerX: 0,
+ centerY: 0,
+ startX: 0,
+ startY: -40,
+ currentX: 1,
+ currentY: -40,
+ actualAngle: 0,
+ snap: false,
+ });
+
+ expect(nextRotation.angle).toBe(1.4);
+ expect(hasDomEditRotationChanged(0, nextRotation.angle)).toBe(true);
+ expect(hasDomEditRotationChanged(0, 0)).toBe(false);
+ });
+});
diff --git a/packages/studio/src/components/editor/DomEditOverlay.tsx b/packages/studio/src/components/editor/DomEditOverlay.tsx
new file mode 100644
index 0000000000..a645a124db
--- /dev/null
+++ b/packages/studio/src/components/editor/DomEditOverlay.tsx
@@ -0,0 +1,1300 @@
+import { memo, useMemo, useRef, useState, type RefObject } from "react";
+import { useMountEffect } from "../../hooks/useMountEffect";
+import { type DomEditSelection, findElementForSelection } from "./domEditing";
+import {
+ applyManualOffsetDragCommit,
+ applyManualOffsetDragDraft,
+ createManualOffsetDragMember,
+ endManualOffsetDragMembers,
+ restoreManualOffsetDragMembers,
+ type ManualOffsetDragMember,
+} from "./manualOffsetDrag";
+import {
+ applyStudioBoxSize,
+ applyStudioBoxSizeDraft,
+ applyStudioRotation,
+ applyStudioRotationDraft,
+ beginStudioManualEditGesture,
+ captureStudioBoxSize,
+ captureStudioPathOffset,
+ captureStudioRotation,
+ endStudioManualEditGesture,
+ isStudioManualEditGestureCurrent,
+ readStudioBoxSize,
+ readStudioRotation,
+ restoreStudioBoxSize,
+ restoreStudioPathOffset,
+ restoreStudioRotation,
+ type StudioBoxSizeSnapshot,
+ type StudioPathOffsetSnapshot,
+ type StudioRotationSnapshot,
+} from "./manualEdits";
+
+interface OverlayRect {
+ left: number;
+ top: number;
+ width: number;
+ height: number;
+ editScaleX: number;
+ editScaleY: number;
+}
+
+interface GroupOverlayItem {
+ key: string;
+ selection: DomEditSelection;
+ element: HTMLElement;
+ rect: OverlayRect;
+}
+
+export interface DomEditGroupPathOffsetCommit {
+ selection: DomEditSelection;
+ next: { x: number; y: number };
+}
+
+interface DomEditOverlayProps {
+ iframeRef: RefObject<HTMLIFrameElement | null>;
+ activeCompositionPath: string | null;
+ selection: DomEditSelection | null;
+ groupSelections?: DomEditSelection[];
+ hoverSelection: DomEditSelection | null;
+ allowCanvasMovement?: boolean;
+ onCanvasMouseDown: (
+ event: React.MouseEvent<HTMLDivElement>,
+ options?: { preferClipAncestor?: boolean },
+ ) => void;
+ onCanvasPointerMove: (
+ event: React.PointerEvent<HTMLDivElement>,
+ options?: { preferClipAncestor?: boolean },
+ ) => DomEditSelection | null;
+ onCanvasPointerLeave: () => void;
+ onSelectionChange: (
+ selection: DomEditSelection,
+ options?: { revealPanel?: boolean; additive?: boolean },
+ ) => void;
+ onBlockedMove: (selection: DomEditSelection) => void;
+ onManualDragStart?: () => void;
+ onPathOffsetCommit: (
+ selection: DomEditSelection,
+ next: { x: number; y: number },
+ ) => Promise<void> | void;
+ onGroupPathOffsetCommit: (updates: DomEditGroupPathOffsetCommit[]) => Promise<void> | void;
+ onBoxSizeCommit: (
+ selection: DomEditSelection,
+ next: { width: number; height: number },
+ ) => Promise<void> | void;
+ onRotationCommit: (selection: DomEditSelection, next: { angle: number }) => Promise<void> | void;
+}
+
+function toOverlayRect(
+ overlayEl: HTMLDivElement,
+ iframe: HTMLIFrameElement,
+ element: HTMLElement,
+): OverlayRect | null {
+ const iframeRect = iframe.getBoundingClientRect();
+ const overlayRect = overlayEl.getBoundingClientRect();
+ const doc = iframe.contentDocument;
+ const root =
+ doc?.querySelector<HTMLElement>("[data-composition-id]") ?? doc?.documentElement ?? null;
+ const rootRect = root?.getBoundingClientRect();
+ const rootWidth = rootRect?.width;
+ const rootHeight = rootRect?.height;
+ if (!rootWidth || !rootHeight) return null;
+
+ const elementRect = element.getBoundingClientRect();
+ const rootScaleX = iframeRect.width / rootWidth;
+ const rootScaleY = iframeRect.height / rootHeight;
+ const sourceBoundary = findSourceBoundary(element);
+ const sourceBoundaryRect = sourceBoundary?.getBoundingClientRect();
+ const editScale = resolveDomEditCoordinateScale({
+ rootScaleX,
+ rootScaleY,
+ sourceRectWidth: sourceBoundaryRect?.width,
+ sourceRectHeight: sourceBoundaryRect?.height,
+ sourceWidth: readPositiveDimension(sourceBoundary?.getAttribute("data-width") ?? null),
+ sourceHeight: readPositiveDimension(sourceBoundary?.getAttribute("data-height") ?? null),
+ });
+
+ return {
+ left: iframeRect.left - overlayRect.left + (elementRect.left - rootRect.left) * rootScaleX,
+ top: iframeRect.top - overlayRect.top + (elementRect.top - rootRect.top) * rootScaleY,
+ width: elementRect.width * rootScaleX,
+ height: elementRect.height * rootScaleY,
+ editScaleX: editScale.scaleX,
+ editScaleY: editScale.scaleY,
+ };
+}
+
+function readPositiveDimension(value: string | null): number | null {
+ if (!value) return null;
+ const parsed = Number.parseFloat(value);
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
+}
+
+function findSourceBoundary(element: HTMLElement): HTMLElement | null {
+ let current: HTMLElement | null = element;
+ while (current) {
+ if (
+ current.hasAttribute("data-composition-file") ||
+ current.hasAttribute("data-composition-src")
+ ) {
+ return current;
+ }
+ current = current.parentElement;
+ }
+ return null;
+}
+
+export function resolveDomEditCoordinateScale(input: {
+ rootScaleX: number;
+ rootScaleY: number;
+ sourceRectWidth?: number;
+ sourceRectHeight?: number;
+ sourceWidth?: number | null;
+ sourceHeight?: number | null;
+}): { scaleX: number; scaleY: number } {
+ const rootScaleX = input.rootScaleX > 0 ? input.rootScaleX : 1;
+ const rootScaleY = input.rootScaleY > 0 ? input.rootScaleY : 1;
+ const sourceScaleX =
+ input.sourceRectWidth && input.sourceRectWidth > 0 && input.sourceWidth && input.sourceWidth > 0
+ ? (input.sourceRectWidth * rootScaleX) / input.sourceWidth
+ : rootScaleX;
+ const sourceScaleY =
+ input.sourceRectHeight &&
+ input.sourceRectHeight > 0 &&
+ input.sourceHeight &&
+ input.sourceHeight > 0
+ ? (input.sourceRectHeight * rootScaleY) / input.sourceHeight
+ : rootScaleY;
+ return {
+ scaleX: sourceScaleX > 0 ? sourceScaleX : rootScaleX,
+ scaleY: sourceScaleY > 0 ? sourceScaleY : rootScaleY,
+ };
+}
+
+type GestureKind = "drag" | "resize" | "rotate";
+const BLOCKED_MOVE_THRESHOLD_PX = 4;
+const MIN_RESIZE_EDGE_PX = 20;
+const OVERLAY_RECT_EPSILON_PX = 0.5;
+const ROTATION_COMMIT_EPSILON_DEGREES = 0.05;
+const ROTATION_SNAP_DEGREES = 15;
+
+function rectsEqual(a: OverlayRect | null, b: OverlayRect | null): boolean {
+ if (a === b) return true;
+ if (!a || !b) return false;
+ return (
+ Math.abs(a.left - b.left) < OVERLAY_RECT_EPSILON_PX &&
+ Math.abs(a.top - b.top) < OVERLAY_RECT_EPSILON_PX &&
+ Math.abs(a.width - b.width) < OVERLAY_RECT_EPSILON_PX &&
+ Math.abs(a.height - b.height) < OVERLAY_RECT_EPSILON_PX &&
+ Math.abs(a.editScaleX - b.editScaleX) < 0.001 &&
+ Math.abs(a.editScaleY - b.editScaleY) < 0.001
+ );
+}
+
+function groupOverlayItemsEqual(a: GroupOverlayItem[], b: GroupOverlayItem[]): boolean {
+ if (a === b) return true;
+ if (a.length !== b.length) return false;
+ return a.every((item, index) => {
+ const other = b[index];
+ return Boolean(
+ other &&
+ item.key === other.key &&
+ item.element === other.element &&
+ item.selection === other.selection &&
+ rectsEqual(item.rect, other.rect),
+ );
+ });
+}
+
+export function resolveDomEditGroupOverlayRect(rects: OverlayRect[]): OverlayRect | null {
+ const first = rects[0];
+ if (!first) return null;
+
+ let left = first.left;
+ let top = first.top;
+ let right = first.left + first.width;
+ let bottom = first.top + first.height;
+
+ for (const rect of rects.slice(1)) {
+ left = Math.min(left, rect.left);
+ top = Math.min(top, rect.top);
+ right = Math.max(right, rect.left + rect.width);
+ bottom = Math.max(bottom, rect.top + rect.height);
+ }
+
+ return {
+ left,
+ top,
+ width: right - left,
+ height: bottom - top,
+ editScaleX: 1,
+ editScaleY: 1,
+ };
+}
+
+export function filterNestedDomEditGroupItems<T extends { element: HTMLElement }>(items: T[]): T[] {
+ return items.filter(
+ (item) => !items.some((other) => other !== item && other.element.contains(item.element)),
+ );
+}
+
+function selectionCacheKey(
+ selection: Pick<DomEditSelection, "id" | "selector" | "selectorIndex" | "sourceFile">,
+): string {
+ return [
+ selection.sourceFile ?? "",
+ selection.id ?? "",
+ selection.selector ?? "",
+ selection.selectorIndex ?? "",
+ ].join("|");
+}
+
+type FocusableDomEditOverlay = {
+ focus(options?: FocusOptions): void;
+};
+
+export function focusDomEditOverlayElement(element: FocusableDomEditOverlay | null): void {
+ element?.focus({ preventScroll: true });
+}
+
+export function resolveDomEditResizeGesture(input: {
+ originWidth: number;
+ originHeight: number;
+ actualWidth: number;
+ actualHeight: number;
+ scaleX: number;
+ scaleY: number;
+ dx: number;
+ dy: number;
+ uniform: boolean;
+}): { overlayWidth: number; overlayHeight: number; width: number; height: number } {
+ const scaleX = input.scaleX > 0 ? input.scaleX : 1;
+ const scaleY = input.scaleY > 0 ? input.scaleY : 1;
+
+ if (input.uniform) {
+ const deltaX = input.dx / scaleX;
+ const deltaY = input.dy / scaleY;
+ const delta = Math.abs(deltaX) >= Math.abs(deltaY) ? deltaX : deltaY;
+ const side = Math.max(1, Math.max(input.actualWidth, input.actualHeight) + delta);
+ return {
+ overlayWidth: Math.max(MIN_RESIZE_EDGE_PX, side * scaleX),
+ overlayHeight: Math.max(MIN_RESIZE_EDGE_PX, side * scaleY),
+ width: side,
+ height: side,
+ };
+ }
+
+ return {
+ overlayWidth: Math.max(MIN_RESIZE_EDGE_PX, input.originWidth + input.dx),
+ overlayHeight: Math.max(MIN_RESIZE_EDGE_PX, input.originHeight + input.dy),
+ width: Math.max(1, input.actualWidth + input.dx / scaleX),
+ height: Math.max(1, input.actualHeight + input.dy / scaleY),
+ };
+}
+
+function pointerAngleDegrees(centerX: number, centerY: number, x: number, y: number): number {
+ return (Math.atan2(y - centerY, x - centerX) * 180) / Math.PI;
+}
+
+function normalizeAngleDelta(delta: number): number {
+ return ((((delta + 180) % 360) + 360) % 360) - 180;
+}
+
+function roundAngle(angle: number): number {
+ return Math.round(angle * 10) / 10;
+}
+
+export function resolveDomEditRotationGesture(input: {
+ centerX: number;
+ centerY: number;
+ startX: number;
+ startY: number;
+ currentX: number;
+ currentY: number;
+ actualAngle: number;
+ snap: boolean;
+}): { angle: number } {
+ const startAngle = pointerAngleDegrees(input.centerX, input.centerY, input.startX, input.startY);
+ const currentAngle = pointerAngleDegrees(
+ input.centerX,
+ input.centerY,
+ input.currentX,
+ input.currentY,
+ );
+ const delta = normalizeAngleDelta(currentAngle - startAngle);
+ const angle = input.actualAngle + delta;
+ return {
+ angle: input.snap
+ ? Math.round(angle / ROTATION_SNAP_DEGREES) * ROTATION_SNAP_DEGREES
+ : roundAngle(angle),
+ };
+}
+
+export function hasDomEditRotationChanged(initialAngle: number, nextAngle: number): boolean {
+ return Math.abs(nextAngle - initialAngle) >= ROTATION_COMMIT_EPSILON_DEGREES;
+}
+
+interface GestureState {
+ kind: GestureKind;
+ mode: "path-offset" | "box-size" | "rotation";
+ selection: DomEditSelection;
+ startX: number;
+ startY: number;
+ centerX: number;
+ centerY: number;
+ initialPathOffset: StudioPathOffsetSnapshot;
+ initialRotation: StudioRotationSnapshot;
+ initialBoxSize: StudioBoxSizeSnapshot;
+ pathOffsetMember?: ManualOffsetDragMember;
+ originLeft: number;
+ originTop: number;
+ originWidth: number;
+ originHeight: number;
+ actualWidth: number;
+ actualHeight: number;
+ actualRotation: number;
+ editScaleX: number;
+ editScaleY: number;
+ manualEditDragToken?: string;
+}
+
+interface GroupGestureState {
+ startX: number;
+ startY: number;
+ originItems: GroupOverlayItem[];
+ members: ManualOffsetDragMember[];
+}
+
+interface BlockedMoveState {
+ pointerId: number;
+ startX: number;
+ startY: number;
+ notified: boolean;
+}
+
+type ResolvedElementRef = {
+ current: { key: string; element: HTMLElement } | null;
+};
+
+export const DomEditOverlay = memo(function DomEditOverlay({
+ iframeRef,
+ activeCompositionPath,
+ selection,
+ groupSelections = [],
+ hoverSelection,
+ allowCanvasMovement = true,
+ onCanvasMouseDown,
+ onCanvasPointerMove,
+ onCanvasPointerLeave,
+ onSelectionChange,
+ onBlockedMove,
+ onManualDragStart,
+ onPathOffsetCommit,
+ onGroupPathOffsetCommit,
+ onBoxSizeCommit,
+ onRotationCommit,
+}: DomEditOverlayProps) {
+ const overlayRef = useRef<HTMLDivElement | null>(null);
+ const boxRef = useRef<HTMLDivElement | null>(null);
+ const [overlayRect, setOverlayRect] = useState<OverlayRect | null>(null);
+ const [hoverRect, setHoverRect] = useState<OverlayRect | null>(null);
+ const [groupOverlayItems, setGroupOverlayItems] = useState<GroupOverlayItem[]>([]);
+ const gestureRef = useRef<GestureState | null>(null);
+ const groupGestureRef = useRef<GroupGestureState | null>(null);
+ const blockedMoveRef = useRef<BlockedMoveState | null>(null);
+ const suppressNextBoxClickRef = useRef(false);
+ const suppressNextBoxMouseDownRef = useRef(false);
+ const suppressNextOverlayMouseDownRef = useRef(false);
+ const rafPausedRef = useRef(false);
+ const resolvedElementRef = useRef<{ key: string; element: HTMLElement } | null>(null);
+ const resolvedHoverElementRef = useRef<{ key: string; element: HTMLElement } | null>(null);
+ const resolvedGroupElementRef = useRef<Map<string, HTMLElement>>(new Map());
+
+ const selectionRef = useRef(selection);
+ selectionRef.current = selection;
+ const activeCompositionPathRef = useRef(activeCompositionPath);
+ activeCompositionPathRef.current = activeCompositionPath;
+ const groupSelectionsRef = useRef(groupSelections);
+ groupSelectionsRef.current = groupSelections;
+ const hoverSelectionRef = useRef(hoverSelection);
+ hoverSelectionRef.current = hoverSelection;
+ const overlayRectRef = useRef(overlayRect);
+ overlayRectRef.current = overlayRect;
+ const hoverRectRef = useRef(hoverRect);
+ hoverRectRef.current = hoverRect;
+ const groupOverlayItemsRef = useRef(groupOverlayItems);
+ groupOverlayItemsRef.current = groupOverlayItems;
+ const onPathOffsetCommitRef = useRef(onPathOffsetCommit);
+ onPathOffsetCommitRef.current = onPathOffsetCommit;
+ const onGroupPathOffsetCommitRef = useRef(onGroupPathOffsetCommit);
+ onGroupPathOffsetCommitRef.current = onGroupPathOffsetCommit;
+ const onBoxSizeCommitRef = useRef(onBoxSizeCommit);
+ onBoxSizeCommitRef.current = onBoxSizeCommit;
+ const onRotationCommitRef = useRef(onRotationCommit);
+ onRotationCommitRef.current = onRotationCommit;
+ const onBlockedMoveRef = useRef(onBlockedMove);
+ onBlockedMoveRef.current = onBlockedMove;
+ const onManualDragStartRef = useRef(onManualDragStart);
+ onManualDragStartRef.current = onManualDragStart;
+ const onCanvasPointerMoveRef = useRef(onCanvasPointerMove);
+ onCanvasPointerMoveRef.current = onCanvasPointerMove;
+ const onCanvasPointerLeaveRef = useRef(onCanvasPointerLeave);
+ onCanvasPointerLeaveRef.current = onCanvasPointerLeave;
+ const onSelectionChangeRef = useRef(onSelectionChange);
+ onSelectionChangeRef.current = onSelectionChange;
+
+ useMountEffect(() => {
+ let frame = 0;
+ const clearOverlayRect = () => {
+ if (!overlayRectRef.current) return;
+ overlayRectRef.current = null;
+ setOverlayRect(null);
+ };
+ const setNextOverlayRect = (next: OverlayRect | null) => {
+ if (rectsEqual(overlayRectRef.current, next)) return;
+ overlayRectRef.current = next;
+ setOverlayRect(next);
+ };
+ const clearHoverRect = () => {
+ if (!hoverRectRef.current) return;
+ hoverRectRef.current = null;
+ setHoverRect(null);
+ };
+ const setNextHoverRect = (next: OverlayRect | null) => {
+ if (rectsEqual(hoverRectRef.current, next)) return;
+ hoverRectRef.current = next;
+ setHoverRect(next);
+ };
+ const clearGroupOverlayItems = () => {
+ if (groupOverlayItemsRef.current.length === 0) return;
+ groupOverlayItemsRef.current = [];
+ setGroupOverlayItems([]);
+ };
+ const setNextGroupOverlayItems = (next: GroupOverlayItem[]) => {
+ if (groupOverlayItemsEqual(groupOverlayItemsRef.current, next)) return;
+ groupOverlayItemsRef.current = next;
+ setGroupOverlayItems(next);
+ };
+ const resolveElement = (doc: Document, sel: DomEditSelection, cacheRef: ResolvedElementRef) => {
+ const key = selectionCacheKey(sel);
+ const cached = cacheRef.current;
+ if (
+ cached?.key === key &&
+ cached.element.isConnected &&
+ cached.element.ownerDocument === doc
+ ) {
+ return cached.element;
+ }
+
+ const next = findElementForSelection(doc, sel, activeCompositionPathRef.current);
+ cacheRef.current = next ? { key, element: next } : null;
+ return next;
+ };
+ const resolveGroupElement = (doc: Document, sel: DomEditSelection) => {
+ const key = selectionCacheKey(sel);
+ const cached = resolvedGroupElementRef.current.get(key);
+ if (cached?.isConnected && cached.ownerDocument === doc) return cached;
+
+ const next = findElementForSelection(doc, sel, activeCompositionPathRef.current);
+ if (next) {
+ resolvedGroupElementRef.current.set(key, next);
+ } else {
+ resolvedGroupElementRef.current.delete(key);
+ }
+ return next;
+ };
+
+ const update = () => {
+ frame = requestAnimationFrame(update);
+ if (rafPausedRef.current) return;
+
+ const sel = selectionRef.current;
+ const iframe = iframeRef.current;
+ const overlayEl = overlayRef.current;
+ if (!iframe || !overlayEl) {
+ resolvedElementRef.current = null;
+ resolvedHoverElementRef.current = null;
+ resolvedGroupElementRef.current.clear();
+ clearOverlayRect();
+ clearHoverRect();
+ clearGroupOverlayItems();
+ return;
+ }
+
+ const doc = iframe.contentDocument;
+ if (!doc) {
+ resolvedElementRef.current = null;
+ resolvedHoverElementRef.current = null;
+ resolvedGroupElementRef.current.clear();
+ clearOverlayRect();
+ clearHoverRect();
+ clearGroupOverlayItems();
+ return;
+ }
+
+ if (sel) {
+ const el = resolveElement(doc, sel, resolvedElementRef);
+ if (el) {
+ setNextOverlayRect(toOverlayRect(overlayEl, iframe, el));
+ } else {
+ clearOverlayRect();
+ }
+ } else {
+ resolvedElementRef.current = null;
+ clearOverlayRect();
+ }
+
+ const group = groupSelectionsRef.current;
+ if (group.length > 0) {
+ const nextGroupItems: GroupOverlayItem[] = [];
+ const liveGroupKeys = new Set<string>();
+ for (const groupSelection of group) {
+ const key = selectionCacheKey(groupSelection);
+ liveGroupKeys.add(key);
+ const el = resolveGroupElement(doc, groupSelection);
+ const rect = el ? toOverlayRect(overlayEl, iframe, el) : null;
+ if (el && rect)
+ nextGroupItems.push({ key, selection: groupSelection, element: el, rect });
+ }
+ for (const key of resolvedGroupElementRef.current.keys()) {
+ if (!liveGroupKeys.has(key)) resolvedGroupElementRef.current.delete(key);
+ }
+ setNextGroupOverlayItems(nextGroupItems);
+ } else {
+ resolvedGroupElementRef.current.clear();
+ clearGroupOverlayItems();
+ }
+
+ const hoverSel = hoverSelectionRef.current;
+ const hoverMatchesSelection = Boolean(
+ sel && hoverSel && selectionCacheKey(sel) === selectionCacheKey(hoverSel),
+ );
+ const hoverMatchesGroup = Boolean(
+ hoverSel && group.some((entry) => selectionCacheKey(entry) === selectionCacheKey(hoverSel)),
+ );
+ if (!hoverSel || hoverMatchesSelection || hoverMatchesGroup) {
+ resolvedHoverElementRef.current = null;
+ clearHoverRect();
+ return;
+ }
+
+ const hoverEl = resolveElement(doc, hoverSel, resolvedHoverElementRef);
+ if (!hoverEl) {
+ clearHoverRect();
+ return;
+ }
+
+ setNextHoverRect(toOverlayRect(overlayEl, iframe, hoverEl));
+ };
+
+ frame = requestAnimationFrame(update);
+ return () => cancelAnimationFrame(frame);
+ });
+
+ const selectionKey = useMemo(() => {
+ if (!selection) return "none";
+ return `${selection.sourceFile}:${selection.id ?? selection.selector ?? selection.label}:${
+ selection.selectorIndex ?? 0
+ }`;
+ }, [selection]);
+ const groupBounds = useMemo(
+ () => resolveDomEditGroupOverlayRect(groupOverlayItems.map((item) => item.rect)),
+ [groupOverlayItems],
+ );
+ const hasGroupSelection = groupSelections.length > 1;
+ const groupCanMove =
+ hasGroupSelection &&
+ groupOverlayItems.length > 1 &&
+ groupOverlayItems.every((item) => item.selection.capabilities.canApplyManualOffset);
+
+ const setDraftOverlayRect = (next: OverlayRect) => {
+ if (rectsEqual(overlayRectRef.current, next)) return;
+ overlayRectRef.current = next;
+ setOverlayRect(next);
+ };
+
+ const restoreGestureOverlayRect = (g: GestureState) => {
+ setDraftOverlayRect({
+ left: g.originLeft,
+ top: g.originTop,
+ width: g.originWidth,
+ height: g.originHeight,
+ editScaleX: g.editScaleX,
+ editScaleY: g.editScaleY,
+ });
+ };
+
+ const setDraftGroupOverlayItems = (next: GroupOverlayItem[]) => {
+ if (groupOverlayItemsEqual(groupOverlayItemsRef.current, next)) return;
+ groupOverlayItemsRef.current = next;
+ setGroupOverlayItems(next);
+ };
+
+ const restoreGroupGestureOverlayItems = (g: GroupGestureState) => {
+ setDraftGroupOverlayItems(g.originItems);
+ };
+
+ const startGroupDrag = (e: React.PointerEvent<HTMLElement>) => {
+ const items = groupOverlayItemsRef.current;
+ if (items.length <= 1) return false;
+
+ const blockedSelection = items.find(
+ (item) => !item.selection.capabilities.canApplyManualOffset,
+ )?.selection;
+ if (blockedSelection) {
+ e.preventDefault();
+ e.stopPropagation();
+ onBlockedMoveRef.current(blockedSelection);
+ return false;
+ }
+
+ onManualDragStartRef.current?.();
+
+ const dragItems = filterNestedDomEditGroupItems(items);
+
+ const members: ManualOffsetDragMember[] = [];
+ for (const item of dragItems) {
+ const result = createManualOffsetDragMember({
+ key: item.key,
+ selection: item.selection,
+ element: item.element,
+ rect: item.rect,
+ });
+ if (!result.ok) {
+ restoreManualOffsetDragMembers(members);
+ e.preventDefault();
+ e.stopPropagation();
+ onBlockedMoveRef.current(result.selection);
+ return false;
+ }
+ members.push(result.member);
+ }
+
+ e.preventDefault();
+ e.stopPropagation();
+ e.currentTarget.setPointerCapture(e.pointerId);
+
+ rafPausedRef.current = true;
+ groupGestureRef.current = {
+ startX: e.clientX,
+ startY: e.clientY,
+ originItems: items,
+ members,
+ };
+ return true;
+ };
+
+ const restoreGroupPathOffsets = (g: GroupGestureState) => {
+ restoreManualOffsetDragMembers(g.members);
+ restoreGroupGestureOverlayItems(g);
+ };
+
+ const startGesture = (
+ kind: GestureKind,
+ e: React.PointerEvent<HTMLElement>,
+ options?: { selection?: DomEditSelection; rect?: OverlayRect | null },
+ ) => {
+ const sel = options?.selection ?? selectionRef.current;
+ const rect = options?.rect ?? overlayRectRef.current;
+ const box = boxRef.current;
+ const overlayEl = overlayRef.current;
+ if (!sel || !rect) return false;
+ if (kind !== "drag" && !box) return false;
+ const mode: GestureState["mode"] =
+ kind === "rotate" ? "rotation" : kind === "drag" ? "path-offset" : "box-size";
+ if (kind === "drag" && !sel.capabilities.canApplyManualOffset) return false;
+ if (kind === "resize" && !sel.capabilities.canApplyManualSize) return false;
+ if (kind === "rotate" && !sel.capabilities.canApplyManualRotation) return false;
+ if (kind === "resize" && (!Number.isFinite(rect.width) || !Number.isFinite(rect.height))) {
+ return false;
+ }
+ const size = readStudioBoxSize(sel.element);
+ const rotation = readStudioRotation(sel.element);
+ const actualWidth = size.width > 0 ? size.width : rect.width / rect.editScaleX;
+ const actualHeight = size.height > 0 ? size.height : rect.height / rect.editScaleY;
+ let initialPathOffset = captureStudioPathOffset(sel.element);
+ let manualEditDragToken: string | undefined;
+ let pathOffsetMember: ManualOffsetDragMember | undefined;
+ if (kind === "drag") {
+ onManualDragStartRef.current?.();
+ const result = createManualOffsetDragMember({
+ key: selectionCacheKey(sel),
+ selection: sel,
+ element: sel.element,
+ rect,
+ });
+ if (!result.ok) {
+ onBlockedMoveRef.current(result.selection);
+ return false;
+ }
+ pathOffsetMember = result.member;
+ initialPathOffset = result.member.initialPathOffset;
+ manualEditDragToken = result.member.gestureToken;
+ } else {
+ manualEditDragToken = beginStudioManualEditGesture(sel.element);
+ }
+ const overlayBounds = overlayEl?.getBoundingClientRect();
+ const centerX = (overlayBounds?.left ?? 0) + rect.left + rect.width / 2;
+ const centerY = (overlayBounds?.top ?? 0) + rect.top + rect.height / 2;
+
+ e.preventDefault();
+ e.stopPropagation();
+ e.currentTarget.setPointerCapture(e.pointerId);
+
+ rafPausedRef.current = true;
+
+ gestureRef.current = {
+ kind,
+ mode,
+ selection: sel,
+ startX: e.clientX,
+ startY: e.clientY,
+ centerX,
+ centerY,
+ initialPathOffset,
+ initialRotation: captureStudioRotation(sel.element),
+ initialBoxSize: captureStudioBoxSize(sel.element),
+ pathOffsetMember,
+ originLeft: rect.left,
+ originTop: rect.top,
+ originWidth: rect.width,
+ originHeight: rect.height,
+ actualWidth,
+ actualHeight,
+ actualRotation: rotation.angle,
+ editScaleX: rect.editScaleX,
+ editScaleY: rect.editScaleY,
+ manualEditDragToken,
+ };
+ return true;
+ };
+
+ const onPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
+ const g = gestureRef.current;
+ const groupG = groupGestureRef.current;
+ const sel = g?.selection ?? selectionRef.current;
+ const box = boxRef.current;
+ const blockedMove = blockedMoveRef.current;
+ if (!blockedMove && !g && !groupG) {
+ onCanvasPointerMoveRef.current(e, { preferClipAncestor: false });
+ }
+
+ if (blockedMove && sel) {
+ const dx = e.clientX - blockedMove.startX;
+ const dy = e.clientY - blockedMove.startY;
+ if (!blockedMove.notified && Math.hypot(dx, dy) >= BLOCKED_MOVE_THRESHOLD_PX) {
+ blockedMove.notified = true;
+ suppressNextBoxClickRef.current = true;
+ onBlockedMoveRef.current(sel);
+ }
+ return;
+ }
+
+ if (groupG) {
+ const dx = e.clientX - groupG.startX;
+ const dy = e.clientY - groupG.startY;
+ setDraftGroupOverlayItems(
+ groupG.originItems.map((item) => ({
+ ...item,
+ rect: {
+ ...item.rect,
+ left: item.rect.left + dx,
+ top: item.rect.top + dy,
+ },
+ })),
+ );
+ for (const member of groupG.members) {
+ applyManualOffsetDragDraft(member, dx, dy);
+ }
+ return;
+ }
+
+ if (!g || !sel) return;
+
+ const dx = e.clientX - g.startX;
+ const dy = e.clientY - g.startY;
+
+ if (g.kind === "rotate") {
+ const nextRotation = resolveDomEditRotationGesture({
+ centerX: g.centerX,
+ centerY: g.centerY,
+ startX: g.startX,
+ startY: g.startY,
+ currentX: e.clientX,
+ currentY: e.clientY,
+ actualAngle: g.actualRotation,
+ snap: e.shiftKey,
+ });
+ applyStudioRotationDraft(sel.element, nextRotation);
+ return;
+ }
+
+ if (g.kind === "drag") {
+ const nextBoxLeft = g.originLeft + dx;
+ const nextBoxTop = g.originTop + dy;
+ setDraftOverlayRect({
+ left: nextBoxLeft,
+ top: nextBoxTop,
+ width: g.originWidth,
+ height: g.originHeight,
+ editScaleX: g.editScaleX,
+ editScaleY: g.editScaleY,
+ });
+ if (box) {
+ box.style.left = `${nextBoxLeft}px`;
+ box.style.top = `${nextBoxTop}px`;
+ }
+ if (g.pathOffsetMember) applyManualOffsetDragDraft(g.pathOffsetMember, dx, dy);
+ } else {
+ if (!box) return;
+ const nextSize = resolveDomEditResizeGesture({
+ originWidth: g.originWidth,
+ originHeight: g.originHeight,
+ actualWidth: g.actualWidth,
+ actualHeight: g.actualHeight,
+ scaleX: g.editScaleX,
+ scaleY: g.editScaleY,
+ dx,
+ dy,
+ uniform: e.shiftKey,
+ });
+ setDraftOverlayRect({
+ left: g.originLeft,
+ top: g.originTop,
+ width: nextSize.overlayWidth,
+ height: nextSize.overlayHeight,
+ editScaleX: g.editScaleX,
+ editScaleY: g.editScaleY,
+ });
+ box.style.width = `${nextSize.overlayWidth}px`;
+ box.style.height = `${nextSize.overlayHeight}px`;
+ applyStudioBoxSizeDraft(sel.element, nextSize);
+ }
+ };
+
+ const onPointerUp = (e: React.PointerEvent<HTMLDivElement>) => {
+ const g = gestureRef.current;
+ const groupG = groupGestureRef.current;
+ const sel = g?.selection ?? selectionRef.current;
+ const box = boxRef.current;
+ blockedMoveRef.current = null;
+
+ if (groupG) {
+ groupGestureRef.current = null;
+ rafPausedRef.current = false;
+
+ const dx = e.clientX - groupG.startX;
+ const dy = e.clientY - groupG.startY;
+ const movedDistance = Math.hypot(e.clientX - groupG.startX, e.clientY - groupG.startY);
+ if (movedDistance < BLOCKED_MOVE_THRESHOLD_PX) {
+ restoreGroupPathOffsets(groupG);
+ suppressNextBoxClickRef.current = true;
+ return;
+ }
+
+ setDraftGroupOverlayItems(
+ groupG.originItems.map((item) => ({
+ ...item,
+ rect: {
+ ...item.rect,
+ left: item.rect.left + dx,
+ top: item.rect.top + dy,
+ },
+ })),
+ );
+ const updates = groupG.members.map((member) => {
+ const finalOffset = applyManualOffsetDragCommit(member, dx, dy);
+ return { selection: member.selection, next: finalOffset };
+ });
+ void Promise.resolve(onGroupPathOffsetCommitRef.current(updates))
+ .catch(() => {
+ for (const member of groupG.members) {
+ if (
+ member.gestureToken &&
+ isStudioManualEditGestureCurrent(member.element, member.gestureToken)
+ ) {
+ restoreStudioPathOffset(member.element, member.initialPathOffset);
+ }
+ }
+ })
+ .finally(() => {
+ endManualOffsetDragMembers(groupG.members);
+ });
+ return;
+ }
+
+ if (!g || !sel) {
+ gestureRef.current = null;
+ rafPausedRef.current = false;
+ return;
+ }
+
+ gestureRef.current = null;
+ rafPausedRef.current = false;
+
+ const movedDistance = Math.hypot(e.clientX - g.startX, e.clientY - g.startY);
+ if (g.kind === "drag" && movedDistance < BLOCKED_MOVE_THRESHOLD_PX) {
+ restoreStudioPathOffset(sel.element, g.initialPathOffset);
+ endStudioManualEditGesture(sel.element, g.manualEditDragToken);
+ if (box) {
+ box.style.left = `${g.originLeft}px`;
+ box.style.top = `${g.originTop}px`;
+ }
+ restoreGestureOverlayRect(g);
+ suppressNextBoxClickRef.current = true;
+ onCanvasMouseDown(e as unknown as React.MouseEvent<HTMLDivElement>, {
+ preferClipAncestor: false,
+ });
+ return;
+ }
+
+ if (g.kind === "resize" && movedDistance < BLOCKED_MOVE_THRESHOLD_PX) {
+ restoreStudioBoxSize(sel.element, g.initialBoxSize);
+ endStudioManualEditGesture(sel.element, g.manualEditDragToken);
+ if (box) {
+ box.style.width = `${g.originWidth}px`;
+ box.style.height = `${g.originHeight}px`;
+ }
+ restoreGestureOverlayRect(g);
+ return;
+ }
+
+ if (g.kind === "rotate") {
+ const finalRotation = resolveDomEditRotationGesture({
+ centerX: g.centerX,
+ centerY: g.centerY,
+ startX: g.startX,
+ startY: g.startY,
+ currentX: e.clientX,
+ currentY: e.clientY,
+ actualAngle: g.actualRotation,
+ snap: e.shiftKey,
+ });
+ if (!hasDomEditRotationChanged(g.actualRotation, finalRotation.angle)) {
+ restoreStudioRotation(sel.element, g.initialRotation);
+ endStudioManualEditGesture(sel.element, g.manualEditDragToken);
+ return;
+ }
+ applyStudioRotation(sel.element, finalRotation);
+ void Promise.resolve(onRotationCommitRef.current(sel, finalRotation))
+ .catch(() => {
+ if (
+ g.manualEditDragToken &&
+ isStudioManualEditGestureCurrent(sel.element, g.manualEditDragToken)
+ ) {
+ restoreStudioRotation(sel.element, g.initialRotation);
+ }
+ })
+ .finally(() => {
+ endStudioManualEditGesture(sel.element, g.manualEditDragToken);
+ });
+ } else if (g.kind === "drag") {
+ const dx = e.clientX - g.startX;
+ const dy = e.clientY - g.startY;
+ if (!g.pathOffsetMember) return;
+ const finalOffset = applyManualOffsetDragCommit(g.pathOffsetMember, dx, dy);
+ const nextBoxLeft = g.originLeft + dx;
+ const nextBoxTop = g.originTop + dy;
+ setDraftOverlayRect({
+ left: nextBoxLeft,
+ top: nextBoxTop,
+ width: g.originWidth,
+ height: g.originHeight,
+ editScaleX: g.editScaleX,
+ editScaleY: g.editScaleY,
+ });
+ if (box) {
+ box.style.left = `${nextBoxLeft}px`;
+ box.style.top = `${nextBoxTop}px`;
+ }
+ void Promise.resolve(onPathOffsetCommitRef.current(sel, finalOffset))
+ .catch(() => {
+ if (
+ g.pathOffsetMember?.gestureToken &&
+ isStudioManualEditGestureCurrent(sel.element, g.pathOffsetMember.gestureToken)
+ ) {
+ restoreStudioPathOffset(sel.element, g.initialPathOffset);
+ }
+ })
+ .finally(() => {
+ if (g.pathOffsetMember) endManualOffsetDragMembers([g.pathOffsetMember]);
+ });
+ } else {
+ const finalSize = readStudioBoxSize(sel.element);
+ applyStudioBoxSize(sel.element, finalSize);
+ void Promise.resolve(onBoxSizeCommitRef.current(sel, finalSize))
+ .catch(() => {
+ if (
+ g.manualEditDragToken &&
+ isStudioManualEditGestureCurrent(sel.element, g.manualEditDragToken)
+ ) {
+ restoreStudioBoxSize(sel.element, g.initialBoxSize);
+ }
+ })
+ .finally(() => {
+ endStudioManualEditGesture(sel.element, g.manualEditDragToken);
+ });
+ }
+ };
+
+ // Click on overlay background → select whatever is under the pointer in the iframe.
+ // This handles clicking children inside an already-selected parent: the selection
+ // box stops propagation for drag gestures, but clicks on the transparent overlay
+ // area outside the box pass through to the iframe pick logic.
+ const handleOverlayMouseDown = (event: React.MouseEvent<HTMLDivElement>) => {
+ if (suppressNextOverlayMouseDownRef.current) {
+ suppressNextOverlayMouseDownRef.current = false;
+ suppressNextBoxMouseDownRef.current = false;
+ suppressNextBoxClickRef.current = false;
+ event.preventDefault();
+ event.stopPropagation();
+ return;
+ }
+ const target = event.target as HTMLElement | null;
+ if (target?.closest('[data-dom-edit-selection-box="true"]')) return;
+ onCanvasMouseDown(event, { preferClipAncestor: false });
+ if (event.shiftKey) {
+ suppressNextBoxMouseDownRef.current = true;
+ suppressNextBoxClickRef.current = true;
+ }
+ };
+
+ const handleOverlayPointerDown = (event: React.PointerEvent<HTMLDivElement>) => {
+ if (!allowCanvasMovement || event.button !== 0) return;
+ if (event.shiftKey) {
+ const candidate =
+ onCanvasPointerMoveRef.current(event, {
+ preferClipAncestor: false,
+ }) ?? hoverSelectionRef.current;
+ if (!candidate) return;
+
+ event.preventDefault();
+ event.stopPropagation();
+ suppressNextOverlayMouseDownRef.current = true;
+ suppressNextBoxMouseDownRef.current = true;
+ suppressNextBoxClickRef.current = true;
+ onSelectionChangeRef.current(candidate, { additive: true });
+ return;
+ }
+
+ const target = event.target as HTMLElement | null;
+ if (target?.closest('[data-dom-edit-selection-box="true"]')) return;
+
+ const hoverCandidate = onCanvasPointerMoveRef.current(event, {
+ preferClipAncestor: false,
+ });
+ const candidate = hoverCandidate ?? hoverSelectionRef.current;
+ if (!candidate?.capabilities.canApplyManualOffset) return;
+
+ const overlayEl = overlayRef.current;
+ const iframe = iframeRef.current;
+ const candidateRect =
+ overlayEl && iframe ? toOverlayRect(overlayEl, iframe, candidate.element) : null;
+ if (!candidateRect) return;
+
+ suppressNextOverlayMouseDownRef.current = true;
+ selectionRef.current = candidate;
+ overlayRectRef.current = candidateRect;
+ hoverRectRef.current = null;
+ setOverlayRect(candidateRect);
+ setHoverRect(null);
+ const didStartGesture = startGesture("drag", event, {
+ selection: candidate,
+ rect: candidateRect,
+ });
+ if (!didStartGesture) {
+ suppressNextOverlayMouseDownRef.current = false;
+ return;
+ }
+ onSelectionChangeRef.current(candidate);
+ };
+
+ // Click on the selection box itself → re-pick the element under the pointer.
+ // This lets you click a child element even when a parent is selected, because
+ // the click coordinates are forwarded to the iframe's element picker.
+ const handleBoxClick = (event: React.MouseEvent<HTMLDivElement>) => {
+ if (gestureRef.current || groupGestureRef.current) return;
+ if (suppressNextBoxClickRef.current) {
+ suppressNextBoxClickRef.current = false;
+ event.stopPropagation();
+ return;
+ }
+ onCanvasMouseDown(event, { preferClipAncestor: false });
+ };
+
+ const clearPointerState = () => {
+ const groupG = groupGestureRef.current;
+ if (groupG) restoreGroupPathOffsets(groupG);
+ const g = gestureRef.current;
+ const sel = g?.selection ?? selectionRef.current;
+ if (g?.mode === "path-offset" && sel) {
+ restoreStudioPathOffset(sel.element, g.initialPathOffset);
+ endStudioManualEditGesture(sel.element, g.manualEditDragToken);
+ restoreGestureOverlayRect(g);
+ }
+ if (g?.mode === "box-size" && sel) {
+ restoreStudioBoxSize(sel.element, g.initialBoxSize);
+ endStudioManualEditGesture(sel.element, g.manualEditDragToken);
+ restoreGestureOverlayRect(g);
+ }
+ if (g?.mode === "rotation" && sel) {
+ restoreStudioRotation(sel.element, g.initialRotation);
+ endStudioManualEditGesture(sel.element, g.manualEditDragToken);
+ }
+ blockedMoveRef.current = null;
+ groupGestureRef.current = null;
+ gestureRef.current = null;
+ rafPausedRef.current = false;
+ };
+
+ return (
+ <div
+ ref={overlayRef}
+ className="absolute inset-0 z-10 pointer-events-auto outline-none"
+ tabIndex={-1}
+ aria-label="Composition canvas"
+ onPointerDownCapture={(event) => focusDomEditOverlayElement(event.currentTarget)}
+ onPointerDown={handleOverlayPointerDown}
+ onMouseDown={handleOverlayMouseDown}
+ onPointerMove={onPointerMove}
+ onPointerLeave={() => onCanvasPointerLeaveRef.current()}
+ onPointerUp={onPointerUp}
+ onPointerCancel={clearPointerState}
+ >
+ {hoverSelection && hoverRect && (
+ <div
+ aria-hidden="true"
+ data-dom-edit-hover-box="true"
+ className="pointer-events-none absolute rounded-xl border border-studio-accent/80 bg-studio-accent/5 shadow-[0_0_0_1px_rgba(60,230,172,0.25)]"
+ style={{
+ left: hoverRect.left,
+ top: hoverRect.top,
+ width: hoverRect.width,
+ height: hoverRect.height,
+ }}
+ />
+ )}
+ {hasGroupSelection && groupOverlayItems.length > 1 && groupBounds && (
+ <>
+ {groupOverlayItems.map((item) => (
+ <div
+ key={item.key}
+ aria-hidden="true"
+ className="pointer-events-none absolute rounded-xl border border-studio-accent/70 bg-studio-accent/[0.03]"
+ style={{
+ left: item.rect.left,
+ top: item.rect.top,
+ width: item.rect.width,
+ height: item.rect.height,
+ }}
+ />
+ ))}
+ <div
+ data-dom-edit-selection-box="true"
+ className="pointer-events-auto absolute rounded-xl border border-studio-accent bg-studio-accent/5 shadow-[0_0_0_1px_rgba(60,230,172,0.3)]"
+ style={{
+ left: groupBounds.left,
+ top: groupBounds.top,
+ width: groupBounds.width,
+ height: groupBounds.height,
+ cursor: allowCanvasMovement && groupCanMove ? "move" : "default",
+ }}
+ onPointerDown={(e) => {
+ if (!allowCanvasMovement) return;
+ if (e.shiftKey) return;
+ startGroupDrag(e);
+ }}
+ onMouseDown={(e) => {
+ if (!suppressNextBoxMouseDownRef.current) return;
+ suppressNextBoxMouseDownRef.current = false;
+ e.preventDefault();
+ e.stopPropagation();
+ }}
+ onClick={handleBoxClick}
+ />
+ </>
+ )}
+ {!hasGroupSelection && selection && overlayRect && (
+ <>
+ {allowCanvasMovement && selection.capabilities.canApplyManualRotation && (
+ <div
+ className="pointer-events-none absolute"
+ style={{
+ left: overlayRect.left + overlayRect.width / 2,
+ top: overlayRect.top - 34,
+ width: 28,
+ height: 34,
+ transform: "translateX(-50%)",
+ }}
+ >
+ <div className="absolute left-1/2 top-3 bottom-0 w-px -translate-x-1/2 bg-studio-accent/60" />
+ <button
+ type="button"
+ className="pointer-events-auto absolute left-1/2 top-0 h-3 w-3 -translate-x-1/2 rounded-full border border-studio-accent bg-studio-accent p-0 shadow-[0_0_0_2px_rgba(60,230,172,0.18)]"
+ style={{ cursor: "grab", touchAction: "none" }}
+ title="Rotate"
+ aria-label="Rotate selection"
+ onPointerDown={(e) => {
+ e.stopPropagation();
+ startGesture("rotate", e);
+ }}
+ />
+ </div>
+ )}
+ <div
+ key={selectionKey}
+ ref={boxRef}
+ data-dom-edit-selection-box="true"
+ className="pointer-events-auto absolute rounded-xl border border-studio-accent/80 bg-studio-accent/5 shadow-[0_0_0_1px_rgba(60,230,172,0.25)]"
+ style={{
+ left: overlayRect.left,
+ top: overlayRect.top,
+ width: overlayRect.width,
+ height: overlayRect.height,
+ cursor:
+ allowCanvasMovement && selection.capabilities.canApplyManualOffset
+ ? "move"
+ : "default",
+ }}
+ onPointerDown={(e) => {
+ if (!allowCanvasMovement) return;
+ if (e.shiftKey) return;
+ if (selection.capabilities.canApplyManualOffset) {
+ startGesture("drag", e);
+ return;
+ }
+ e.preventDefault();
+ e.stopPropagation();
+ e.currentTarget.setPointerCapture(e.pointerId);
+ blockedMoveRef.current = {
+ pointerId: e.pointerId,
+ startX: e.clientX,
+ startY: e.clientY,
+ notified: false,
+ };
+ }}
+ onMouseDown={(e) => {
+ if (!suppressNextBoxMouseDownRef.current) return;
+ suppressNextBoxMouseDownRef.current = false;
+ e.preventDefault();
+ e.stopPropagation();
+ }}
+ onClick={handleBoxClick}
+ >
+ {/* Resize handle — bottom-right corner */}
+ {allowCanvasMovement && selection.capabilities.canApplyManualSize && (
+ <div
+ className="absolute -right-1.5 -bottom-1.5 w-3 h-3 rounded-sm bg-studio-accent border border-studio-accent/60"
+ style={{ cursor: "se-resize", touchAction: "none" }}
+ onPointerDown={(e) => {
+ e.stopPropagation();
+ startGesture("resize", e);
+ }}
+ />
+ )}
+ </div>
+ </>
+ )}
+ </div>
+ );
+});
diff --git a/packages/studio/src/components/editor/PropertyPanel.tsx b/packages/studio/src/components/editor/PropertyPanel.tsx
index 1acb2aad08..18ecd8dbe1 100644
--- a/packages/studio/src/components/editor/PropertyPanel.tsx
+++ b/packages/studio/src/components/editor/PropertyPanel.tsx
@@ -1,272 +1,2540 @@
-import { memo } from "react";
-import { X, MousePointer, Move, Type, Palette, Clock, Eye } from "../../icons/SystemIcons";
-import { Button, IconButton } from "../ui";
-import type { PickedElement } from "../../hooks/useElementPicker";
+import {
+ memo,
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useMemo,
+ useRef,
+ useState,
+ type ReactNode,
+} from "react";
+import { createPortal } from "react-dom";
+import {
+ Eye,
+ Layers,
+ MessageSquare,
+ Move,
+ Palette,
+ Plus,
+ RotateCcw,
+ Settings,
+ Type,
+ X,
+} from "../../icons/SystemIcons";
+import {
+ formatCssColor,
+ hsvToRgb,
+ parseCssColor,
+ rgbToHsv,
+ toColorPickerValue,
+ toHexColor,
+ type ParsedColor,
+} from "./colorValue";
+import {
+ buildDefaultGradientModel,
+ insertGradientStop,
+ parseGradient,
+ serializeGradient,
+ type GradientModel,
+} from "./gradientValue";
+import { isTextEditableSelection, type DomEditSelection } from "./domEditing";
+import { readStudioBoxSize, readStudioPathOffset } from "./manualEdits";
+import {
+ COMMON_LOCAL_FONT_FAMILIES,
+ googleFontStylesheetUrl,
+ POPULAR_GOOGLE_FONT_FAMILIES,
+} from "./fontCatalog";
+import { fontFamilyFromAssetPath, importedFontFaceCss, type ImportedFontAsset } from "./fontAssets";
+import { resolveFloatingPanelPosition, type FloatingPosition } from "./floatingPanel";
+import { IMAGE_EXT } from "../../utils/mediaTypes";
interface PropertyPanelProps {
- element: PickedElement | null;
- isPickMode: boolean;
- onEnablePick: () => void;
- onDisablePick: () => void;
- onClearPick: () => void;
+ projectId: string;
+ assets: string[];
+ element: DomEditSelection | null;
+ copiedAgentPrompt: boolean;
+ onClearSelection: () => void;
onSetStyle: (prop: string, value: string) => void;
- onSetDataAttr: (attr: string, value: string) => void;
- onSetText?: (text: string) => void;
+ onSetManualOffset: (element: DomEditSelection, next: { x: number; y: number }) => void;
+ onSetManualSize: (element: DomEditSelection, next: { width: number; height: number }) => void;
+ onSetText: (value: string, fieldKey?: string) => void;
+ onSetTextFieldStyle: (fieldKey: string, property: string, value: string) => void;
+ onAddTextField: (afterFieldKey?: string) => string | Promise<string | null> | null;
+ onRemoveTextField: (fieldKey: string) => void;
+ onResetManualEdits: (element: DomEditSelection) => void;
+ onAskAgent: () => void;
+ onImportAssets?: (files: FileList) => Promise<string[]>;
+ fontAssets?: ImportedFontAsset[];
+ onImportFonts?: (files: FileList | File[]) => Promise<ImportedFontAsset[]>;
}
-function PropertyRow({
+const FIELD =
+ "min-w-0 rounded-xl border border-neutral-800 bg-neutral-900/95 px-3 py-2 text-neutral-100 shadow-[inset_0_1px_0_rgba(255,255,255,0.03)] transition-colors focus-within:border-neutral-600";
+const LABEL = "text-[11px] font-medium uppercase tracking-[0.18em] text-neutral-500";
+const RESPONSIVE_GRID = "grid grid-cols-[repeat(auto-fit,minmax(118px,1fr))] gap-3";
+const EMPTY_STYLES: Record<string, string> = {};
+const GENERIC_FONT_FAMILIES = new Set([
+ "inherit",
+ "initial",
+ "revert",
+ "revert-layer",
+ "serif",
+ "sans-serif",
+ "monospace",
+ "cursive",
+ "fantasy",
+ "system-ui",
+ "ui-sans-serif",
+ "ui-serif",
+ "ui-monospace",
+ "ui-rounded",
+ "emoji",
+ "math",
+ "fangsong",
+]);
+const DEFAULT_FONT_FAMILIES = [
+ ...COMMON_LOCAL_FONT_FAMILIES,
+ "Inter",
+ "system-ui",
+ "sans-serif",
+ "serif",
+ "monospace",
+];
+
+interface LocalFontData {
+ family: string;
+ fullName?: string;
+ postscriptName?: string;
+ style?: string;
+ blob?: () => Promise<Blob>;
+}
+
+type FontSource = "Current" | "Document" | "Imported" | "Local" | "Google" | "System";
+
+interface FontOption {
+ family: string;
+ source: FontSource;
+}
+
+const COLOR_PICKER_SIZE = { width: 292, height: 386 };
+
+function colorFromCss(value: string): ParsedColor {
+ return parseCssColor(value) ?? { red: 0, green: 0, blue: 0, alpha: 1 };
+}
+
+declare global {
+ interface Window {
+ queryLocalFonts?: () => Promise<LocalFontData[]>;
+ }
+}
+
+function sanitizeFontFilePart(value: string): string {
+ return value
+ .replace(/[^\w .-]+/g, " ")
+ .replace(/\s+/g, " ")
+ .trim();
+}
+
+function localFontSortScore(font: LocalFontData): number {
+ const style = font.style?.toLowerCase() ?? "";
+ const fullName = font.fullName?.toLowerCase() ?? "";
+ if (style === "regular" || fullName.endsWith(" regular")) return 0;
+ if (style === "normal" || fullName.endsWith(" normal")) return 1;
+ if (style === "medium" || fullName.endsWith(" medium")) return 2;
+ return 3;
+}
+
+function parseNumericValue(value: string | undefined): number | null {
+ if (!value) return null;
+ const parsed = Number.parseFloat(value);
+ return Number.isFinite(parsed) ? parsed : null;
+}
+
+function formatNumericValue(value: number): string {
+ const rounded = Math.round(value * 100) / 100;
+ return Number.isInteger(rounded)
+ ? `${rounded}`
+ : rounded.toFixed(2).replace(/0+$/, "").replace(/\.$/, "");
+}
+
+interface ParsedNumericToken {
+ value: number;
+ unit: string;
+}
+
+function parseNumericToken(value: string | undefined): ParsedNumericToken | null {
+ if (!value) return null;
+ const match = value.trim().match(/^(-?\d+(?:\.\d+)?)([a-z%]*)$/i);
+ if (!match) return null;
+ const parsed = Number.parseFloat(match[1]);
+ if (!Number.isFinite(parsed)) return null;
+ return {
+ value: parsed,
+ unit: match[2] ?? "",
+ };
+}
+
+function parsePxMetricValue(value: string): number | null {
+ const token = parseNumericToken(value);
+ if (!token) return null;
+ if (token.unit && token.unit.toLowerCase() !== "px") return null;
+ return token.value;
+}
+
+function formatPxMetricValue(value: number): string {
+ return `${formatNumericValue(value)}px`;
+}
+
+function adjustNumericToken(
+ value: string,
+ direction: 1 | -1,
+ modifiers?: { shiftKey?: boolean; altKey?: boolean },
+): string | null {
+ const token = parseNumericToken(value);
+ if (!token) return null;
+
+ const baseStep = modifiers?.altKey ? 0.1 : modifiers?.shiftKey ? 10 : 1;
+ const nextValue = token.value + baseStep * direction;
+ return `${formatNumericValue(nextValue)}${token.unit}`;
+}
+
+function formatColorToken(value: string): string {
+ const parsed = parseCssColor(value);
+ if (!parsed) return value;
+ const hex = toColorPickerValue(value).replace(/^#/, "").toUpperCase();
+ return `${hex} / ${Math.round(parsed.alpha * 100)}%`;
+}
+
+function extractBackgroundImageUrl(value: string | undefined): string {
+ if (!value) return "";
+ const lowerValue = value.toLowerCase();
+ const urlStart = lowerValue.indexOf("url(");
+ if (urlStart < 0) return "";
+
+ let index = urlStart + 4;
+ while (
+ index < value.length &&
+ (value[index] === " " ||
+ value[index] === "\n" ||
+ value[index] === "\r" ||
+ value[index] === "\t" ||
+ value[index] === "\f")
+ ) {
+ index += 1;
+ }
+
+ const quote = value[index] === '"' || value[index] === "'" ? value[index] : null;
+ if (quote) {
+ index += 1;
+ const endQuote = value.indexOf(quote, index);
+ return endQuote >= index ? value.slice(index, endQuote) : "";
+ }
+
+ const endParen = value.indexOf(")", index);
+ if (endParen < index) return "";
+ return value.slice(index, endParen).trim();
+}
+
+function normalizeProjectPath(value: string): string {
+ const trimmed = value.trim();
+ const maybeUrl = /^[a-z]+:\/\//i.test(trimmed) ? new URL(trimmed).pathname : trimmed;
+ return decodeURIComponent(maybeUrl)
+ .replace(/\\/g, "/")
+ .replace(/^\.?\//, "");
+}
+
+function toRelativeProjectAssetPath(sourceFile: string, assetPath: string): string {
+ const fromParts = normalizeProjectPath(sourceFile).split("/").filter(Boolean);
+ const targetParts = normalizeProjectPath(assetPath).split("/").filter(Boolean);
+
+ fromParts.pop();
+
+ while (fromParts.length > 0 && targetParts.length > 0 && fromParts[0] === targetParts[0]) {
+ fromParts.shift();
+ targetParts.shift();
+ }
+
+ return [...fromParts.map(() => ".."), ...targetParts].join("/") || assetPath;
+}
+
+function toProjectRootAssetPath(assetPath: string): string {
+ return normalizeProjectPath(assetPath);
+}
+
+function resolveSelectedAsset(
+ imageUrl: string,
+ sourceFile: string,
+ assets: string[],
+): string | null {
+ const normalizedUrl = normalizeProjectPath(imageUrl);
+ if (!normalizedUrl) return null;
+
+ for (const asset of assets) {
+ const normalizedAsset = normalizeProjectPath(asset);
+ const relativeAsset = toRelativeProjectAssetPath(sourceFile, asset);
+ if (
+ normalizedUrl === normalizedAsset ||
+ normalizedUrl === relativeAsset ||
+ normalizedUrl.endsWith(`/${normalizedAsset}`) ||
+ normalizedUrl.endsWith(`/${relativeAsset}`)
+ ) {
+ return asset;
+ }
+ }
+
+ return null;
+}
+
+function collectSelectionColors(styles: Record<string, string>) {
+ const candidates = [
+ { source: "Fill", value: styles["background-color"] },
+ { source: "Text", value: styles.color },
+ ];
+
+ const deduped = new Map<string, { swatch: string; token: string; sources: string[] }>();
+
+ for (const candidate of candidates) {
+ if (!candidate.value) continue;
+ const parsed = parseCssColor(candidate.value);
+ if (!parsed || parsed.alpha <= 0) continue;
+
+ const key = `${toColorPickerValue(candidate.value)}-${Math.round(parsed.alpha * 100)}`;
+ const existing = deduped.get(key);
+ if (existing) {
+ existing.sources.push(candidate.source);
+ continue;
+ }
+
+ deduped.set(key, {
+ swatch: toColorPickerValue(candidate.value),
+ token: formatColorToken(candidate.value),
+ sources: [candidate.source],
+ });
+ }
+
+ return Array.from(deduped.values());
+}
+
+function CommitField({
+ value,
+ disabled,
+ liveCommit,
+ onCommit,
+}: {
+ value: string;
+ disabled?: boolean;
+ liveCommit?: boolean;
+ onCommit: (nextValue: string) => void;
+}) {
+ const [draft, setDraft] = useState(value);
+ const commitTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const valueRef = useRef(value);
+
+ valueRef.current = value;
+
+ useEffect(() => {
+ setDraft(value);
+ }, [value]);
+
+ useEffect(
+ () => () => {
+ if (commitTimerRef.current) clearTimeout(commitTimerRef.current);
+ },
+ [],
+ );
+
+ const commitDraft = (nextDraft: string) => {
+ if (commitTimerRef.current) clearTimeout(commitTimerRef.current);
+ if (nextDraft !== valueRef.current) {
+ onCommit(nextDraft);
+ }
+ };
+
+ const scheduleCommit = (nextDraft: string) => {
+ if (commitTimerRef.current) clearTimeout(commitTimerRef.current);
+ commitTimerRef.current = setTimeout(() => {
+ if (nextDraft !== valueRef.current) {
+ onCommit(nextDraft);
+ }
+ }, 120);
+ };
+
+ return (
+ <input
+ type="text"
+ value={draft}
+ disabled={disabled}
+ onChange={(e) => {
+ setDraft(e.target.value);
+ if (liveCommit) scheduleCommit(e.target.value);
+ }}
+ onBlur={() => commitDraft(draft)}
+ onWheel={(e) => {
+ if (disabled) return;
+ const delta = e.deltaY === 0 ? e.deltaX : e.deltaY;
+ if (delta === 0) return;
+ const nextDraft = adjustNumericToken(draft, delta < 0 ? 1 : -1, e);
+ if (!nextDraft) return;
+ e.preventDefault();
+ setDraft(nextDraft);
+ scheduleCommit(nextDraft);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ (e.target as HTMLInputElement).blur();
+ return;
+ }
+ if (e.key !== "ArrowUp" && e.key !== "ArrowDown") return;
+ const nextDraft = adjustNumericToken(draft, e.key === "ArrowUp" ? 1 : -1, e);
+ if (!nextDraft) return;
+ e.preventDefault();
+ setDraft(nextDraft);
+ scheduleCommit(nextDraft);
+ }}
+ title={parseNumericToken(value) ? "Scroll or use Arrow keys to adjust" : undefined}
+ className="min-w-0 w-full bg-transparent text-[11px] font-medium text-neutral-100 outline-none disabled:cursor-not-allowed disabled:text-neutral-600"
+ />
+ );
+}
+
+function MetricField({
label,
value,
- onChange,
+ disabled,
+ liveCommit,
+ onCommit,
+}: {
+ label: string;
+ value: string;
+ disabled?: boolean;
+ liveCommit?: boolean;
+ onCommit: (nextValue: string) => void;
+}) {
+ return (
+ <div className={FIELD}>
+ <div className="flex min-w-0 items-center gap-3">
+ <span className="flex-shrink-0 text-[11px] font-medium text-neutral-500">{label}</span>
+ <CommitField
+ value={value}
+ disabled={disabled}
+ liveCommit={liveCommit}
+ onCommit={onCommit}
+ />
+ </div>
+ </div>
+ );
+}
+
+function DetailField({
+ label,
+ value,
+ disabled,
+ onCommit,
+}: {
+ label: string;
+ value: string;
+ disabled?: boolean;
+ onCommit: (nextValue: string) => void;
+}) {
+ return (
+ <label className="grid min-w-0 gap-1.5">
+ <span className={LABEL}>{label}</span>
+ <div className={FIELD}>
+ <CommitField value={value} disabled={disabled} onCommit={onCommit} />
+ </div>
+ </label>
+ );
+}
+
+function TextAreaField({
+ label,
+ value,
+ disabled,
+ autoFocus,
+ onCommit,
+}: {
+ label: string;
+ value: string;
+ disabled?: boolean;
+ autoFocus?: boolean;
+ onCommit: (nextValue: string) => void;
+}) {
+ const [draft, setDraft] = useState(value);
+ const textareaRef = useRef<HTMLTextAreaElement | null>(null);
+ const commitTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const focusedRef = useRef(false);
+ const valueRef = useRef(value);
+
+ valueRef.current = value;
+
+ useEffect(() => {
+ if (focusedRef.current) return;
+ setDraft(value);
+ }, [value]);
+
+ useEffect(
+ () => () => {
+ if (commitTimerRef.current) clearTimeout(commitTimerRef.current);
+ },
+ [],
+ );
+
+ useEffect(() => {
+ if (!autoFocus) return;
+ textareaRef.current?.focus();
+ }, [autoFocus]);
+
+ const commitDraft = (nextDraft: string) => {
+ if (commitTimerRef.current) clearTimeout(commitTimerRef.current);
+ if (nextDraft !== valueRef.current) {
+ onCommit(nextDraft);
+ }
+ };
+
+ const scheduleCommit = (nextDraft: string) => {
+ if (commitTimerRef.current) clearTimeout(commitTimerRef.current);
+ commitTimerRef.current = setTimeout(() => {
+ if (nextDraft !== valueRef.current) {
+ onCommit(nextDraft);
+ }
+ }, 120);
+ };
+
+ return (
+ <label className="grid min-w-0 gap-1.5">
+ <span className={LABEL}>{label}</span>
+ <div className={FIELD}>
+ <textarea
+ ref={textareaRef}
+ value={draft}
+ disabled={disabled}
+ rows={4}
+ onFocus={() => {
+ focusedRef.current = true;
+ }}
+ onChange={(e) => {
+ setDraft(e.target.value);
+ scheduleCommit(e.target.value);
+ }}
+ onBlur={() => {
+ focusedRef.current = false;
+ commitDraft(draft);
+ }}
+ className="w-full resize-none bg-transparent text-[11px] font-medium text-neutral-100 outline-none disabled:cursor-not-allowed disabled:text-neutral-600"
+ />
+ </div>
+ </label>
+ );
+}
+
+function formatTextFieldPreview(value: string): string {
+ const collapsed = value.trim().replace(/\s+/g, " ");
+ if (collapsed.length <= 56) return collapsed;
+ return `${collapsed.slice(0, 55)}…`;
+}
+
+function getTextFieldColor(
+ field: { computedStyles: Record<string, string> },
+ inheritedStyles: Record<string, string>,
+): string {
+ return field.computedStyles.color || inheritedStyles.color || "rgb(0, 0, 0)";
+}
+
+function splitFontFamilies(value: string): string[] {
+ const families: string[] = [];
+ let current = "";
+ let quote: '"' | "'" | null = null;
+
+ for (const char of value) {
+ if ((char === '"' || char === "'") && !quote) {
+ quote = char;
+ continue;
+ }
+ if (char === quote) {
+ quote = null;
+ continue;
+ }
+ if (char === "," && !quote) {
+ if (current.trim()) families.push(current.trim());
+ current = "";
+ continue;
+ }
+ current += char;
+ }
+
+ if (current.trim()) families.push(current.trim());
+ return families.map((family) => family.replace(/^["']|["']$/g, "").trim()).filter(Boolean);
+}
+
+function primaryFontFamily(value: string): string {
+ return splitFontFamilies(value)[0] ?? "inherit";
+}
+
+function quoteFontFamily(family: string): string {
+ const trimmed = family.trim();
+ if (GENERIC_FONT_FAMILIES.has(trimmed.toLowerCase())) return trimmed;
+ return `"${trimmed.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
+}
+
+function buildFontFamilyValue(family: string): string {
+ const trimmed = family.trim();
+ if (!trimmed) return "inherit";
+ if (GENERIC_FONT_FAMILIES.has(trimmed.toLowerCase())) return trimmed;
+ return `${quoteFontFamily(trimmed)}, ui-sans-serif, system-ui, sans-serif`;
+}
+
+function collectDocumentFontFamilies(): string[] {
+ if (typeof document === "undefined") return [];
+ const fontSet = document.fonts;
+ if (!fontSet) return [];
+ return Array.from(fontSet, (fontFace) => fontFace.family.replace(/^["']|["']$/g, "").trim())
+ .filter(Boolean)
+ .sort((a, b) => a.localeCompare(b));
+}
+
+function uniqueFontFamilies(values: string[]): string[] {
+ const seen = new Set<string>();
+ const result: string[] = [];
+ for (const value of values) {
+ const family = value.trim();
+ if (!family) continue;
+ const key = family.toLowerCase();
+ if (seen.has(key)) continue;
+ seen.add(key);
+ result.push(family);
+ }
+ return result;
+}
+
+function uniqueFontOptions(values: FontOption[]): FontOption[] {
+ const seen = new Set<string>();
+ const result: FontOption[] = [];
+ for (const value of values) {
+ const family = value.family.trim();
+ if (!family) continue;
+ const key = family.toLowerCase();
+ if (seen.has(key)) continue;
+ seen.add(key);
+ result.push({ family, source: value.source });
+ }
+ return result;
+}
+
+function fontSourceRank(source: FontSource): number {
+ if (source === "Current") return 0;
+ if (source === "Document") return 1;
+ if (source === "Imported") return 2;
+ if (source === "Local") return 3;
+ if (source === "Google") return 4;
+ return 5;
+}
+
+function sortFontOptions(options: FontOption[]): FontOption[] {
+ return [...options].sort((a, b) => {
+ const rankDelta = fontSourceRank(a.source) - fontSourceRank(b.source);
+ if (rankDelta !== 0) return rankDelta;
+
+ const commonA = COMMON_LOCAL_FONT_FAMILIES.findIndex(
+ (family) => family.toLowerCase() === a.family.toLowerCase(),
+ );
+ const commonB = COMMON_LOCAL_FONT_FAMILIES.findIndex(
+ (family) => family.toLowerCase() === b.family.toLowerCase(),
+ );
+ const commonDelta =
+ (commonA === -1 ? Number.MAX_SAFE_INTEGER : commonA) -
+ (commonB === -1 ? Number.MAX_SAFE_INTEGER : commonB);
+
+ return commonDelta === 0 ? a.family.localeCompare(b.family) : commonDelta;
+ });
+}
+
+function fontSearchKey(value: string): string {
+ return value.toLowerCase().replace(/[^a-z0-9]+/g, "");
+}
+
+function fontMatchesQuery(family: string, query: string): boolean {
+ const normalizedQuery = query.trim().toLowerCase();
+ if (!normalizedQuery) return true;
+ const normalizedFamily = family.toLowerCase();
+ if (normalizedFamily.includes(normalizedQuery)) return true;
+ return fontSearchKey(family).includes(fontSearchKey(normalizedQuery));
+}
+
+function loadGoogleFontStylesheet(family: string): void {
+ if (typeof document === "undefined") return;
+ const trimmed = family.trim();
+ if (!trimmed) return;
+
+ const id = `studio-google-font-${trimmed.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`;
+ if (document.getElementById(id)) return;
+
+ const preconnect = document.querySelector('link[data-studio-google-font-preconnect="true"]');
+ if (!preconnect) {
+ const preconnectEl = document.createElement("link");
+ preconnectEl.setAttribute("data-studio-google-font-preconnect", "true");
+ preconnectEl.rel = "preconnect";
+ preconnectEl.href = "https://fonts.gstatic.com";
+ preconnectEl.crossOrigin = "anonymous";
+ document.head.appendChild(preconnectEl);
+ }
+
+ const link = document.createElement("link");
+ link.id = id;
+ link.rel = "stylesheet";
+ link.href = googleFontStylesheetUrl(trimmed);
+ document.head.appendChild(link);
+}
+
+function loadImportedFontStylesheet(asset: ImportedFontAsset): void {
+ if (typeof document === "undefined") return;
+ const id = `studio-imported-font-${asset.family.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`;
+ if (document.getElementById(id)) return;
+
+ const style = document.createElement("style");
+ style.id = id;
+ style.textContent = importedFontFaceCss(asset);
+ document.head.appendChild(style);
+}
+
+function FontWeightField({
+ value,
+ disabled,
+ onCommit,
+}: {
+ value: string;
+ disabled?: boolean;
+ onCommit: (nextValue: string) => void;
+}) {
+ const options = ["300", "400", "500", "600", "700", "800"];
+ return (
+ <div className={FIELD}>
+ <div className="flex min-w-0 items-center gap-3">
+ <span className="flex-shrink-0 text-[11px] font-medium text-neutral-500">Weight</span>
+ <select
+ value={value}
+ disabled={disabled}
+ onChange={(e) => onCommit(e.target.value)}
+ className="min-w-0 w-full appearance-none bg-transparent text-[11px] font-medium text-neutral-100 outline-none disabled:cursor-not-allowed disabled:text-neutral-600"
+ >
+ {options.map((option) => (
+ <option key={option} value={option}>
+ {option}
+ </option>
+ ))}
+ </select>
+ </div>
+ </div>
+ );
+}
+
+function FontFamilyField({
+ value,
+ disabled,
+ importedFonts,
+ onImportFonts,
+ onCommit,
+}: {
+ value: string;
+ disabled?: boolean;
+ importedFonts: ImportedFontAsset[];
+ onImportFonts?: (files: FileList | File[]) => Promise<ImportedFontAsset[]>;
+ onCommit: (nextValue: string) => void;
+}) {
+ const currentFamily = primaryFontFamily(value);
+ const containerRef = useRef<HTMLDivElement | null>(null);
+ const inputRef = useRef<HTMLInputElement | null>(null);
+ const fontInputRef = useRef<HTMLInputElement | null>(null);
+ const [open, setOpen] = useState(false);
+ const [query, setQuery] = useState("");
+ const [localFonts, setLocalFonts] = useState<string[]>([]);
+ const [localFontData, setLocalFontData] = useState<LocalFontData[]>([]);
+ const [googleFonts, setGoogleFonts] = useState<string[]>(() => [...POPULAR_GOOGLE_FONT_FAMILIES]);
+ const [loadingLocalFonts, setLoadingLocalFonts] = useState(false);
+ const [loadingGoogleFonts, setLoadingGoogleFonts] = useState(false);
+ const [importingFonts, setImportingFonts] = useState(false);
+ const [fontNotice, setFontNotice] = useState<string | null>(null);
+ const canQueryLocalFonts =
+ typeof window !== "undefined" && typeof window.queryLocalFonts === "function";
+
+ useEffect(() => {
+ if (!open) return;
+ const handlePointerDown = (event: PointerEvent) => {
+ const target = event.target;
+ if (!(target instanceof Node)) return;
+ if (!containerRef.current?.contains(target)) setOpen(false);
+ };
+ document.addEventListener("pointerdown", handlePointerDown);
+ return () => {
+ document.removeEventListener("pointerdown", handlePointerDown);
+ };
+ }, [open]);
+
+ useEffect(() => {
+ if (!open) return;
+ requestAnimationFrame(() => inputRef.current?.focus());
+ }, [open]);
+
+ useEffect(() => {
+ let cancelled = false;
+ void fetch("/api/fonts")
+ .then((response) => (response.ok ? response.json() : null))
+ .then((data: { fonts?: string[] } | null) => {
+ const fonts = data?.fonts;
+ if (cancelled || !Array.isArray(fonts)) return;
+ setLocalFonts((current) => uniqueFontFamilies([...current, ...fonts]));
+ })
+ .catch(() => undefined);
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ useEffect(() => {
+ let cancelled = false;
+ setLoadingGoogleFonts(true);
+ void fetch("/api/fonts/google")
+ .then((response) => (response.ok ? response.json() : null))
+ .then((data: { fonts?: string[] } | null) => {
+ const fonts = data?.fonts;
+ if (cancelled || !Array.isArray(fonts)) return;
+ setGoogleFonts(uniqueFontFamilies([...fonts, ...POPULAR_GOOGLE_FONT_FAMILIES]));
+ })
+ .catch(() => undefined)
+ .finally(() => {
+ if (!cancelled) setLoadingGoogleFonts(false);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ useEffect(() => {
+ if (googleFonts.some((family) => family.toLowerCase() === currentFamily.toLowerCase())) {
+ loadGoogleFontStylesheet(currentFamily);
+ }
+ const imported = importedFonts.find(
+ (font) => font.family.toLowerCase() === currentFamily.toLowerCase(),
+ );
+ if (imported) loadImportedFontStylesheet(imported);
+ }, [currentFamily, googleFonts, importedFonts]);
+
+ const loadBrowserLocalFonts = async () => {
+ if (!canQueryLocalFonts || !window.queryLocalFonts) {
+ setFontNotice("This browser does not expose installed fonts. Import a font file instead.");
+ return;
+ }
+ setLoadingLocalFonts(true);
+ setFontNotice(null);
+ try {
+ const fonts = await window.queryLocalFonts();
+ const sortedFonts = [...fonts].sort((a, b) => localFontSortScore(a) - localFontSortScore(b));
+ const families = sortedFonts
+ .map((font) => font.family)
+ .filter((name): name is string => Boolean(name))
+ .map((name) => fontFamilyFromAssetPath(`${name}.ttf`));
+ setLocalFontData(sortedFonts);
+ setLocalFonts((current) => uniqueFontFamilies([...current, ...families]));
+ setFontNotice(fonts.length === 0 ? "No browser-local fonts were returned." : null);
+ } catch (error) {
+ const name = error instanceof Error ? error.name : "";
+ setFontNotice(
+ name === "NotAllowedError"
+ ? "Local font access was denied. Import a font file instead."
+ : "Local font access is unavailable. Import a font file instead.",
+ );
+ } finally {
+ setLoadingLocalFonts(false);
+ }
+ };
+
+ const handleImportFonts = async (files: FileList | File[] | null) => {
+ if (!files?.length || !onImportFonts) return;
+ setImportingFonts(true);
+ setFontNotice(null);
+ try {
+ const imported = await onImportFonts(files);
+ for (const font of imported) loadImportedFontStylesheet(font);
+ const first = imported[0];
+ if (first) {
+ onCommit(buildFontFamilyValue(first.family));
+ setQuery("");
+ setOpen(false);
+ } else {
+ setFontNotice("No supported font files were imported.");
+ }
+ } finally {
+ setImportingFonts(false);
+ }
+ };
+
+ const projectFontAssets = useMemo(
+ () =>
+ uniqueFontOptions(
+ importedFonts.map((font): FontOption => ({ family: font.family, source: "Imported" })),
+ ),
+ [importedFonts],
+ );
+
+ const options = useMemo(() => {
+ const documentFonts = collectDocumentFontFamilies();
+ return sortFontOptions(
+ uniqueFontOptions([
+ { family: currentFamily, source: "Current" },
+ ...documentFonts.map((family): FontOption => ({ family, source: "Document" })),
+ ...projectFontAssets,
+ ...localFonts.map((family): FontOption => ({ family, source: "Local" })),
+ ...googleFonts.map((family): FontOption => ({ family, source: "Google" })),
+ ...DEFAULT_FONT_FAMILIES.map((family): FontOption => ({ family, source: "System" })),
+ ]),
+ );
+ }, [currentFamily, googleFonts, localFonts, projectFontAssets]);
+
+ const filteredOptions = useMemo(() => {
+ const matches = options.filter((option) => fontMatchesQuery(option.family, query));
+ return matches.slice(0, query.trim() ? 120 : 160);
+ }, [options, query]);
+
+ const importLocalFont = async (family: string): Promise<ImportedFontAsset | null> => {
+ if (!onImportFonts) return null;
+ const candidates = localFontData
+ .filter((font) => fontFamilyFromAssetPath(`${font.family}.ttf`) === family)
+ .sort((a, b) => localFontSortScore(a) - localFontSortScore(b));
+ const font = candidates.find((entry) => typeof entry.blob === "function");
+ if (!font?.blob) return null;
+
+ const blob = await font.blob();
+ const style = sanitizeFontFilePart(font.style ?? "Regular") || "Regular";
+ const name = sanitizeFontFilePart(`${family} ${style}`) || family;
+ const file = new File([blob], `${name}.ttf`, {
+ type: blob.type || "font/ttf",
+ });
+ const imported = await onImportFonts([file]);
+ return (
+ imported.find((asset) => asset.family.toLowerCase() === family.toLowerCase()) ??
+ imported[0] ??
+ null
+ );
+ };
+
+ const commitFamily = async (option: FontOption) => {
+ if (option.source === "Local") {
+ setImportingFonts(true);
+ setFontNotice(null);
+ try {
+ const imported = await importLocalFont(option.family);
+ if (imported) {
+ loadImportedFontStylesheet(imported);
+ onCommit(buildFontFamilyValue(imported.family));
+ setQuery("");
+ setOpen(false);
+ return;
+ }
+ onCommit(buildFontFamilyValue(option.family));
+ setQuery("");
+ setOpen(false);
+ } finally {
+ setImportingFonts(false);
+ }
+ return;
+ }
+
+ if (option.source === "Google") {
+ loadGoogleFontStylesheet(option.family);
+ }
+ const imported = importedFonts.find(
+ (font) => font.family.toLowerCase() === option.family.toLowerCase(),
+ );
+ if (imported) loadImportedFontStylesheet(imported);
+ onCommit(buildFontFamilyValue(option.family));
+ setQuery("");
+ setOpen(false);
+ };
+
+ return (
+ <div ref={containerRef} className="relative grid min-w-0 gap-1.5">
+ <span className={LABEL}>Font family</span>
+ <button
+ type="button"
+ disabled={disabled}
+ onClick={() => setOpen((next) => !next)}
+ className={`${FIELD} flex h-10 items-center justify-between gap-3 text-left hover:border-neutral-700 disabled:cursor-not-allowed`}
+ >
+ <span
+ className="min-w-0 flex-1 truncate text-[11px] font-medium text-neutral-100"
+ style={{ fontFamily: value }}
+ >
+ {currentFamily}
+ </span>
+ <span className="flex-shrink-0 text-[10px] uppercase tracking-[0.14em] text-neutral-600">
+ Font
+ </span>
+ </button>
+
+ {open && (
+ <div className="absolute left-0 right-0 top-[calc(100%+6px)] z-50 overflow-hidden rounded-xl border border-neutral-700 bg-neutral-950 shadow-2xl">
+ <div className="grid grid-cols-[minmax(0,1fr)_auto_auto] gap-2 border-b border-neutral-800 p-2">
+ <input
+ ref={inputRef}
+ type="text"
+ value={query}
+ disabled={disabled}
+ placeholder={loadingGoogleFonts ? "Loading Google Fonts..." : "Search fonts"}
+ onChange={(e) => setQuery(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Escape") {
+ e.preventDefault();
+ setOpen(false);
+ }
+ if (e.key === "Enter" && filteredOptions[0]) {
+ e.preventDefault();
+ commitFamily(filteredOptions[0]);
+ }
+ }}
+ className="min-w-0 rounded-lg border border-neutral-800 bg-neutral-900 px-2.5 py-2 text-[11px] font-medium text-neutral-100 outline-none placeholder:text-neutral-600 focus:border-neutral-600"
+ />
+ {canQueryLocalFonts && (
+ <button
+ type="button"
+ disabled={disabled || loadingLocalFonts}
+ onClick={loadBrowserLocalFonts}
+ className="rounded-lg border border-neutral-700 bg-neutral-900 px-2.5 text-[10px] font-medium text-neutral-400 transition-colors hover:border-neutral-600 hover:text-neutral-100 disabled:cursor-not-allowed disabled:text-neutral-700"
+ >
+ {loadingLocalFonts ? "..." : "Local"}
+ </button>
+ )}
+ <button
+ type="button"
+ disabled={disabled || importingFonts || !onImportFonts}
+ onClick={() => fontInputRef.current?.click()}
+ className="rounded-lg border border-neutral-700 bg-neutral-900 px-2.5 text-[10px] font-medium text-neutral-400 transition-colors hover:border-neutral-600 hover:text-neutral-100 disabled:cursor-not-allowed disabled:text-neutral-700"
+ >
+ {importingFonts ? "..." : "Import"}
+ </button>
+ <input
+ ref={fontInputRef}
+ type="file"
+ accept=".ttf,.otf,.ttc,.woff,.woff2,.eot,font/*"
+ multiple
+ aria-label="Import local font files"
+ disabled={disabled || importingFonts || !onImportFonts}
+ className="hidden"
+ onChange={async (event) => {
+ await handleImportFonts(event.target.files);
+ event.target.value = "";
+ }}
+ />
+ </div>
+ {fontNotice && (
+ <div className="border-b border-neutral-800 px-3 py-2 text-[10px] leading-4 text-neutral-500">
+ {fontNotice}
+ </div>
+ )}
+ <div className="max-h-64 overflow-y-auto p-1">
+ {filteredOptions.length === 0 ? (
+ <div className="px-2 py-3 text-[11px] text-neutral-500">No fonts found.</div>
+ ) : (
+ filteredOptions.map((option) => (
+ <button
+ key={`${option.source}-${option.family}`}
+ type="button"
+ onClick={() => commitFamily(option)}
+ className={`flex w-full min-w-0 items-center justify-between gap-3 rounded-lg px-2 py-2 text-left text-[11px] transition-colors ${
+ option.family === currentFamily
+ ? "bg-studio-accent/15 text-neutral-50"
+ : "text-neutral-300 hover:bg-neutral-900 hover:text-neutral-100"
+ }`}
+ >
+ <span className="min-w-0 truncate font-medium">{option.family}</span>
+ <span className="flex-shrink-0 text-[9px] uppercase tracking-[0.14em] text-neutral-600">
+ {option.source}
+ </span>
+ </button>
+ ))
+ )}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
+
+function ColorField({
+ label,
+ value,
+ disabled,
+ onCommit,
}: {
label: string;
value: string;
- onChange: (v: string) => void;
+ disabled?: boolean;
+ onCommit: (nextValue: string) => void;
+}) {
+ const buttonRef = useRef<HTMLButtonElement | null>(null);
+ const panelRef = useRef<HTMLDivElement | null>(null);
+ const [open, setOpen] = useState(false);
+ const [panelPosition, setPanelPosition] = useState<FloatingPosition | null>(null);
+ const [draftColor, setDraftColor] = useState<ParsedColor>(() => colorFromCss(value));
+ const [hexDraft, setHexDraft] = useState(() => toHexColor(colorFromCss(value)).toUpperCase());
+ const hsv = rgbToHsv(draftColor);
+ const hueColor = formatCssColor({
+ ...hsvToRgb({ hue: hsv.hue, saturation: 1, value: 1 }),
+ alpha: 1,
+ });
+ const opaqueColor = formatCssColor({ ...draftColor, alpha: 1 });
+ const currentColor = formatCssColor(draftColor);
+ const saturationPercent = Math.round(hsv.saturation * 100);
+ const brightnessPercent = Math.round(hsv.value * 100);
+ const alphaPercent = Math.round(draftColor.alpha * 100);
+
+ useEffect(() => {
+ const nextColor = colorFromCss(value);
+ setDraftColor(nextColor);
+ setHexDraft(toHexColor(nextColor).toUpperCase());
+ }, [value]);
+
+ const updatePanelPosition = useCallback(() => {
+ const anchor = buttonRef.current?.getBoundingClientRect();
+ if (!anchor) return;
+ const measured = panelRef.current?.getBoundingClientRect();
+ setPanelPosition(
+ resolveFloatingPanelPosition(
+ anchor,
+ { width: window.innerWidth, height: window.innerHeight },
+ {
+ width: measured?.width || COLOR_PICKER_SIZE.width,
+ height: measured?.height || COLOR_PICKER_SIZE.height,
+ },
+ ),
+ );
+ }, []);
+
+ useLayoutEffect(() => {
+ if (!open) return;
+ updatePanelPosition();
+
+ const handlePositionInvalidated = () => updatePanelPosition();
+ window.addEventListener("resize", handlePositionInvalidated);
+ window.addEventListener("scroll", handlePositionInvalidated, true);
+ return () => {
+ window.removeEventListener("resize", handlePositionInvalidated);
+ window.removeEventListener("scroll", handlePositionInvalidated, true);
+ };
+ }, [open, updatePanelPosition]);
+
+ useEffect(() => {
+ if (!open) return;
+
+ const handlePointerDown = (event: PointerEvent) => {
+ const target = event.target as Node | null;
+ if (!target) return;
+ if (panelRef.current?.contains(target) || buttonRef.current?.contains(target)) return;
+ setOpen(false);
+ };
+ const handleKeyDown = (event: KeyboardEvent) => {
+ if (event.key === "Escape") setOpen(false);
+ };
+
+ document.addEventListener("pointerdown", handlePointerDown);
+ document.addEventListener("keydown", handleKeyDown);
+ return () => {
+ document.removeEventListener("pointerdown", handlePointerDown);
+ document.removeEventListener("keydown", handleKeyDown);
+ };
+ }, [open]);
+
+ const commitColor = (nextColor: ParsedColor) => {
+ setDraftColor(nextColor);
+ setHexDraft(toHexColor(nextColor).toUpperCase());
+ onCommit(formatCssColor(nextColor));
+ };
+
+ const commitHsv = (nextHsv: { hue?: number; saturation?: number; value?: number }) => {
+ const rgb = hsvToRgb({
+ hue: nextHsv.hue ?? hsv.hue,
+ saturation: nextHsv.saturation ?? hsv.saturation,
+ value: nextHsv.value ?? hsv.value,
+ });
+ commitColor({ ...rgb, alpha: draftColor.alpha });
+ };
+
+ const updateSaturationValue = (clientX: number, clientY: number, target: HTMLDivElement) => {
+ const rect = target.getBoundingClientRect();
+ const saturation = Math.max(0, Math.min(1, (clientX - rect.left) / rect.width));
+ const nextValue = Math.max(0, Math.min(1, 1 - (clientY - rect.top) / rect.height));
+ commitHsv({ saturation, value: nextValue });
+ };
+
+ const handleHexCommit = (nextHex: string) => {
+ setHexDraft(nextHex);
+ const normalized = nextHex.trim().startsWith("#") ? nextHex.trim() : `#${nextHex.trim()}`;
+ const parsed = parseCssColor(normalized);
+ if (!parsed) return;
+ commitColor({ ...parsed, alpha: draftColor.alpha });
+ };
+
+ const picker = open
+ ? createPortal(
+ <div
+ ref={panelRef}
+ className="fixed z-[9999] w-[292px] overflow-hidden rounded-2xl border border-neutral-700 bg-neutral-950 shadow-2xl shadow-black/50"
+ style={{
+ left: panelPosition?.left ?? -9999,
+ top: panelPosition?.top ?? -9999,
+ }}
+ >
+ <div className="flex items-center justify-between border-b border-neutral-800 px-3 py-2">
+ <div className="min-w-0">
+ <div className="truncate text-[11px] font-medium text-neutral-100">{label}</div>
+ <div className="text-[9px] uppercase tracking-[0.16em] text-neutral-600">Color</div>
+ </div>
+ <button
+ type="button"
+ onClick={() => setOpen(false)}
+ className="flex h-7 w-7 items-center justify-center rounded-lg text-neutral-500 transition-colors hover:bg-neutral-900 hover:text-neutral-200"
+ aria-label="Close color picker"
+ >
+ <X size={13} />
+ </button>
+ </div>
+ <div className="space-y-3 p-3">
+ <div
+ className="relative h-36 cursor-crosshair overflow-hidden rounded-xl border border-neutral-700 shadow-[inset_0_0_0_1px_rgba(255,255,255,0.06)]"
+ style={{
+ backgroundColor: hueColor,
+ }}
+ onPointerDown={(event) => {
+ event.currentTarget.setPointerCapture(event.pointerId);
+ updateSaturationValue(event.clientX, event.clientY, event.currentTarget);
+ }}
+ onPointerMove={(event) => {
+ if (event.buttons !== 1) return;
+ updateSaturationValue(event.clientX, event.clientY, event.currentTarget);
+ }}
+ >
+ <div className="absolute inset-0 bg-gradient-to-r from-white to-transparent" />
+ <div className="absolute inset-0 bg-gradient-to-t from-black to-transparent" />
+ <div
+ className="pointer-events-none absolute top-0 h-full w-px -translate-x-1/2 bg-white/70 shadow-[0_0_0_1px_rgba(0,0,0,0.45)] mix-blend-difference"
+ style={{ left: `${hsv.saturation * 100}%` }}
+ />
+ <div
+ className="pointer-events-none absolute left-0 h-px w-full -translate-y-1/2 bg-white/70 shadow-[0_0_0_1px_rgba(0,0,0,0.45)] mix-blend-difference"
+ style={{ top: `${(1 - hsv.value) * 100}%` }}
+ />
+ <div
+ className="pointer-events-none absolute h-6 w-6 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white shadow-[0_0_0_1px_rgba(0,0,0,0.85),0_8px_18px_rgba(0,0,0,0.45)]"
+ style={{
+ left: `${hsv.saturation * 100}%`,
+ top: `${(1 - hsv.value) * 100}%`,
+ backgroundColor: opaqueColor,
+ }}
+ />
+ </div>
+
+ <div className="flex min-w-0 items-center gap-3">
+ <div
+ className="h-9 w-9 flex-shrink-0 rounded-xl border border-neutral-600 shadow-[inset_0_1px_0_rgba(255,255,255,0.08)]"
+ style={{ backgroundColor: currentColor }}
+ />
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-[11px] font-medium text-neutral-100">
+ {currentColor}
+ </div>
+ <div className="mt-0.5 text-[9px] uppercase tracking-[0.12em] text-neutral-600">
+ S {saturationPercent}% · B {brightnessPercent}% · A {alphaPercent}%
+ </div>
+ </div>
+ </div>
+
+ <ColorSlider
+ label="Hue"
+ value={hsv.hue}
+ min={0}
+ max={360}
+ step={1}
+ displayValue={`${Math.round(hsv.hue)}°`}
+ background="linear-gradient(90deg, #f00, #ff0, #0f0, #0ff, #00f, #f0f, #f00)"
+ thumbColor={hueColor}
+ disabled={disabled}
+ onCommit={(nextHue) => commitHsv({ hue: nextHue })}
+ />
+
+ <ColorSlider
+ label="Alpha"
+ value={draftColor.alpha}
+ min={0}
+ max={1}
+ step={0.01}
+ displayValue={`${alphaPercent}%`}
+ background={`linear-gradient(90deg, transparent, ${opaqueColor})`}
+ thumbColor={currentColor}
+ disabled={disabled}
+ onCommit={(nextAlpha) => commitColor({ ...draftColor, alpha: nextAlpha })}
+ />
+
+ <label className="grid gap-1.5">
+ <span className={LABEL}>Hex</span>
+ <input
+ value={hexDraft}
+ onChange={(event) => handleHexCommit(event.target.value)}
+ className={`${FIELD} h-10 w-full text-[11px] font-medium outline-none`}
+ spellCheck={false}
+ />
+ </label>
+ </div>
+ </div>,
+ document.body,
+ )
+ : null;
+
+ const openPicker = () => {
+ if (disabled) return;
+ setOpen((current) => !current);
+ if (!open) {
+ requestAnimationFrame(updatePanelPosition);
+ }
+ };
+
+ return (
+ <div className="grid min-w-0 gap-1.5">
+ <span className={LABEL}>{label}</span>
+ <button
+ type="button"
+ disabled={disabled}
+ aria-label={`Pick ${label.toLowerCase()} color`}
+ ref={buttonRef}
+ onClick={openPicker}
+ className={`${FIELD} flex items-center gap-3 text-left hover:border-neutral-700 disabled:cursor-not-allowed ${open ? "border-neutral-600" : ""}`}
+ >
+ <div
+ className="relative h-7 w-7 flex-shrink-0 overflow-hidden rounded-lg border border-neutral-700 bg-neutral-950 shadow-[inset_0_1px_0_rgba(255,255,255,0.04)]"
+ style={{ backgroundColor: value || "transparent" }}
+ />
+ <span className="min-w-0 flex-1 truncate text-[11px] font-medium text-neutral-100">
+ {value}
+ </span>
+ </button>
+ {picker}
+ </div>
+ );
+}
+
+function ColorSlider({
+ label,
+ value,
+ min,
+ max,
+ step,
+ displayValue,
+ background,
+ thumbColor,
+ disabled,
+ onCommit,
+}: {
+ label: string;
+ value: number;
+ min: number;
+ max: number;
+ step: number;
+ displayValue: string;
+ background: string;
+ thumbColor: string;
+ disabled?: boolean;
+ onCommit: (nextValue: number) => void;
+}) {
+ const trackRef = useRef<HTMLDivElement | null>(null);
+ const percent = ((value - min) / (max - min)) * 100;
+
+ const commitFromClientX = (clientX: number) => {
+ const rect = trackRef.current?.getBoundingClientRect();
+ if (!rect || rect.width <= 0) return;
+ const rawValue = min + ((clientX - rect.left) / rect.width) * (max - min);
+ const stepped = Math.round(rawValue / step) * step;
+ onCommit(Math.max(min, Math.min(max, stepped)));
+ };
+
+ const commitKeyboardValue = (nextValue: number) => {
+ onCommit(Math.max(min, Math.min(max, nextValue)));
+ };
+
+ return (
+ <div className="grid gap-1.5">
+ <div className="flex items-center justify-between">
+ <span className={LABEL}>{label}</span>
+ <span className="text-[10px] font-medium text-neutral-400">{displayValue}</span>
+ </div>
+ <div
+ ref={trackRef}
+ role="slider"
+ tabIndex={disabled ? -1 : 0}
+ aria-label={label}
+ aria-valuemin={min}
+ aria-valuemax={max}
+ aria-valuenow={value}
+ aria-disabled={disabled}
+ className={`relative h-4 rounded-full border border-neutral-700 shadow-[inset_0_1px_2px_rgba(0,0,0,0.55)] outline-none focus:border-[#f5a400] focus:ring-2 focus:ring-[#f5a400]/40 ${
+ disabled ? "cursor-not-allowed opacity-50" : "cursor-ew-resize"
+ }`}
+ style={{ background }}
+ onPointerDown={(event) => {
+ if (disabled) return;
+ event.currentTarget.setPointerCapture(event.pointerId);
+ commitFromClientX(event.clientX);
+ }}
+ onPointerMove={(event) => {
+ if (disabled || event.buttons !== 1) return;
+ commitFromClientX(event.clientX);
+ }}
+ onKeyDown={(event) => {
+ if (disabled) return;
+ if (event.key === "ArrowRight" || event.key === "ArrowUp") {
+ event.preventDefault();
+ commitKeyboardValue(value + step);
+ } else if (event.key === "ArrowLeft" || event.key === "ArrowDown") {
+ event.preventDefault();
+ commitKeyboardValue(value - step);
+ } else if (event.key === "Home") {
+ event.preventDefault();
+ commitKeyboardValue(min);
+ } else if (event.key === "End") {
+ event.preventDefault();
+ commitKeyboardValue(max);
+ }
+ }}
+ >
+ <div
+ className="pointer-events-none absolute top-1/2 h-6 w-6 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white shadow-[0_0_0_1px_rgba(0,0,0,0.85),0_6px_14px_rgba(0,0,0,0.5)]"
+ style={{ left: `${Math.max(0, Math.min(100, percent))}%`, backgroundColor: thumbColor }}
+ />
+ </div>
+ </div>
+ );
+}
+
+function ImageFillField({
+ projectId,
+ sourceFile,
+ value,
+ assets,
+ disabled,
+ onCommit,
+ onImportAssets,
+}: {
+ projectId: string;
+ sourceFile: string;
+ value: string;
+ assets: string[];
+ disabled?: boolean;
+ onCommit: (nextValue: string) => void;
+ onImportAssets?: (files: FileList) => Promise<string[]>;
+}) {
+ const fileInputRef = useRef<HTMLInputElement | null>(null);
+ const [uploading, setUploading] = useState(false);
+ const imageAssets = useMemo(() => assets.filter((asset) => IMAGE_EXT.test(asset)), [assets]);
+ const selectedAsset = useMemo(
+ () => resolveSelectedAsset(value, sourceFile, imageAssets),
+ [imageAssets, sourceFile, value],
+ );
+ const externalUrlValue = selectedAsset ? "" : value;
+
+ const handleUpload = async (files: FileList | null) => {
+ if (!files?.length || !onImportAssets) return;
+ setUploading(true);
+ try {
+ const uploaded = await onImportAssets(files);
+ const nextImage = uploaded.find((asset) => IMAGE_EXT.test(asset));
+ if (nextImage) {
+ onCommit(`url("${toProjectRootAssetPath(nextImage)}")`);
+ }
+ } finally {
+ setUploading(false);
+ }
+ };
+
+ return (
+ <div className="space-y-4">
+ <div className="grid min-w-0 gap-1.5">
+ <div className="flex min-w-0 flex-wrap items-center justify-between gap-2">
+ <span className={LABEL}>Project asset</span>
+ <button
+ type="button"
+ disabled={disabled || uploading}
+ onClick={() => fileInputRef.current?.click()}
+ className={`inline-flex h-7 max-w-full items-center gap-1.5 rounded-lg border border-neutral-700 bg-neutral-950 px-2.5 text-[11px] font-medium text-neutral-300 transition-colors ${
+ disabled || uploading
+ ? "cursor-not-allowed text-neutral-600"
+ : "cursor-pointer hover:border-neutral-600 hover:text-white"
+ }`}
+ >
+ <Plus size={12} className="flex-shrink-0" />
+ <span className="truncate">{uploading ? "Uploading…" : "Upload image"}</span>
+ </button>
+ <input
+ ref={fileInputRef}
+ type="file"
+ accept="image/*"
+ aria-label="Upload image asset"
+ disabled={disabled || uploading}
+ className="hidden"
+ onChange={async (event) => {
+ await handleUpload(event.target.files);
+ event.target.value = "";
+ }}
+ />
+ </div>
+ {imageAssets.length > 0 ? (
+ <div className="space-y-3">
+ {selectedAsset && (
+ <div className="overflow-hidden rounded-xl border border-neutral-800 bg-neutral-900/80">
+ <img
+ src={`/api/projects/${projectId}/preview/${selectedAsset}`}
+ alt={selectedAsset.split("/").pop() ?? selectedAsset}
+ className="h-28 w-full object-contain bg-neutral-950/80"
+ />
+ </div>
+ )}
+ <div className={FIELD}>
+ <select
+ value={selectedAsset ?? ""}
+ disabled={disabled}
+ onChange={(e) => {
+ const nextAsset = e.target.value;
+ if (!nextAsset) {
+ onCommit("none");
+ return;
+ }
+ onCommit(`url("${toProjectRootAssetPath(nextAsset)}")`);
+ }}
+ className="min-w-0 w-full appearance-none bg-transparent text-[11px] font-medium text-neutral-100 outline-none disabled:cursor-not-allowed disabled:text-neutral-600"
+ >
+ <option value="">None</option>
+ {imageAssets.map((asset) => (
+ <option key={asset} value={asset}>
+ {asset}
+ </option>
+ ))}
+ </select>
+ </div>
+ </div>
+ ) : (
+ <div className="rounded-xl border border-dashed border-neutral-800 bg-neutral-900/50 px-3 py-3 text-[11px] leading-5 text-neutral-500">
+ No image assets yet. Upload one here and Studio will also add it to the Assets tab.
+ </div>
+ )}
+ </div>
+
+ <DetailField
+ label="External URL"
+ value={externalUrlValue}
+ disabled={disabled}
+ onCommit={(next) => onCommit(next.trim() ? `url("${next.trim()}")` : "none")}
+ />
+ </div>
+ );
+}
+
+function GradientField({
+ value,
+ fallbackColor,
+ disabled,
+ onCommit,
+}: {
+ value: string;
+ fallbackColor: string | undefined;
+ disabled?: boolean;
+ onCommit: (nextValue: string) => void;
+}) {
+ const previewRef = useRef<HTMLDivElement | null>(null);
+ const parsed = parseGradient(value) ?? buildDefaultGradientModel(fallbackColor);
+
+ const commit = (next: GradientModel) => onCommit(serializeGradient(next));
+
+ const patch = (partial: Partial<GradientModel>) => commit({ ...parsed, ...partial });
+
+ const updateStop = (index: number, partial: Partial<GradientModel["stops"][number]>) => {
+ const stops = parsed.stops.map((stop, stopIndex) =>
+ stopIndex === index ? { ...stop, ...partial } : stop,
+ );
+ commit({ ...parsed, stops });
+ };
+
+ const addStop = (position?: number) => {
+ const nextGradient =
+ position != null
+ ? insertGradientStop(parsed, position)
+ : insertGradientStop(
+ parsed,
+ parsed.stops.at(-1)?.position != null
+ ? Math.min(100, (parsed.stops.at(-1)?.position ?? 90) + 10)
+ : 100,
+ );
+ commit(nextGradient);
+ };
+
+ const removeStop = (index: number) => {
+ if (parsed.stops.length <= 2) return;
+ commit({ ...parsed, stops: parsed.stops.filter((_, stopIndex) => stopIndex !== index) });
+ };
+
+ const previewStyle = {
+ backgroundImage: serializeGradient(parsed),
+ };
+
+ return (
+ <div className="space-y-4">
+ <div className={`${FIELD} space-y-3 p-3`}>
+ <div
+ ref={previewRef}
+ className="relative h-11 overflow-hidden rounded-lg border border-neutral-700"
+ style={previewStyle}
+ onClick={(event) => {
+ if (disabled) return;
+ const rect = previewRef.current?.getBoundingClientRect();
+ if (!rect || rect.width <= 0) return;
+ const position = ((event.clientX - rect.left) / rect.width) * 100;
+ addStop(position);
+ }}
+ >
+ {parsed.stops.map((stop, index) => (
+ <div
+ key={`stop-preview-${index}`}
+ className="absolute top-1/2 h-4 w-4 -translate-y-1/2 rounded-full border-2 border-white/90 shadow-[0_0_0_1px_rgba(0,0,0,0.35)]"
+ style={{
+ left: `calc(${stop.position}% - 8px)`,
+ backgroundColor: stop.color,
+ }}
+ />
+ ))}
+ </div>
+ <div className="flex min-w-0 flex-wrap items-center gap-2">
+ <SegmentedControl
+ disabled={disabled}
+ value={parsed.kind}
+ onChange={(next) => patch({ kind: next as GradientModel["kind"] })}
+ options={[
+ { label: "Linear", value: "linear" },
+ { label: "Radial", value: "radial" },
+ { label: "Conic", value: "conic" },
+ ]}
+ />
+ <label className="flex items-center gap-2 text-[11px] font-medium text-neutral-400">
+ <input
+ type="checkbox"
+ checked={parsed.repeating}
+ disabled={disabled}
+ onChange={(e) => patch({ repeating: e.target.checked })}
+ className="h-4 w-4 rounded border-neutral-700 bg-neutral-950 text-[#3ce6ac] focus:ring-[#3ce6ac]"
+ />
+ Repeat
+ </label>
+ <button
+ type="button"
+ disabled={disabled}
+ onClick={() =>
+ commit({
+ ...parsed,
+ stops: [...parsed.stops].reverse().map((stop) => ({
+ ...stop,
+ position: 100 - stop.position,
+ })),
+ })
+ }
+ className="inline-flex h-7 items-center gap-1.5 rounded-lg border border-neutral-700 bg-neutral-950 px-2.5 text-[11px] font-medium text-neutral-300 transition-colors hover:border-neutral-600 hover:text-white disabled:cursor-not-allowed disabled:text-neutral-600"
+ >
+ <RotateCcw size={12} />
+ Reverse
+ </button>
+ </div>
+ </div>
+
+ {(parsed.kind === "linear" || parsed.kind === "conic") && (
+ <div className="grid gap-1.5">
+ <span className={LABEL}>{parsed.kind === "linear" ? "Angle" : "Start angle"}</span>
+ <SliderControl
+ value={parsed.angle}
+ min={0}
+ max={360}
+ step={1}
+ disabled={disabled}
+ displayValue={`${Math.round(parsed.angle)}°`}
+ formatDisplayValue={(next) => `${Math.round(next)}°`}
+ onCommit={(next) => patch({ angle: next })}
+ />
+ </div>
+ )}
+
+ {parsed.kind === "radial" && (
+ <div className={RESPONSIVE_GRID}>
+ <SelectField
+ label="Shape"
+ value={parsed.shape}
+ disabled={disabled}
+ onChange={(next) => patch({ shape: next as GradientModel["shape"] })}
+ options={["ellipse", "circle"]}
+ />
+ <SelectField
+ label="Size"
+ value={parsed.radialSize}
+ disabled={disabled}
+ onChange={(next) => patch({ radialSize: next as GradientModel["radialSize"] })}
+ options={["closest-side", "closest-corner", "farthest-side", "farthest-corner"]}
+ />
+ </div>
+ )}
+
+ {(parsed.kind === "radial" || parsed.kind === "conic") && (
+ <div className={RESPONSIVE_GRID}>
+ <div className="grid min-w-0 gap-1.5">
+ <span className={LABEL}>Center X</span>
+ <SliderControl
+ value={parsed.centerX}
+ min={0}
+ max={100}
+ step={1}
+ disabled={disabled}
+ displayValue={`${Math.round(parsed.centerX)}%`}
+ formatDisplayValue={(next) => `${Math.round(next)}%`}
+ onCommit={(next) => patch({ centerX: next })}
+ />
+ </div>
+ <div className="grid min-w-0 gap-1.5">
+ <span className={LABEL}>Center Y</span>
+ <SliderControl
+ value={parsed.centerY}
+ min={0}
+ max={100}
+ step={1}
+ disabled={disabled}
+ displayValue={`${Math.round(parsed.centerY)}%`}
+ formatDisplayValue={(next) => `${Math.round(next)}%`}
+ onCommit={(next) => patch({ centerY: next })}
+ />
+ </div>
+ </div>
+ )}
+
+ <div className="space-y-3">
+ <div className="flex items-center justify-between">
+ <span className={LABEL}>Stops</span>
+ <button
+ type="button"
+ disabled={disabled || parsed.stops.length >= 6}
+ onClick={() => addStop()}
+ className="inline-flex h-7 items-center gap-1.5 rounded-lg border border-neutral-700 bg-neutral-950 px-2.5 text-[11px] font-medium text-neutral-300 transition-colors hover:border-neutral-600 hover:text-white disabled:cursor-not-allowed disabled:text-neutral-600"
+ >
+ <Plus size={12} />
+ Add stop
+ </button>
+ </div>
+ <div className="space-y-3">
+ {parsed.stops.map((stop, index) => (
+ <div
+ key={`stop-editor-${index}`}
+ className="grid min-w-0 grid-cols-[minmax(0,1fr)_68px_28px] gap-2"
+ >
+ <ColorField
+ label={`Stop ${index + 1}`}
+ value={stop.color}
+ disabled={disabled}
+ onCommit={(next) => updateStop(index, { color: next })}
+ />
+ <DetailField
+ label="Pos"
+ value={`${Math.round(stop.position)}%`}
+ disabled={disabled}
+ onCommit={(next) =>
+ updateStop(index, {
+ position: Number.parseFloat(next.replace("%", "")) || 0,
+ })
+ }
+ />
+ <button
+ type="button"
+ disabled={disabled || parsed.stops.length <= 2}
+ onClick={() => removeStop(index)}
+ className="mt-[22px] flex h-10 items-center justify-center rounded-lg border border-neutral-700 bg-neutral-950 text-neutral-400 transition-colors hover:border-neutral-600 hover:text-white disabled:cursor-not-allowed disabled:text-neutral-700"
+ aria-label={`Remove stop ${index + 1}`}
+ >
+ <X size={12} />
+ </button>
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function SliderControl({
+ value,
+ min,
+ max,
+ step,
+ displayValue,
+ formatDisplayValue,
+ disabled,
+ onCommit,
+}: {
+ value: number;
+ min: number;
+ max: number;
+ step: number;
+ displayValue: string;
+ formatDisplayValue?: (nextValue: number) => string;
+ disabled?: boolean;
+ onCommit: (nextValue: number) => void;
}) {
+ const [draft, setDraft] = useState(value);
+ const commitTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const valueRef = useRef(value);
+
+ valueRef.current = value;
+
+ useEffect(() => {
+ setDraft(value);
+ }, [value]);
+
+ useEffect(
+ () => () => {
+ if (commitTimerRef.current) clearTimeout(commitTimerRef.current);
+ },
+ [],
+ );
+
+ const commitDraft = (nextDraft: number) => {
+ if (commitTimerRef.current) clearTimeout(commitTimerRef.current);
+ if (nextDraft !== valueRef.current) {
+ onCommit(nextDraft);
+ }
+ };
+
+ const scheduleCommit = (nextDraft: number) => {
+ if (commitTimerRef.current) clearTimeout(commitTimerRef.current);
+ commitTimerRef.current = setTimeout(() => {
+ if (nextDraft !== valueRef.current) {
+ onCommit(nextDraft);
+ }
+ }, 40);
+ };
+
+ const renderedDisplayValue = formatDisplayValue?.(draft) ?? displayValue;
+
return (
- <div className="flex items-center gap-2">
- <span className="text-2xs text-neutral-600 w-16 flex-shrink-0 text-right">{label}</span>
+ <div className="grid min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-2">
<input
- type="text"
- value={value}
- onChange={(e) => onChange(e.target.value)}
- className="flex-1 bg-neutral-900 border border-neutral-800 rounded px-1.5 py-0.5 text-2xs text-neutral-200 font-mono outline-none focus:border-neutral-600 min-w-0"
+ type="range"
+ min={min}
+ max={max}
+ step={step}
+ value={draft}
+ disabled={disabled}
+ onChange={(e) => {
+ const nextDraft = Number(e.target.value);
+ setDraft(nextDraft);
+ scheduleCommit(nextDraft);
+ }}
+ onMouseUp={() => commitDraft(draft)}
+ onTouchEnd={() => commitDraft(draft)}
+ onBlur={() => commitDraft(draft)}
+ className="h-2 min-w-0 w-full cursor-pointer appearance-none rounded-full bg-neutral-800 accent-[#3ce6ac] disabled:cursor-not-allowed"
/>
+ <div className="min-w-[52px] rounded-xl border border-neutral-800 bg-neutral-900 px-2 py-2 text-right text-[11px] font-medium text-neutral-100 shadow-[inset_0_1px_0_rgba(255,255,255,0.03)]">
+ {renderedDisplayValue}
+ </div>
</div>
);
}
-function ColorRow({
+function SegmentedControl({
+ options,
+ value,
+ disabled,
+ onChange,
+}: {
+ options: Array<{ label: string; value: string }>;
+ value: string;
+ disabled?: boolean;
+ onChange: (nextValue: string) => void;
+}) {
+ return (
+ <div
+ className="grid min-w-0 gap-1 rounded-xl bg-neutral-900 p-1 shadow-[inset_0_1px_0_rgba(255,255,255,0.03)]"
+ style={{ gridTemplateColumns: `repeat(${options.length}, minmax(0, 1fr))` }}
+ >
+ {options.map((option) => {
+ const selected = option.value === value;
+ return (
+ <button
+ key={option.value}
+ type="button"
+ disabled={disabled}
+ onClick={() => onChange(option.value)}
+ className={`min-w-0 truncate rounded-lg px-2 py-1.5 text-[11px] font-medium transition-colors disabled:cursor-not-allowed ${
+ selected
+ ? "bg-neutral-800 text-white shadow-[0_1px_3px_rgba(0,0,0,0.28)]"
+ : "text-neutral-500 hover:text-neutral-200"
+ }`}
+ >
+ {option.label}
+ </button>
+ );
+ })}
+ </div>
+ );
+}
+
+function SelectField({
label,
value,
+ disabled,
+ options,
onChange,
}: {
label: string;
value: string;
- onChange: (v: string) => void;
+ disabled?: boolean;
+ options: string[];
+ onChange: (nextValue: string) => void;
}) {
return (
- <div className="flex items-center gap-2">
- <span className="text-2xs text-neutral-600 w-16 flex-shrink-0 text-right">{label}</span>
- <div className="flex items-center gap-1 flex-1">
- <div
- className="w-5 h-5 rounded border border-neutral-700 flex-shrink-0"
- style={{ backgroundColor: value }}
- />
- <input
- type="text"
+ <label className="grid min-w-0 gap-1.5">
+ <span className={LABEL}>{label}</span>
+ <div className={FIELD}>
+ <select
value={value}
+ disabled={disabled}
onChange={(e) => onChange(e.target.value)}
- className="flex-1 bg-neutral-900 border border-neutral-800 rounded px-1.5 py-0.5 text-2xs text-neutral-200 font-mono outline-none focus:border-neutral-600 min-w-0"
- />
+ className="min-w-0 w-full appearance-none bg-transparent text-[11px] font-medium text-neutral-100 outline-none disabled:cursor-not-allowed disabled:text-neutral-600"
+ >
+ {options.map((option) => (
+ <option key={option} value={option}>
+ {option}
+ </option>
+ ))}
+ </select>
</div>
- </div>
+ </label>
);
}
-function SectionHeader({ icon: Icon, label }: { icon: typeof Move; label: string }) {
+function Section({
+ title,
+ icon,
+ children,
+ accessory,
+}: {
+ title: string;
+ icon: ReactNode;
+ children: ReactNode;
+ accessory?: ReactNode;
+}) {
return (
- <div className="flex items-center gap-1.5 mt-2 mb-1">
- <Icon size={10} className="text-neutral-600" />
- <span className="text-2xs font-medium text-neutral-500 uppercase tracking-wider">
- {label}
- </span>
+ <section className="min-w-0 border-t border-neutral-800/80 px-4 py-4">
+ <div className="mb-3 flex min-w-0 flex-wrap items-center justify-between gap-2">
+ <div className="flex min-w-0 items-center gap-2.5">
+ <span className="flex-shrink-0 text-neutral-500">{icon}</span>
+ <h3 className="text-[11px] font-semibold uppercase tracking-[0.12em] text-neutral-300">
+ {title}
+ </h3>
+ </div>
+ {accessory}
+ </div>
+ {children}
+ </section>
+ );
+}
+
+function SelectionColorRow({
+ swatch,
+ token,
+ sources,
+}: {
+ swatch: string;
+ token: string;
+ sources: string[];
+}) {
+ return (
+ <div className={`${FIELD} flex min-w-0 items-center gap-3`}>
+ <div
+ className="h-7 w-7 flex-shrink-0 rounded-lg border border-neutral-700"
+ style={{ backgroundColor: swatch }}
+ />
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-[11px] font-medium text-neutral-100">{token}</div>
+ <div className="truncate text-[11px] uppercase tracking-[0.18em] text-neutral-500">
+ {sources.join(" · ")}
+ </div>
+ </div>
</div>
);
}
export const PropertyPanel = memo(function PropertyPanel({
+ projectId,
+ assets,
element,
- isPickMode,
- onEnablePick,
- onDisablePick,
- onClearPick,
+ copiedAgentPrompt,
+ onClearSelection,
onSetStyle,
- onSetDataAttr,
+ onSetManualOffset,
+ onSetManualSize,
onSetText,
+ onSetTextFieldStyle,
+ onAddTextField,
+ onRemoveTextField,
+ onResetManualEdits,
+ onAskAgent,
+ onImportAssets,
+ fontAssets = [],
+ onImportFonts,
}: PropertyPanelProps) {
+ const styles = element?.computedStyles ?? EMPTY_STYLES;
+ const selectionColors = useMemo(() => collectSelectionColors(styles), [styles]);
+ const backgroundImage = styles["background-image"] ?? "none";
+ const fillMode =
+ backgroundImage && backgroundImage !== "none"
+ ? backgroundImage.includes("gradient")
+ ? "Gradient"
+ : "Image"
+ : "Solid";
+ const [preferredFillMode, setPreferredFillMode] = useState(fillMode);
+ const imageUrl = extractBackgroundImageUrl(backgroundImage);
+ const [activeTextFieldKey, setActiveTextFieldKey] = useState<string | null>(
+ element?.textFields[0]?.key ?? null,
+ );
+ const hasTextControls = element != null && isTextEditableSelection(element);
+
+ useEffect(() => {
+ setPreferredFillMode(fillMode);
+ }, [fillMode, element?.id, element?.selector, backgroundImage]);
+
+ useEffect(() => {
+ const nextFields = element?.textFields ?? [];
+ setActiveTextFieldKey((current) => {
+ if (current && nextFields.some((field) => field.key === current)) return current;
+ return nextFields[0]?.key ?? null;
+ });
+ }, [element?.id, element?.selector, element?.textFields]);
+
if (!element) {
return (
- <div className="flex flex-col items-center justify-center h-full px-4 text-center">
- <MousePointer size={20} className="text-neutral-700 mb-2" />
- <p className="text-xs text-neutral-500">Click an element in the preview to inspect it</p>
- <Button
- variant="secondary"
- size="sm"
- onClick={isPickMode ? onDisablePick : onEnablePick}
- className={`mt-3 ${isPickMode ? "bg-studio-accent/20 text-studio-accent border-studio-accent/30" : ""}`}
- >
- {isPickMode ? "Pick mode active..." : "Enable Pick Mode"}
- </Button>
+ <div className="flex h-full flex-col items-center justify-center bg-neutral-900 px-6 text-center">
+ <Eye size={18} className="mb-3 text-neutral-600" />
+ <p className="text-sm font-medium text-neutral-200">Select an element in the preview.</p>
+ <p className="mt-2 max-w-[260px] text-xs leading-5 text-neutral-500">
+ The inspector is tuned for element edits with safer geometry controls, color picking, and
+ cleaner grouped layer controls.
+ </p>
</div>
);
}
- const s = element.computedStyles;
+ const styleEditingDisabled = !element.capabilities.canEditStyles;
+ const manualOffsetEditingDisabled = !element.capabilities.canApplyManualOffset;
+ const manualSizeEditingDisabled = !element.capabilities.canApplyManualSize;
+ const isFlex = styles.display === "flex" || styles.display === "inline-flex";
+ const radiusValue = parseNumericValue(styles["border-radius"]) ?? 0;
+ const opacityValue = Math.round((parseNumericValue(styles.opacity) ?? 1) * 100);
+ const clipContent = ["hidden", "clip"].includes((styles.overflow ?? "").trim());
+ const sourceLabel = element.id ? `#${element.id}` : element.selector;
+ const showEditableSections = element.capabilities.canEditStyles;
+ const manualOffset = readStudioPathOffset(element.element);
+ const manualSize = readStudioBoxSize(element.element);
+ const resolvedWidth =
+ manualSize.width > 0
+ ? manualSize.width
+ : (parsePxMetricValue(styles.width ?? "") ?? element.boundingBox.width);
+ const resolvedHeight =
+ manualSize.height > 0
+ ? manualSize.height
+ : (parsePxMetricValue(styles.height ?? "") ?? element.boundingBox.height);
+
+ const commitManualOffset = (axis: "x" | "y", nextValue: string) => {
+ const parsed = parsePxMetricValue(nextValue);
+ if (parsed == null) return;
+ const current = readStudioPathOffset(element.element);
+ onSetManualOffset(element, {
+ x: axis === "x" ? parsed : current.x,
+ y: axis === "y" ? parsed : current.y,
+ });
+ };
+
+ const commitManualSize = (axis: "width" | "height", nextValue: string) => {
+ const parsed = parsePxMetricValue(nextValue);
+ if (parsed == null || parsed <= 0) return;
+ const current = readStudioBoxSize(element.element);
+ const width =
+ current.width > 0
+ ? current.width
+ : (parsePxMetricValue(styles.width ?? "") ?? element.boundingBox.width);
+ const height =
+ current.height > 0
+ ? current.height
+ : (parsePxMetricValue(styles.height ?? "") ?? element.boundingBox.height);
+ onSetManualSize(element, {
+ width: axis === "width" ? parsed : width,
+ height: axis === "height" ? parsed : height,
+ });
+ };
+
+ const handleFillModeChange = (nextMode: string) => {
+ setPreferredFillMode(nextMode);
+ if (nextMode === "Solid") {
+ onSetStyle("background-image", "none");
+ return;
+ }
+ if (nextMode === "Gradient" && !backgroundImage.includes("gradient")) {
+ onSetStyle(
+ "background-image",
+ serializeGradient(buildDefaultGradientModel(styles["background-color"])),
+ );
+ }
+ };
return (
- <div className="flex flex-col h-full min-h-0">
- {/* Header */}
- <div className="flex items-center justify-between px-3 py-2 border-b border-neutral-800 flex-shrink-0">
- <div className="flex items-center gap-1.5 min-w-0">
- <span className="text-2xs font-mono text-studio-accent truncate">{element.selector}</span>
- </div>
- <div className="flex items-center gap-1">
- <IconButton
- icon={<MousePointer size={11} />}
- aria-label={isPickMode ? "Disable pick mode" : "Enable pick mode"}
- size="sm"
- onClick={isPickMode ? onDisablePick : onEnablePick}
- className={isPickMode ? "text-studio-accent bg-studio-accent/10" : ""}
- />
- <IconButton
- icon={<X size={11} />}
+ <div className="flex h-full min-h-0 flex-col overflow-hidden bg-neutral-900 text-neutral-100">
+ <div className="border-b border-neutral-800 px-4 py-5">
+ <div className="flex items-start justify-between gap-4">
+ <div className="min-w-0">
+ <div className={LABEL}>Document</div>
+ <div className="mt-3 truncate text-[12px] font-semibold text-neutral-100">
+ {element.label}
+ </div>
+ <div className="mt-1 truncate text-[11px] text-neutral-500">{sourceLabel}</div>
+ </div>
+ <button
+ type="button"
aria-label="Clear selection"
- size="sm"
- onClick={onClearPick}
- />
- </div>
- </div>
-
- {/* Properties */}
- <div className="flex-1 overflow-y-auto px-3 py-2 space-y-1">
- {/* Element info */}
- <div className="flex items-center gap-2 mb-2">
- <span className="text-2xs text-neutral-300 font-medium">{element.label}</span>
- <span className="text-2xs text-neutral-600 font-mono">&lt;{element.tagName}&gt;</span>
+ onClick={onClearSelection}
+ className="flex h-9 w-9 items-center justify-center rounded-full border border-neutral-700 bg-neutral-950 text-neutral-500 shadow-[0_1px_2px_rgba(0,0,0,0.2)] transition-colors hover:border-neutral-600 hover:text-neutral-200"
+ >
+ <X size={13} />
+ </button>
</div>
-
- {/* Position & Size */}
- <SectionHeader icon={Move} label="Position & Size" />
- <div className="grid grid-cols-2 gap-1">
- <PropertyRow
- label="X"
- value={s["left"] ?? "auto"}
- onChange={(v) => onSetStyle("left", v)}
- />
- <PropertyRow
- label="Y"
- value={s["top"] ?? "auto"}
- onChange={(v) => onSetStyle("top", v)}
- />
- <PropertyRow
- label="W"
- value={s["width"] ?? "auto"}
- onChange={(v) => onSetStyle("width", v)}
- />
- <PropertyRow
- label="H"
- value={s["height"] ?? "auto"}
- onChange={(v) => onSetStyle("height", v)}
- />
+ <div className="mt-4 flex min-w-0 flex-wrap items-center gap-2">
+ <button
+ type="button"
+ onClick={onAskAgent}
+ className="inline-flex h-8 items-center justify-center gap-2 rounded-xl border border-neutral-700 bg-neutral-950 px-3.5 text-[11px] font-medium text-neutral-100 transition-colors hover:border-studio-accent/40 hover:text-studio-accent"
+ >
+ <MessageSquare size={15} />
+ <span>{copiedAgentPrompt ? "Prompt copied" : "Ask agent"}</span>
+ </button>
+ <button
+ type="button"
+ onClick={() => onResetManualEdits(element)}
+ title="Reset move, size, and rotation edits"
+ className="inline-flex h-8 items-center justify-center gap-2 rounded-xl border border-neutral-700 bg-neutral-950 px-3.5 text-[11px] font-medium text-neutral-100 transition-colors hover:border-neutral-500 hover:text-white"
+ >
+ <RotateCcw size={14} />
+ <span>Reset edits</span>
+ </button>
</div>
+ </div>
- {/* Typography */}
- {(element.tagName === "div" ||
- element.tagName === "span" ||
- element.tagName === "p" ||
- element.tagName === "h1" ||
- element.tagName === "h2") && (
- <>
- <SectionHeader icon={Type} label="Typography" />
- <PropertyRow
- label="Size"
- value={s["font-size"] ?? ""}
- onChange={(v) => onSetStyle("font-size", v)}
+ <div className="flex-1 overflow-y-auto">
+ <Section title="Layout" icon={<Move size={15} />}>
+ <div className={RESPONSIVE_GRID}>
+ <MetricField
+ label="X"
+ value={formatPxMetricValue(manualOffset.x)}
+ disabled={manualOffsetEditingDisabled}
+ onCommit={(next) => commitManualOffset("x", next)}
/>
- <PropertyRow
- label="Weight"
- value={s["font-weight"] ?? ""}
- onChange={(v) => onSetStyle("font-weight", v)}
+ <MetricField
+ label="Y"
+ value={formatPxMetricValue(manualOffset.y)}
+ disabled={manualOffsetEditingDisabled}
+ onCommit={(next) => commitManualOffset("y", next)}
/>
- <PropertyRow
- label="Family"
- value={s["font-family"]?.split(",")[0] ?? ""}
- onChange={(v) => onSetStyle("font-family", v)}
+ <MetricField
+ label="W"
+ value={formatPxMetricValue(resolvedWidth)}
+ disabled={manualSizeEditingDisabled}
+ onCommit={(next) => commitManualSize("width", next)}
/>
- </>
- )}
-
- {/* Colors */}
- <SectionHeader icon={Palette} label="Colors" />
- <ColorRow
- label="Color"
- value={s["color"] ?? "#fff"}
- onChange={(v) => onSetStyle("color", v)}
- />
- <ColorRow
- label="Background"
- value={s["background-color"] ?? "transparent"}
- onChange={(v) => onSetStyle("background-color", v)}
- />
-
- {/* Appearance */}
- <SectionHeader icon={Eye} label="Appearance" />
- <PropertyRow
- label="Opacity"
- value={s["opacity"] ?? "1"}
- onChange={(v) => onSetStyle("opacity", v)}
- />
- <PropertyRow
- label="Radius"
- value={s["border-radius"] ?? "0"}
- onChange={(v) => onSetStyle("border-radius", v)}
- />
- <PropertyRow
- label="Z-index"
- value={s["z-index"] ?? "auto"}
- onChange={(v) => onSetStyle("z-index", v)}
- />
- <PropertyRow
- label="Transform"
- value={s["transform"] ?? "none"}
- onChange={(v) => onSetStyle("transform", v)}
- />
+ <MetricField
+ label="H"
+ value={formatPxMetricValue(resolvedHeight)}
+ disabled={manualSizeEditingDisabled}
+ onCommit={(next) => commitManualSize("height", next)}
+ />
+ </div>
+ </Section>
- {/* Timing */}
- {(element.dataAttributes["start"] || element.dataAttributes["duration"]) && (
- <>
- <SectionHeader icon={Clock} label="Timing" />
- {element.dataAttributes["start"] != null && (
- <PropertyRow
- label="Start"
- value={element.dataAttributes["start"]}
- onChange={(v) => onSetDataAttr("start", v)}
+ {showEditableSections && isFlex && (
+ <Section title="Flex" icon={<Layers size={15} />}>
+ <div className="space-y-4">
+ <SegmentedControl
+ disabled={styleEditingDisabled}
+ value={styles["flex-direction"] || "row"}
+ onChange={(next) => onSetStyle("flex-direction", next)}
+ options={[
+ { label: "→ Row", value: "row" },
+ { label: "↓ Column", value: "column" },
+ ]}
/>
- )}
- {element.dataAttributes["duration"] != null && (
- <PropertyRow
- label="Duration"
- value={element.dataAttributes["duration"]}
- onChange={(v) => onSetDataAttr("duration", v)}
- />
- )}
- {element.dataAttributes["track-index"] != null && (
- <PropertyRow
- label="Track"
- value={element.dataAttributes["track-index"]}
- onChange={(v) => onSetDataAttr("track-index", v)}
+ <div className={RESPONSIVE_GRID}>
+ <SelectField
+ label="Justify"
+ value={styles["justify-content"] || "flex-start"}
+ disabled={styleEditingDisabled}
+ onChange={(next) => onSetStyle("justify-content", next)}
+ options={[
+ "flex-start",
+ "center",
+ "space-between",
+ "space-around",
+ "space-evenly",
+ "flex-end",
+ ]}
+ />
+ <SelectField
+ label="Align"
+ value={styles["align-items"] || "stretch"}
+ disabled={styleEditingDisabled}
+ onChange={(next) => onSetStyle("align-items", next)}
+ options={["stretch", "flex-start", "center", "flex-end", "baseline"]}
+ />
+ </div>
+ <DetailField
+ label="Gap"
+ value={styles.gap ?? "0px"}
+ disabled={styleEditingDisabled}
+ onCommit={(next) => onSetStyle("gap", next.endsWith("px") ? next : `${next}px`)}
/>
- )}
- </>
+ <label className="flex items-center gap-3 rounded-2xl border border-neutral-800 bg-neutral-900 px-3 py-3 text-[12px] text-neutral-300 shadow-[inset_0_1px_0_rgba(255,255,255,0.03)]">
+ <input
+ type="checkbox"
+ checked={clipContent}
+ disabled={styleEditingDisabled}
+ onChange={(e) => onSetStyle("overflow", e.target.checked ? "hidden" : "visible")}
+ className="h-4 w-4 rounded border-neutral-700 bg-neutral-950 text-[#3ce6ac] focus:ring-[#3ce6ac]"
+ />
+ <span>Clip content</span>
+ </label>
+ </div>
+ </Section>
)}
- {/* Editable text content */}
- {element.textContent && (
+ {showEditableSections && (
<>
- <SectionHeader icon={Type} label="Text Content" />
- <textarea
- defaultValue={element.textContent}
- onBlur={(e) => onSetText?.(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === "Enter" && e.metaKey) {
- (e.target as HTMLTextAreaElement).blur();
- }
- }}
- rows={3}
- className="w-full bg-neutral-900 border border-neutral-800 rounded px-2 py-1.5 text-xs text-neutral-200 outline-none focus:border-neutral-600 resize-y leading-relaxed"
- placeholder="Edit text..."
- />
+ <Section title="Radius" icon={<Settings size={15} />}>
+ <SliderControl
+ value={radiusValue}
+ min={0}
+ max={Math.max(240, Math.ceil(radiusValue))}
+ step={1}
+ disabled={styleEditingDisabled}
+ displayValue={`${formatNumericValue(radiusValue)}px`}
+ formatDisplayValue={(next) => `${formatNumericValue(next)}px`}
+ onCommit={(next) => onSetStyle("border-radius", `${formatNumericValue(next)}px`)}
+ />
+ </Section>
+
+ <Section title="Blending" icon={<Eye size={15} />}>
+ <div className="space-y-4">
+ <SliderControl
+ value={opacityValue}
+ min={0}
+ max={100}
+ step={1}
+ disabled={styleEditingDisabled}
+ displayValue={`${opacityValue}%`}
+ formatDisplayValue={(next) => `${Math.round(next)}%`}
+ onCommit={(next) => onSetStyle("opacity", formatNumericValue(next / 100))}
+ />
+ <SelectField
+ label="Mode"
+ value={styles["mix-blend-mode"] || "normal"}
+ disabled={styleEditingDisabled}
+ onChange={(next) => onSetStyle("mix-blend-mode", next)}
+ options={["normal", "multiply", "screen", "overlay", "darken", "lighten"]}
+ />
+ </div>
+ </Section>
+
+ <Section
+ title="Fill"
+ icon={<Palette size={15} />}
+ accessory={
+ <div className="rounded-full border border-neutral-700 bg-neutral-900 px-2.5 py-1 text-[10px] font-medium uppercase tracking-[0.16em] text-neutral-400">
+ {preferredFillMode}
+ </div>
+ }
+ >
+ <div className="space-y-4">
+ <SegmentedControl
+ disabled={styleEditingDisabled}
+ value={preferredFillMode}
+ onChange={handleFillModeChange}
+ options={[
+ { label: "Solid", value: "Solid" },
+ { label: "Gradient", value: "Gradient" },
+ { label: "Image", value: "Image" },
+ ]}
+ />
+ {preferredFillMode === "Solid" ? (
+ <ColorField
+ label="Fill color"
+ value={styles["background-color"] ?? "transparent"}
+ disabled={styleEditingDisabled}
+ onCommit={(next) => onSetStyle("background-color", next)}
+ />
+ ) : preferredFillMode === "Gradient" ? (
+ <GradientField
+ value={
+ backgroundImage !== "none"
+ ? backgroundImage
+ : serializeGradient(buildDefaultGradientModel(styles["background-color"]))
+ }
+ fallbackColor={styles["background-color"]}
+ disabled={styleEditingDisabled}
+ onCommit={(next) => onSetStyle("background-image", next)}
+ />
+ ) : (
+ <ImageFillField
+ projectId={projectId}
+ sourceFile={element.sourceFile}
+ value={imageUrl}
+ assets={assets}
+ disabled={styleEditingDisabled}
+ onCommit={(next) => onSetStyle("background-image", next)}
+ onImportAssets={onImportAssets}
+ />
+ )}
+ {!hasTextControls && (
+ <ColorField
+ label="Text color"
+ value={styles.color ?? "rgb(0, 0, 0)"}
+ disabled={styleEditingDisabled}
+ onCommit={(next) => onSetStyle("color", next)}
+ />
+ )}
+ </div>
+ </Section>
+
+ {hasTextControls && (
+ <Section title="Text" icon={<Type size={15} />}>
+ {(() => {
+ const textFields = element.textFields;
+ const activeField =
+ textFields.find((field) => field.key === activeTextFieldKey) ?? textFields[0];
+ if (!activeField) return null;
+
+ if (textFields.length === 1) {
+ return (
+ <div className="space-y-4 rounded-xl border border-neutral-800 bg-neutral-900/60 p-3">
+ <div className="min-w-0">
+ <div className="truncate text-[11px] font-medium text-neutral-100">
+ {formatTextFieldPreview(activeField.value) || "Text"}
+ </div>
+ <div className="text-[10px] uppercase tracking-[0.12em] text-neutral-500">
+ {activeField.tagName}
+ </div>
+ </div>
+
+ <TextAreaField
+ key={activeField.key}
+ label="Content"
+ value={activeField.value}
+ disabled={false}
+ onCommit={(next) => onSetText(next, activeField.key)}
+ />
+
+ <ColorField
+ label="Text color"
+ value={getTextFieldColor(activeField, styles)}
+ disabled={false}
+ onCommit={(next) => onSetTextFieldStyle(activeField.key, "color", next)}
+ />
+
+ <div className={RESPONSIVE_GRID}>
+ <MetricField
+ label="Size"
+ value={
+ activeField.computedStyles["font-size"] ||
+ styles["font-size"] ||
+ "16px"
+ }
+ disabled={false}
+ liveCommit
+ onCommit={(next) =>
+ onSetTextFieldStyle(activeField.key, "font-size", next)
+ }
+ />
+ <FontWeightField
+ value={
+ activeField.computedStyles["font-weight"] ||
+ styles["font-weight"] ||
+ "400"
+ }
+ disabled={false}
+ onCommit={(next) =>
+ onSetTextFieldStyle(activeField.key, "font-weight", next)
+ }
+ />
+ </div>
+
+ <FontFamilyField
+ value={
+ activeField.computedStyles["font-family"] ||
+ styles["font-family"] ||
+ "inherit"
+ }
+ disabled={false}
+ importedFonts={fontAssets}
+ onImportFonts={onImportFonts}
+ onCommit={(next) =>
+ onSetTextFieldStyle(activeField.key, "font-family", next)
+ }
+ />
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-4">
+ <div className="grid gap-1.5">
+ <div className="flex min-w-0 flex-wrap items-center justify-between gap-2">
+ <span className={LABEL}>Text layers</span>
+ <button
+ type="button"
+ onClick={() => {
+ void Promise.resolve(onAddTextField(activeField.key)).then(
+ (nextKey) => {
+ if (nextKey) setActiveTextFieldKey(nextKey);
+ },
+ );
+ }}
+ className="inline-flex h-7 max-w-full items-center gap-1.5 rounded-lg border border-neutral-700 bg-neutral-950 px-2.5 text-[11px] font-medium text-neutral-300 transition-colors hover:border-neutral-600 hover:text-white"
+ >
+ <Plus size={12} className="flex-shrink-0" />
+ <span className="truncate">Add text</span>
+ </button>
+ </div>
+ <div className="grid gap-2">
+ {textFields.map((field, index) => {
+ const active = field.key === activeField.key;
+ return (
+ <button
+ key={field.key}
+ type="button"
+ onClick={() => setActiveTextFieldKey(field.key)}
+ className={`min-w-0 w-full rounded-xl border px-3 py-2 text-left transition-colors ${
+ active
+ ? "border-studio-accent/50 bg-studio-accent/10"
+ : "border-neutral-800 bg-neutral-900/80 hover:border-neutral-700 hover:bg-neutral-900"
+ }`}
+ >
+ <div className="flex min-w-0 items-center justify-between gap-2">
+ <div className="flex min-w-0 items-center gap-2">
+ <span
+ className="h-4 w-4 flex-shrink-0 rounded border border-neutral-700 bg-neutral-950"
+ style={{ backgroundColor: getTextFieldColor(field, styles) }}
+ />
+ <span className="min-w-0 truncate text-[11px] font-medium text-neutral-100">
+ {formatTextFieldPreview(field.value) || `Text ${index + 1}`}
+ </span>
+ </div>
+ <span className="flex-shrink-0 rounded-md border border-neutral-700 bg-neutral-950 px-1.5 py-0.5 text-[10px] uppercase tracking-[0.12em] text-neutral-500">
+ {field.tagName}
+ </span>
+ </div>
+ </button>
+ );
+ })}
+ </div>
+ </div>
+
+ <div className="space-y-4 rounded-xl border border-neutral-800 bg-neutral-900/60 p-3">
+ <div className="flex min-w-0 items-center justify-between gap-2">
+ <div className="min-w-0">
+ <div className="truncate text-[11px] font-medium text-neutral-100">
+ {formatTextFieldPreview(activeField.value) || "Text"}
+ </div>
+ <div className="text-[10px] uppercase tracking-[0.12em] text-neutral-500">
+ {activeField.tagName}
+ </div>
+ </div>
+ <button
+ type="button"
+ onClick={() => onRemoveTextField(activeField.key)}
+ className="inline-flex h-7 flex-shrink-0 items-center rounded-lg border border-neutral-700 bg-neutral-950 px-2.5 text-[11px] font-medium text-neutral-300 transition-colors hover:border-neutral-600 hover:text-white"
+ >
+ Remove
+ </button>
+ </div>
+
+ <TextAreaField
+ key={activeField.key}
+ label="Content"
+ value={activeField.value}
+ disabled={false}
+ autoFocus
+ onCommit={(next) => onSetText(next, activeField.key)}
+ />
+
+ <ColorField
+ label="Text color"
+ value={getTextFieldColor(activeField, styles)}
+ disabled={false}
+ onCommit={(next) => onSetTextFieldStyle(activeField.key, "color", next)}
+ />
+
+ <div className={RESPONSIVE_GRID}>
+ <MetricField
+ label="Size"
+ value={activeField.computedStyles["font-size"] || "16px"}
+ disabled={false}
+ liveCommit
+ onCommit={(next) =>
+ onSetTextFieldStyle(activeField.key, "font-size", next)
+ }
+ />
+ <FontWeightField
+ value={activeField.computedStyles["font-weight"] || "400"}
+ disabled={false}
+ onCommit={(next) =>
+ onSetTextFieldStyle(activeField.key, "font-weight", next)
+ }
+ />
+ </div>
+
+ <FontFamilyField
+ value={
+ activeField.computedStyles["font-family"] ||
+ styles["font-family"] ||
+ "inherit"
+ }
+ disabled={false}
+ importedFonts={fontAssets}
+ onImportFonts={onImportFonts}
+ onCommit={(next) =>
+ onSetTextFieldStyle(activeField.key, "font-family", next)
+ }
+ />
+ </div>
+ </div>
+ );
+ })()}
+ </Section>
+ )}
+
+ {selectionColors.length > 0 && (
+ <Section title="Selection colors" icon={<Palette size={15} />}>
+ <div className="space-y-3">
+ {selectionColors.map((entry) => (
+ <SelectionColorRow
+ key={`${entry.swatch}-${entry.token}`}
+ swatch={entry.swatch}
+ token={entry.token}
+ sources={entry.sources}
+ />
+ ))}
+ </div>
+ </Section>
+ )}
</>
)}
</div>
diff --git a/packages/studio/src/components/editor/colorValue.test.ts b/packages/studio/src/components/editor/colorValue.test.ts
new file mode 100644
index 0000000000..fe0cb0b97d
--- /dev/null
+++ b/packages/studio/src/components/editor/colorValue.test.ts
@@ -0,0 +1,82 @@
+import { describe, expect, it } from "vitest";
+import {
+ formatCssColor,
+ hsvToRgb,
+ mergeColorWithExistingAlpha,
+ parseCssColor,
+ rgbToHsv,
+ toColorPickerValue,
+ toHexColor,
+} from "./colorValue";
+
+describe("parseCssColor", () => {
+ it("parses rgb values", () => {
+ expect(parseCssColor("rgb(12, 34, 56)")).toEqual({
+ red: 12,
+ green: 34,
+ blue: 56,
+ alpha: 1,
+ });
+ });
+
+ it("parses rgba values", () => {
+ expect(parseCssColor("rgba(15, 23, 42, 0.64)")).toEqual({
+ red: 15,
+ green: 23,
+ blue: 42,
+ alpha: 0.64,
+ });
+ });
+
+ it("parses transparent", () => {
+ expect(parseCssColor("transparent")).toEqual({
+ red: 0,
+ green: 0,
+ blue: 0,
+ alpha: 0,
+ });
+ });
+});
+
+describe("toColorPickerValue", () => {
+ it("converts css color to hex", () => {
+ expect(toColorPickerValue("rgba(15, 23, 42, 0.64)")).toBe("#0f172a");
+ });
+});
+
+describe("toHexColor", () => {
+ it("formats rgb channels as hex", () => {
+ expect(toHexColor({ red: 15, green: 23, blue: 42 })).toBe("#0f172a");
+ });
+});
+
+describe("formatCssColor", () => {
+ it("formats opaque colors as rgb", () => {
+ expect(formatCssColor({ red: 18, green: 52, blue: 86, alpha: 1 })).toBe("rgb(18, 52, 86)");
+ });
+
+ it("formats translucent colors as rgba", () => {
+ expect(formatCssColor({ red: 18, green: 52, blue: 86, alpha: 0.64 })).toBe(
+ "rgba(18, 52, 86, 0.64)",
+ );
+ });
+});
+
+describe("rgb hsv conversion", () => {
+ it("round-trips primary color values", () => {
+ const hsv = rgbToHsv({ red: 47, green: 198, blue: 127 });
+ expect(hsvToRgb(hsv)).toEqual({ red: 47, green: 198, blue: 127 });
+ });
+});
+
+describe("mergeColorWithExistingAlpha", () => {
+ it("preserves alpha when the previous color was translucent", () => {
+ expect(mergeColorWithExistingAlpha("#123456", "rgba(15, 23, 42, 0.64)")).toBe(
+ "rgba(18, 52, 86, 0.64)",
+ );
+ });
+
+ it("returns rgb when the previous color was opaque", () => {
+ expect(mergeColorWithExistingAlpha("#123456", "rgb(15, 23, 42)")).toBe("rgb(18, 52, 86)");
+ });
+});
diff --git a/packages/studio/src/components/editor/colorValue.ts b/packages/studio/src/components/editor/colorValue.ts
new file mode 100644
index 0000000000..d1d04fb5a2
--- /dev/null
+++ b/packages/studio/src/components/editor/colorValue.ts
@@ -0,0 +1,175 @@
+export interface ParsedColor {
+ red: number;
+ green: number;
+ blue: number;
+ alpha: number;
+}
+
+export interface HsvColor {
+ hue: number;
+ saturation: number;
+ value: number;
+}
+
+function clampChannel(value: number): number {
+ return Math.max(0, Math.min(255, Math.round(value)));
+}
+
+function clampAlpha(value: number): number {
+ return Math.max(0, Math.min(1, value));
+}
+
+function toHex(value: number): string {
+ return clampChannel(value).toString(16).padStart(2, "0");
+}
+
+function formatAlpha(value: number): string {
+ return `${Math.round(clampAlpha(value) * 100) / 100}`;
+}
+
+export function parseCssColor(value: string): ParsedColor | null {
+ const trimmed = value.trim().toLowerCase();
+ if (!trimmed) return null;
+ if (trimmed === "transparent") {
+ return { red: 0, green: 0, blue: 0, alpha: 0 };
+ }
+
+ const shortHex = trimmed.match(/^#([0-9a-f]{3})$/i);
+ if (shortHex) {
+ const [r, g, b] = shortHex[1].split("");
+ return {
+ red: Number.parseInt(r + r, 16),
+ green: Number.parseInt(g + g, 16),
+ blue: Number.parseInt(b + b, 16),
+ alpha: 1,
+ };
+ }
+
+ const hex = trimmed.match(/^#([0-9a-f]{6})$/i);
+ if (hex) {
+ return {
+ red: Number.parseInt(hex[1].slice(0, 2), 16),
+ green: Number.parseInt(hex[1].slice(2, 4), 16),
+ blue: Number.parseInt(hex[1].slice(4, 6), 16),
+ alpha: 1,
+ };
+ }
+
+ const rgba = trimmed.match(
+ /^rgba?\(\s*([0-9.]+)\s*,\s*([0-9.]+)\s*,\s*([0-9.]+)(?:\s*,\s*([0-9.]+))?\s*\)$/i,
+ );
+ if (rgba) {
+ return {
+ red: clampChannel(Number.parseFloat(rgba[1])),
+ green: clampChannel(Number.parseFloat(rgba[2])),
+ blue: clampChannel(Number.parseFloat(rgba[3])),
+ alpha: clampAlpha(rgba[4] != null ? Number.parseFloat(rgba[4]) : 1),
+ };
+ }
+
+ return null;
+}
+
+export function toColorPickerValue(value: string): string {
+ const parsed = parseCssColor(value);
+ if (!parsed) return "#000000";
+ return toHexColor(parsed);
+}
+
+export function toHexColor(color: Pick<ParsedColor, "red" | "green" | "blue">): string {
+ return `#${toHex(color.red)}${toHex(color.green)}${toHex(color.blue)}`;
+}
+
+export function formatCssColor(color: ParsedColor): string {
+ const red = clampChannel(color.red);
+ const green = clampChannel(color.green);
+ const blue = clampChannel(color.blue);
+ const alpha = clampAlpha(color.alpha);
+
+ if (alpha >= 1) {
+ return `rgb(${red}, ${green}, ${blue})`;
+ }
+
+ return `rgba(${red}, ${green}, ${blue}, ${formatAlpha(alpha)})`;
+}
+
+export function rgbToHsv(color: Pick<ParsedColor, "red" | "green" | "blue">): HsvColor {
+ const red = clampChannel(color.red) / 255;
+ const green = clampChannel(color.green) / 255;
+ const blue = clampChannel(color.blue) / 255;
+ const max = Math.max(red, green, blue);
+ const min = Math.min(red, green, blue);
+ const delta = max - min;
+
+ let hue = 0;
+ if (delta !== 0) {
+ if (max === red) {
+ hue = 60 * (((green - blue) / delta) % 6);
+ } else if (max === green) {
+ hue = 60 * ((blue - red) / delta + 2);
+ } else {
+ hue = 60 * ((red - green) / delta + 4);
+ }
+ }
+
+ if (hue < 0) hue += 360;
+
+ return {
+ hue,
+ saturation: max === 0 ? 0 : delta / max,
+ value: max,
+ };
+}
+
+export function hsvToRgb(color: HsvColor): Pick<ParsedColor, "red" | "green" | "blue"> {
+ const hue = (((color.hue % 360) + 360) % 360) / 60;
+ const saturation = Math.max(0, Math.min(1, color.saturation));
+ const value = Math.max(0, Math.min(1, color.value));
+ const chroma = value * saturation;
+ const x = chroma * (1 - Math.abs((hue % 2) - 1));
+ const m = value - chroma;
+
+ let red = 0;
+ let green = 0;
+ let blue = 0;
+
+ if (hue >= 0 && hue < 1) {
+ red = chroma;
+ green = x;
+ } else if (hue >= 1 && hue < 2) {
+ red = x;
+ green = chroma;
+ } else if (hue >= 2 && hue < 3) {
+ green = chroma;
+ blue = x;
+ } else if (hue >= 3 && hue < 4) {
+ green = x;
+ blue = chroma;
+ } else if (hue >= 4 && hue < 5) {
+ red = x;
+ blue = chroma;
+ } else {
+ red = chroma;
+ blue = x;
+ }
+
+ return {
+ red: clampChannel((red + m) * 255),
+ green: clampChannel((green + m) * 255),
+ blue: clampChannel((blue + m) * 255),
+ };
+}
+
+export function mergeColorWithExistingAlpha(nextHex: string, previousValue: string): string {
+ const hex = nextHex.trim();
+ const match = hex.match(/^#([0-9a-f]{6})$/i);
+ if (!match) return previousValue;
+
+ const previous = parseCssColor(previousValue);
+ const red = Number.parseInt(match[1].slice(0, 2), 16);
+ const green = Number.parseInt(match[1].slice(2, 4), 16);
+ const blue = Number.parseInt(match[1].slice(4, 6), 16);
+ const alpha = previous?.alpha ?? 1;
+
+ return formatCssColor({ red, green, blue, alpha });
+}
diff --git a/packages/studio/src/components/editor/domEditing.test.ts b/packages/studio/src/components/editor/domEditing.test.ts
new file mode 100644
index 0000000000..f68ff51919
--- /dev/null
+++ b/packages/studio/src/components/editor/domEditing.test.ts
@@ -0,0 +1,669 @@
+import { describe, expect, it } from "vitest";
+import { Window } from "happy-dom";
+import {
+ buildDomEditStylePatchOperation,
+ buildElementAgentPrompt,
+ findElementForSelection,
+ getDomEditNonEditableReason,
+ getDomEditTargetKey,
+ isTextEditableSelection,
+ serializeDomEditTextFields,
+ type DomEditSelection,
+ resolveDomEditCapabilities,
+ resolveDomEditSelection,
+} from "./domEditing";
+
+function createDocument(markup: string): Document {
+ const window = new Window();
+ Object.assign(window, { SyntaxError });
+ window.document.body.innerHTML = markup;
+ return window.document;
+}
+
+describe("resolveDomEditCapabilities", () => {
+ it("marks absolute px-positioned layers as movable and resizable", () => {
+ expect(
+ resolveDomEditCapabilities({
+ selector: "#card",
+ inlineStyles: {
+ left: "120px",
+ top: "80px",
+ width: "240px",
+ height: "140px",
+ },
+ computedStyles: {
+ position: "absolute",
+ left: "120px",
+ top: "80px",
+ width: "240px",
+ height: "140px",
+ transform: "none",
+ },
+ isCompositionHost: false,
+ isMasterView: false,
+ }),
+ ).toEqual({
+ canSelect: true,
+ canEditStyles: true,
+ canMove: true,
+ canResize: true,
+ canApplyManualOffset: true,
+ canApplyManualSize: true,
+ canApplyManualRotation: true,
+ reasonIfDisabled: undefined,
+ });
+ });
+
+ it("rejects flex/grid children for move and resize", () => {
+ expect(
+ resolveDomEditCapabilities({
+ selector: "#chip",
+ tagName: "div",
+ inlineStyles: {},
+ computedStyles: {
+ position: "static",
+ display: "block",
+ left: "auto",
+ top: "auto",
+ width: "180px",
+ height: "64px",
+ transform: "none",
+ },
+ isCompositionHost: false,
+ isMasterView: false,
+ }),
+ ).toMatchObject({
+ canSelect: true,
+ canEditStyles: true,
+ canMove: false,
+ canResize: false,
+ canApplyManualOffset: true,
+ canApplyManualSize: true,
+ canApplyManualRotation: true,
+ reasonIfDisabled: undefined,
+ });
+ });
+
+ it("rejects transform-driven geometry", () => {
+ expect(
+ resolveDomEditCapabilities({
+ selector: "#card",
+ inlineStyles: {
+ left: "120px",
+ top: "80px",
+ width: "240px",
+ height: "140px",
+ },
+ computedStyles: {
+ position: "absolute",
+ left: "120px",
+ top: "80px",
+ width: "240px",
+ height: "140px",
+ transform: "matrix(1, 0, 0, 1, 12, 0)",
+ },
+ isCompositionHost: false,
+ isMasterView: false,
+ }),
+ ).toMatchObject({
+ canMove: false,
+ canResize: false,
+ canApplyManualOffset: true,
+ canApplyManualSize: true,
+ canApplyManualRotation: true,
+ });
+ });
+
+ it("treats identity transforms left behind by animation libraries as movable", () => {
+ expect(
+ resolveDomEditCapabilities({
+ selector: "#card",
+ inlineStyles: {
+ left: "120px",
+ top: "80px",
+ width: "240px",
+ height: "140px",
+ },
+ computedStyles: {
+ position: "absolute",
+ left: "120px",
+ top: "80px",
+ width: "240px",
+ height: "140px",
+ transform: "matrix(1, 0, 0, 1, 0, 0)",
+ },
+ isCompositionHost: false,
+ isMasterView: false,
+ }),
+ ).toMatchObject({
+ canMove: true,
+ canResize: true,
+ canApplyManualOffset: true,
+ });
+ });
+
+ it("treats identity matrix3d transforms as movable", () => {
+ expect(
+ resolveDomEditCapabilities({
+ selector: "#card",
+ inlineStyles: {
+ left: "120px",
+ top: "80px",
+ width: "240px",
+ height: "140px",
+ },
+ computedStyles: {
+ position: "absolute",
+ left: "120px",
+ top: "80px",
+ width: "240px",
+ height: "140px",
+ transform: "matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)",
+ },
+ isCompositionHost: false,
+ isMasterView: false,
+ }),
+ ).toMatchObject({
+ canMove: true,
+ canResize: true,
+ });
+ });
+
+ it("allows imported absolute media to resize from computed px geometry", () => {
+ expect(
+ resolveDomEditCapabilities({
+ selector: "#photo",
+ inlineStyles: {
+ inset: "0",
+ width: "100%",
+ height: "100%",
+ },
+ computedStyles: {
+ position: "absolute",
+ left: "0px",
+ top: "0px",
+ width: "330px",
+ height: "228px",
+ transform: "none",
+ },
+ isCompositionHost: false,
+ isMasterView: false,
+ }),
+ ).toMatchObject({
+ canMove: true,
+ canResize: true,
+ });
+ });
+});
+
+describe("resolveDomEditSelection", () => {
+ it("keeps composition host transforms disabled in master view", () => {
+ expect(
+ resolveDomEditCapabilities({
+ selector: "#detail-host",
+ inlineStyles: {
+ left: "80px",
+ top: "60px",
+ width: "320px",
+ height: "220px",
+ },
+ computedStyles: {
+ position: "absolute",
+ left: "80px",
+ top: "60px",
+ width: "320px",
+ height: "220px",
+ transform: "none",
+ },
+ isCompositionHost: true,
+ isMasterView: true,
+ }),
+ ).toEqual({
+ canSelect: true,
+ canEditStyles: false,
+ canMove: true,
+ canResize: true,
+ canApplyManualOffset: false,
+ canApplyManualSize: false,
+ canApplyManualRotation: false,
+ reasonIfDisabled: "Select an internal layer to transform it.",
+ });
+ });
+
+ it("resolves child clicks inside a composition host to the child in master view", () => {
+ const document = createDocument(`
+ <div data-composition-id="main">
+ <div
+ id="detail-host"
+ class="clip"
+ data-composition-id="detail-card"
+ data-composition-file="compositions/detail-card.html"
+ >
+ <span id="inner-copy">Nested scene</span>
+ </div>
+ </div>
+ `);
+
+ const child = document.getElementById("inner-copy") as HTMLElement;
+ const selection = resolveDomEditSelection(child, {
+ activeCompositionPath: null,
+ isMasterView: true,
+ });
+
+ expect(selection?.id).toBe("inner-copy");
+ expect(selection?.sourceFile).toBe("compositions/detail-card.html");
+ expect(selection?.isCompositionHost).toBe(false);
+ expect(selection?.capabilities.canApplyManualOffset).toBe(true);
+ expect(selection?.capabilities.canEditStyles).toBe(true);
+ });
+
+ it("does not prefer a scene host clip ancestor when selecting inside it", () => {
+ const document = createDocument(`
+ <div data-composition-id="main">
+ <div
+ id="detail-host"
+ class="clip"
+ data-composition-id="detail-card"
+ data-composition-file="compositions/detail-card.html"
+ >
+ <span id="inner-copy">Nested scene</span>
+ </div>
+ </div>
+ `);
+
+ const child = document.getElementById("inner-copy") as HTMLElement;
+ const selection = resolveDomEditSelection(child, {
+ activeCompositionPath: null,
+ isMasterView: true,
+ preferClipAncestor: true,
+ });
+
+ expect(selection?.id).toBe("inner-copy");
+ expect(selection?.sourceFile).toBe("compositions/detail-card.html");
+ expect(selection?.isCompositionHost).toBe(false);
+ });
+
+ it("still prefers an internal clip ancestor inside a scene", () => {
+ const document = createDocument(`
+ <div data-composition-id="main">
+ <div
+ id="detail-host"
+ class="clip"
+ data-composition-id="detail-card"
+ data-composition-file="compositions/detail-card.html"
+ >
+ <section id="nested-card" class="clip">
+ <span id="inner-copy">Nested scene</span>
+ </section>
+ </div>
+ </div>
+ `);
+
+ const child = document.getElementById("inner-copy") as HTMLElement;
+ const selection = resolveDomEditSelection(child, {
+ activeCompositionPath: null,
+ isMasterView: true,
+ preferClipAncestor: true,
+ });
+
+ expect(selection?.id).toBe("nested-card");
+ expect(selection?.sourceFile).toBe("compositions/detail-card.html");
+ expect(selection?.isCompositionHost).toBe(false);
+ });
+
+ it("scopes class selector indexing to the same source file", () => {
+ const document = createDocument(`
+ <div data-composition-id="main">
+ <div class="chip">Root chip</div>
+ <div data-composition-id="nested" data-composition-file="compositions/nested.html">
+ <div class="chip">Nested chip</div>
+ </div>
+ </div>
+ `);
+
+ const rootChip = document.getElementsByClassName("chip")[0] as HTMLElement;
+ const selection = resolveDomEditSelection(rootChip, {
+ activeCompositionPath: null,
+ isMasterView: true,
+ });
+
+ expect(selection?.sourceFile).toBe("index.html");
+ expect(selection?.selector).toBe(".chip");
+ expect(selection?.selectorIndex).toBe(0);
+ expect(findElementForSelection(document, selection!, null)).toBe(rootChip);
+ });
+
+ it("resolves nested duplicate ids from master view without treating root as the nested source", () => {
+ const document = createDocument(`
+ <div data-composition-id="main">
+ <div id="card">Root card</div>
+ <div data-composition-id="nested" data-composition-file="scenes/nested.html">
+ <div id="card">Nested card</div>
+ </div>
+ </div>
+ `);
+
+ const nestedCard = document.querySelector(
+ '[data-composition-file="scenes/nested.html"] #card',
+ ) as HTMLElement;
+ const selection = resolveDomEditSelection(nestedCard, {
+ activeCompositionPath: null,
+ isMasterView: true,
+ });
+
+ expect(selection?.sourceFile).toBe("scenes/nested.html");
+ expect(findElementForSelection(document, selection!, null)).toBe(nestedCard);
+ });
+
+ it("prefers the nearest clip ancestor on single-click style selection", () => {
+ const document = createDocument(`
+ <section id="card" class="clip" style="left: 10px; top: 20px; width: 200px; height: 100px; position: absolute;">
+ <p id="copy">Hello</p>
+ </section>
+ `);
+
+ const child = document.getElementById("copy") as HTMLElement;
+ const selection = resolveDomEditSelection(child, {
+ activeCompositionPath: null,
+ isMasterView: false,
+ preferClipAncestor: true,
+ });
+
+ expect(selection?.id).toBe("card");
+ expect(selection?.selector).toBe("#card");
+ });
+
+ it("can resolve the exact child when clip-ancestor preference is disabled", () => {
+ const document = createDocument(`
+ <section id="card" class="clip" style="left: 10px; top: 20px; width: 200px; height: 100px; position: absolute;">
+ <p id="copy">Hello</p>
+ </section>
+ `);
+
+ const child = document.getElementById("copy") as HTMLElement;
+ const selection = resolveDomEditSelection(child, {
+ activeCompositionPath: null,
+ isMasterView: false,
+ preferClipAncestor: false,
+ });
+
+ expect(selection?.id).toBe("copy");
+ expect(selection?.selector).toBe("#copy");
+ });
+
+ it("collects simple child text blocks as separate editable fields", () => {
+ const document = createDocument(`
+ <section id="card" class="clip" style="left: 10px; top: 20px; width: 200px; height: 100px; position: absolute;">
+ <strong>Headline</strong>
+ <span>Supporting copy</span>
+ </section>
+ `);
+
+ const selection = resolveDomEditSelection(document.getElementById("card") as HTMLElement, {
+ activeCompositionPath: null,
+ isMasterView: false,
+ });
+
+ expect(selection?.textFields.map((field) => field.label)).toEqual(["Text 1", "Text 2"]);
+ expect(selection?.textFields.map((field) => field.value)).toEqual([
+ "Headline",
+ "Supporting copy",
+ ]);
+ });
+
+ it("preserves user-entered text spacing in editable text fields", () => {
+ const document = createDocument(`
+ <section id="card" class="clip" style="position: absolute;">
+ <strong>Headline with trailing space </strong>
+ </section>
+ `);
+
+ const selection = resolveDomEditSelection(document.getElementById("card") as HTMLElement, {
+ activeCompositionPath: null,
+ isMasterView: false,
+ });
+
+ expect(selection?.textFields[0]?.value).toBe("Headline with trailing space ");
+ });
+
+ it("keeps an emptied text layer editable so users can type into it again", () => {
+ const document = createDocument(`
+ <div id="card" class="clip" style="position: absolute;"></div>
+ `);
+
+ const selection = resolveDomEditSelection(document.getElementById("card") as HTMLElement, {
+ activeCompositionPath: null,
+ isMasterView: false,
+ });
+
+ expect(selection?.textFields).toMatchObject([
+ {
+ key: "self:0:div",
+ label: "Content",
+ value: "",
+ source: "self",
+ },
+ ]);
+ expect(selection ? isTextEditableSelection(selection) : false).toBe(true);
+ });
+
+ it("keeps emptied child text layers editable after their content is cleared", () => {
+ const document = createDocument(`
+ <div id="card" class="clip" style="position: absolute;">
+ <strong></strong>
+ <span></span>
+ </div>
+ `);
+
+ const selection = resolveDomEditSelection(document.getElementById("card") as HTMLElement, {
+ activeCompositionPath: null,
+ isMasterView: false,
+ });
+
+ expect(selection?.textFields.map((field) => field.tagName)).toEqual(["strong", "span"]);
+ expect(selection?.textFields.map((field) => field.value)).toEqual(["", ""]);
+ });
+
+ it("explains anonymous child elements that resolve to an editable parent", () => {
+ const document = createDocument(`
+ <div data-composition-id="main">
+ <div id="card">
+ <strong>Headline</strong>
+ </div>
+ </div>
+ `);
+
+ const child = document.querySelector("strong") as HTMLElement;
+ const selection = resolveDomEditSelection(child, {
+ activeCompositionPath: null,
+ isMasterView: false,
+ preferClipAncestor: false,
+ });
+
+ expect(selection?.id).toBe("card");
+ expect(getDomEditNonEditableReason(child, selection)).toBe("Selection resolves to Card");
+ });
+
+ it("does not mark an element as non-editable when Studio can edit it directly", () => {
+ const document = createDocument(`
+ <div data-composition-id="main">
+ <div id="card">Editable</div>
+ </div>
+ `);
+
+ const element = document.getElementById("card") as HTMLElement;
+ const selection = resolveDomEditSelection(element, {
+ activeCompositionPath: null,
+ isMasterView: false,
+ });
+
+ expect(getDomEditNonEditableReason(element, selection)).toBeNull();
+ });
+
+ it("keeps duplicate class targets distinct for history keys", () => {
+ const first = getDomEditTargetKey({
+ sourceFile: "index.html",
+ selector: ".card",
+ selectorIndex: 0,
+ });
+ const second = getDomEditTargetKey({
+ sourceFile: "index.html",
+ selector: ".card",
+ selectorIndex: 1,
+ });
+
+ expect(first).not.toBe(second);
+ });
+});
+
+describe("patch builders and prompt builder", () => {
+ it("builds style patch operations", () => {
+ expect(buildDomEditStylePatchOperation("background-color", "rgb(15, 23, 42)")).toEqual({
+ type: "inline-style",
+ property: "background-color",
+ value: "rgb(15, 23, 42)",
+ });
+ });
+
+ it("builds an agent prompt with source and selector context", () => {
+ const selection = {
+ element: {} as HTMLElement,
+ id: "editable-card",
+ selector: "#editable-card",
+ selectorIndex: undefined,
+ sourceFile: "index.html",
+ compositionPath: "index.html",
+ compositionSrc: undefined,
+ isCompositionHost: false,
+ label: "Drag me first",
+ tagName: "div",
+ boundingBox: { x: 108, y: 112, width: 380, height: 196 },
+ textContent: "Drag me first",
+ dataAttributes: {},
+ inlineStyles: {
+ left: "108px",
+ top: "112px",
+ width: "380px",
+ height: "196px",
+ },
+ computedStyles: {
+ position: "absolute",
+ left: "108px",
+ top: "112px",
+ width: "380px",
+ height: "196px",
+ color: "rgb(248, 250, 252)",
+ },
+ textFields: [
+ {
+ key: "self:0:div",
+ label: "Content",
+ value: "Drag me first",
+ tagName: "div",
+ attributes: [],
+ inlineStyles: {},
+ computedStyles: {},
+ source: "self",
+ },
+ ],
+ capabilities: {
+ canSelect: true,
+ canEditStyles: true,
+ canMove: true,
+ canResize: true,
+ canApplyManualOffset: true,
+ canApplyManualSize: true,
+ canApplyManualRotation: true,
+ },
+ } satisfies DomEditSelection;
+
+ const prompt = buildElementAgentPrompt({
+ selection,
+ currentTime: 1.25,
+ tagSnippet: `<div id="editable-card" style="position:absolute; left: 108px; top: 112px; width: 380px; height: 196px; color: rgb(248, 250, 252)"`,
+ });
+
+ expect(prompt).toContain("## HyperFrames element edit request v1");
+ expect(prompt).toContain("Schema version: 1");
+ expect(prompt).toContain("Source file: index.html");
+ expect(prompt).toContain("Selector: #editable-card");
+ expect(prompt).toContain("Playback time:");
+ expect(prompt).toContain("Text fields:");
+ expect(prompt).toContain('key=self:0:div; tag=<div>; source=self; text="Drag me first"');
+ expect(prompt).toContain("Inline styles:");
+ expect(prompt).toContain("Computed styles (browser-resolved):");
+ expect(prompt).toContain("Target HTML:");
+ expect(prompt).toContain("Guardrails:");
+ expect(prompt).toContain("Do not modify other elements' data-* attributes or positioning.");
+ });
+
+ it("uses an absolute source path in copied agent prompts when provided", () => {
+ const selection = {
+ element: {} as HTMLElement,
+ id: "editable-card",
+ selector: "#editable-card",
+ selectorIndex: undefined,
+ sourceFile: "index.html",
+ compositionPath: "index.html",
+ compositionSrc: undefined,
+ isCompositionHost: false,
+ label: "Drag me first",
+ tagName: "div",
+ boundingBox: { x: 108, y: 112, width: 380, height: 196 },
+ textContent: "Drag me first",
+ dataAttributes: {},
+ inlineStyles: {},
+ computedStyles: {},
+ textFields: [],
+ capabilities: {
+ canSelect: true,
+ canEditStyles: true,
+ canMove: true,
+ canResize: true,
+ canApplyManualOffset: true,
+ canApplyManualSize: true,
+ canApplyManualRotation: true,
+ },
+ } satisfies DomEditSelection;
+
+ const prompt = buildElementAgentPrompt({
+ selection,
+ currentTime: 1.25,
+ sourceFilePath: "/tmp/hf-studio-project/index.html",
+ });
+
+ expect(prompt).toContain("Source file: /tmp/hf-studio-project/index.html");
+ expect(prompt).not.toContain("Source file: index.html");
+ });
+
+ it("serializes child text fields back into HTML", () => {
+ expect(
+ serializeDomEditTextFields([
+ {
+ key: "child:0:strong",
+ label: "Text 1",
+ value: "Headline <1>",
+ tagName: "strong",
+ attributes: [],
+ inlineStyles: {
+ "font-size": "22px",
+ },
+ computedStyles: {},
+ source: "child",
+ },
+ {
+ key: "child:1:span",
+ label: "Text 2",
+ value: "Details & more",
+ tagName: "span",
+ attributes: [],
+ inlineStyles: {},
+ computedStyles: {},
+ source: "child",
+ },
+ ]),
+ ).toBe(
+ '<strong data-hf-text-key="child:0:strong" style="font-size: 22px">Headline &lt;1&gt;</strong><span data-hf-text-key="child:1:span">Details &amp; more</span>',
+ );
+ });
+});
diff --git a/packages/studio/src/components/editor/domEditing.ts b/packages/studio/src/components/editor/domEditing.ts
new file mode 100644
index 0000000000..c9a5156b4e
--- /dev/null
+++ b/packages/studio/src/components/editor/domEditing.ts
@@ -0,0 +1,733 @@
+import { formatTime } from "../../player/lib/time";
+import type { PatchOperation, PatchTarget } from "../../utils/sourcePatcher";
+
+const CURATED_STYLE_PROPERTIES = [
+ "position",
+ "display",
+ "top",
+ "left",
+ "right",
+ "bottom",
+ "inset",
+ "width",
+ "height",
+ "gap",
+ "justify-content",
+ "align-items",
+ "flex-direction",
+ "font-size",
+ "font-weight",
+ "font-family",
+ "color",
+ "background-color",
+ "background-image",
+ "opacity",
+ "mix-blend-mode",
+ "border-radius",
+ "border-color",
+ "outline-color",
+ "overflow",
+ "box-shadow",
+ "z-index",
+ "transform",
+] as const;
+
+export interface DomEditCapabilities {
+ canSelect: boolean;
+ canEditStyles: boolean;
+ /** Directly editable authored left/top style fields. Canvas drag uses manual edits instead. */
+ canMove: boolean;
+ /** Directly editable authored width/height style fields. Canvas resize uses manual edits instead. */
+ canResize: boolean;
+ canApplyManualOffset: boolean;
+ canApplyManualSize: boolean;
+ canApplyManualRotation: boolean;
+ reasonIfDisabled?: string;
+}
+
+export interface DomEditTextField {
+ key: string;
+ label: string;
+ value: string;
+ tagName: string;
+ attributes: Array<{ name: string; value: string }>;
+ inlineStyles: Record<string, string>;
+ computedStyles: Record<string, string>;
+ source: "self" | "child";
+}
+
+export interface DomEditSelection extends PatchTarget {
+ element: HTMLElement;
+ label: string;
+ tagName: string;
+ sourceFile: string;
+ compositionPath: string;
+ compositionSrc?: string;
+ isCompositionHost: boolean;
+ boundingBox: { x: number; y: number; width: number; height: number };
+ textContent: string | null;
+ dataAttributes: Record<string, string>;
+ inlineStyles: Record<string, string>;
+ computedStyles: Record<string, string>;
+ textFields: DomEditTextField[];
+ capabilities: DomEditCapabilities;
+}
+
+export interface DomEditContextOptions {
+ activeCompositionPath: string | null;
+ isMasterView: boolean;
+ preferClipAncestor?: boolean;
+}
+
+function isHtmlElement(value: unknown): value is HTMLElement {
+ return (
+ typeof value === "object" &&
+ value !== null &&
+ "nodeType" in value &&
+ typeof (value as { nodeType?: unknown }).nodeType === "number" &&
+ (value as { nodeType: number }).nodeType === 1
+ );
+}
+
+function parsePx(value: string | undefined): number | null {
+ if (!value) return null;
+ const trimmed = value.trim();
+ if (!trimmed.endsWith("px")) return null;
+ const parsed = parseFloat(trimmed);
+ return Number.isFinite(parsed) ? parsed : null;
+}
+
+function isIdentityTransform(value: string | undefined): boolean {
+ const transform = (value ?? "none").trim();
+ if (!transform || transform === "none") return true;
+
+ const matrix = transform.match(/^matrix\(([^)]+)\)$/i);
+ if (matrix) {
+ const values = matrix[1].split(",").map((part) => Number.parseFloat(part.trim()));
+ if (values.length !== 6 || values.some((part) => !Number.isFinite(part))) return false;
+ return (
+ Math.abs(values[0] - 1) < 0.0001 &&
+ Math.abs(values[1]) < 0.0001 &&
+ Math.abs(values[2]) < 0.0001 &&
+ Math.abs(values[3] - 1) < 0.0001 &&
+ Math.abs(values[4]) < 0.0001 &&
+ Math.abs(values[5]) < 0.0001
+ );
+ }
+
+ const matrix3d = transform.match(/^matrix3d\(([^)]+)\)$/i);
+ if (!matrix3d) return false;
+ const values = matrix3d[1].split(",").map((part) => Number.parseFloat(part.trim()));
+ if (values.length !== 16 || values.some((part) => !Number.isFinite(part))) return false;
+ const identity = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
+ return values.every((part, index) => Math.abs(part - identity[index]) < 0.0001);
+}
+
+function isTextBearingTag(tagName: string): boolean {
+ return ["div", "span", "p", "strong", "h1", "h2", "h3", "h4", "h5", "h6"].includes(tagName);
+}
+
+function getCuratedComputedStyles(el: HTMLElement): Record<string, string> {
+ const styles: Record<string, string> = {};
+ const computed = el.ownerDocument.defaultView?.getComputedStyle(el);
+ if (!computed) return styles;
+
+ for (const prop of CURATED_STYLE_PROPERTIES) {
+ const value = computed.getPropertyValue(prop);
+ if (value) styles[prop] = value;
+ }
+
+ return styles;
+}
+
+function findClosestByAttribute(el: HTMLElement, attributeNames: string[]): HTMLElement | null {
+ let current: HTMLElement | null = el;
+ while (current) {
+ const candidate = current;
+ if (attributeNames.some((attribute) => candidate.hasAttribute(attribute))) {
+ return candidate;
+ }
+ current = current.parentElement;
+ }
+ return null;
+}
+
+function getSourceFileForElement(
+ el: HTMLElement,
+ activeCompositionPath: string | null,
+): { sourceFile: string; compositionPath: string } {
+ const sourceHost = findClosestByAttribute(el, ["data-composition-file", "data-composition-src"]);
+ const ownerRoot = findClosestByAttribute(el, ["data-composition-id"]);
+ const sourceFile =
+ sourceHost?.getAttribute("data-composition-file") ??
+ sourceHost?.getAttribute("data-composition-src") ??
+ ownerRoot?.getAttribute("data-composition-file") ??
+ ownerRoot?.getAttribute("data-composition-src") ??
+ activeCompositionPath ??
+ "index.html";
+
+ return {
+ sourceFile,
+ compositionPath: sourceFile,
+ };
+}
+
+function getPreferredClipAncestor(startEl: HTMLElement): HTMLElement | null {
+ let current: HTMLElement | null = startEl;
+ while (current) {
+ if (current.classList.contains("clip")) {
+ const isCompositionHost =
+ current.hasAttribute("data-composition-src") ||
+ current.hasAttribute("data-composition-file");
+ if (!isCompositionHost || current === startEl) return current;
+ }
+ current = current.parentElement;
+ }
+ return null;
+}
+
+function getSelectionCandidate(startEl: HTMLElement, options: DomEditContextOptions): HTMLElement {
+ if (options.preferClipAncestor) {
+ const clipAncestor = getPreferredClipAncestor(startEl);
+ if (clipAncestor) {
+ return clipAncestor;
+ }
+ }
+
+ return startEl;
+}
+
+function getPreferredClassSelector(el: HTMLElement): string | undefined {
+ const classes = el.className
+ .split(/\s+/)
+ .map((value) => value.trim())
+ .filter(Boolean);
+ if (classes.length === 0) return undefined;
+ const preferred =
+ classes.find((value) => value !== "clip" && !value.startsWith("__hf-")) ?? classes[0];
+ return preferred ? `.${preferred}` : undefined;
+}
+
+function humanizeIdentifier(value: string): string {
+ return (
+ value
+ .replace(/\.html$/i, "")
+ .replace(/^compositions\//i, "")
+ .split("/")
+ .at(-1)
+ ?.replace(/[-_]+/g, " ")
+ .replace(/\b\w/g, (char) => char.toUpperCase()) ?? value
+ );
+}
+
+function buildStableSelector(el: HTMLElement): string | undefined {
+ if (el.id) return `#${el.id}`;
+
+ const compositionId = el.getAttribute("data-composition-id");
+ if (compositionId) return `[data-composition-id="${compositionId}"]`;
+
+ return getPreferredClassSelector(el);
+}
+
+function getSelectorIndex(
+ doc: Document,
+ el: HTMLElement,
+ selector: string | undefined,
+ sourceFile: string,
+ activeCompositionPath: string | null,
+): number | undefined {
+ if (!selector?.startsWith(".")) return undefined;
+
+ const candidates = Array.from(doc.querySelectorAll(selector)).filter(
+ (candidate): candidate is HTMLElement =>
+ isHtmlElement(candidate) &&
+ getSourceFileForElement(candidate, activeCompositionPath).sourceFile === sourceFile,
+ );
+ const index = candidates.indexOf(el);
+ return index >= 0 ? index : undefined;
+}
+
+function buildElementLabel(el: HTMLElement): string {
+ const compositionId = el.getAttribute("data-composition-id");
+ if (compositionId && compositionId !== "main") {
+ return humanizeIdentifier(compositionId);
+ }
+
+ const compositionSrc =
+ el.getAttribute("data-composition-src") ?? el.getAttribute("data-composition-file");
+ if (compositionSrc) {
+ return humanizeIdentifier(compositionSrc);
+ }
+
+ if (el.id) return humanizeIdentifier(el.id);
+
+ const preferredClass = getPreferredClassSelector(el);
+ if (preferredClass) {
+ return humanizeIdentifier(preferredClass.replace(/^\./, ""));
+ }
+
+ const text = (el.textContent ?? "").trim().replace(/\s+/g, " ");
+ if (text) return text.length > 40 ? `${text.slice(0, 39)}…` : text;
+ return el.tagName.toLowerCase();
+}
+
+function getDataAttributes(el: HTMLElement): Record<string, string> {
+ const attrs: Record<string, string> = {};
+ for (const attr of el.attributes) {
+ if (attr.name.startsWith("data-")) {
+ attrs[attr.name.slice(5)] = attr.value;
+ }
+ }
+ return attrs;
+}
+
+function getInlineStyles(el: HTMLElement): Record<string, string> {
+ const styles: Record<string, string> = {};
+ for (const property of CURATED_STYLE_PROPERTIES) {
+ const value = el.style.getPropertyValue(property);
+ if (value) styles[property] = value;
+ }
+ return styles;
+}
+
+function isEditableTextLeaf(el: HTMLElement): boolean {
+ return isTextBearingTag(el.tagName.toLowerCase()) && el.children.length === 0;
+}
+
+function getTextFieldLabel(
+ _tagName: string,
+ index: number,
+ total: number,
+ source: "self" | "child",
+): string {
+ if (source === "self" || total === 1) return "Content";
+ return `Text ${index + 1}`;
+}
+
+function buildTextField(
+ el: HTMLElement,
+ index: number,
+ total: number,
+ source: "self" | "child",
+): DomEditTextField {
+ const tagName = el.tagName.toLowerCase();
+ const key = el.getAttribute("data-hf-text-key") ?? `${source}:${index}:${tagName}`;
+ return {
+ key,
+ label: getTextFieldLabel(tagName, index, total, source),
+ value: el.textContent ?? "",
+ tagName,
+ attributes: Array.from(el.attributes)
+ .filter((attribute) => attribute.name !== "style")
+ .map((attribute) => ({
+ name: attribute.name,
+ value: attribute.value,
+ })),
+ inlineStyles: getInlineStyles(el),
+ computedStyles: getCuratedComputedStyles(el),
+ source,
+ };
+}
+
+function collectDomEditTextFields(el: HTMLElement): DomEditTextField[] {
+ const childFields = Array.from(el.children).filter(isHtmlElement).filter(isEditableTextLeaf);
+ if (childFields.length > 0) {
+ return childFields.map((child, index) =>
+ buildTextField(child, index, childFields.length, "child"),
+ );
+ }
+
+ if (isEditableTextLeaf(el)) {
+ return [buildTextField(el, 0, 1, "self")];
+ }
+
+ return [];
+}
+
+function escapeHtmlText(value: string): string {
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
+}
+
+function serializeTextFieldStyle(field: DomEditTextField): string {
+ const entries = Object.entries(field.inlineStyles).filter(([, value]) => Boolean(value));
+ if (entries.length === 0) return "";
+ return entries.map(([key, value]) => `${key}: ${value}`).join("; ");
+}
+
+export function serializeDomEditTextFields(fields: DomEditTextField[]): string {
+ return fields
+ .filter((field) => field.source === "child")
+ .map((field) => {
+ const attrs = [
+ ...field.attributes.filter((attribute) => attribute.name !== "data-hf-text-key"),
+ { name: "data-hf-text-key", value: field.key },
+ ]
+ .map((attribute) => ` ${attribute.name}="${attribute.value.replace(/"/g, "&quot;")}"`)
+ .join("");
+ const style = serializeTextFieldStyle(field);
+ const styleAttr = style ? ` style="${style.replace(/"/g, "&quot;")}"` : "";
+ return `<${field.tagName}${attrs}${styleAttr}>${escapeHtmlText(field.value)}</${field.tagName}>`;
+ })
+ .join("");
+}
+
+export function buildDefaultDomEditTextField(base?: Partial<DomEditTextField>): DomEditTextField {
+ return {
+ key: `child:new:${Date.now()}`,
+ label: "Text",
+ value: "New text",
+ tagName: "span",
+ attributes: [],
+ inlineStyles: {
+ "font-family": base?.computedStyles?.["font-family"] ?? "inherit",
+ "font-size": base?.computedStyles?.["font-size"] ?? "16px",
+ "font-weight": base?.computedStyles?.["font-weight"] ?? "400",
+ color: base?.computedStyles?.color ?? "inherit",
+ },
+ computedStyles: {},
+ source: "child",
+ };
+}
+
+export function resolveDomEditCapabilities(args: {
+ selector?: string;
+ tagName?: string;
+ className?: string;
+ inlineStyles: Record<string, string>;
+ computedStyles: Record<string, string>;
+ isCompositionHost: boolean;
+ isMasterView: boolean;
+}): DomEditCapabilities {
+ if (!args.selector) {
+ return {
+ canSelect: false,
+ canEditStyles: false,
+ canMove: false,
+ canResize: false,
+ canApplyManualOffset: false,
+ canApplyManualSize: false,
+ canApplyManualRotation: false,
+ reasonIfDisabled: "Studio could not resolve a stable patch target for this element.",
+ };
+ }
+
+ const position = args.computedStyles.position;
+ const left = parsePx(args.inlineStyles.left) ?? parsePx(args.computedStyles.left);
+ const top = parsePx(args.inlineStyles.top) ?? parsePx(args.computedStyles.top);
+ const width = parsePx(args.inlineStyles.width) ?? parsePx(args.computedStyles.width);
+ const height = parsePx(args.inlineStyles.height) ?? parsePx(args.computedStyles.height);
+ const hasTransformDrivenGeometry = !isIdentityTransform(args.computedStyles.transform);
+
+ const canMove =
+ (position === "absolute" || position === "fixed") &&
+ left != null &&
+ top != null &&
+ !hasTransformDrivenGeometry;
+
+ const canResize = canMove && (width != null || height != null);
+ const canApplyManualGeometry = !args.isCompositionHost;
+ const canApplyManualOffset = canApplyManualGeometry;
+ const canApplyManualSize = canApplyManualGeometry;
+ const canApplyManualRotation = canApplyManualGeometry;
+ const reasonIfDisabled = canApplyManualGeometry
+ ? undefined
+ : "Select an internal layer to transform it.";
+
+ if (args.isCompositionHost && args.isMasterView) {
+ return {
+ canSelect: true,
+ canEditStyles: false,
+ canMove,
+ canResize,
+ canApplyManualOffset,
+ canApplyManualSize,
+ canApplyManualRotation,
+ reasonIfDisabled,
+ };
+ }
+
+ return {
+ canSelect: true,
+ canEditStyles: true,
+ canMove,
+ canResize,
+ canApplyManualOffset,
+ canApplyManualSize,
+ canApplyManualRotation,
+ reasonIfDisabled,
+ };
+}
+
+export function resolveDomEditSelection(
+ startEl: HTMLElement | null,
+ options: DomEditContextOptions,
+): DomEditSelection | null {
+ if (!startEl) return null;
+ const doc = startEl.ownerDocument;
+
+ let current: HTMLElement | null = getSelectionCandidate(startEl, options);
+ while (current && current !== doc.body && current !== doc.documentElement) {
+ const selector = buildStableSelector(current);
+ if (!selector) {
+ current = current.parentElement;
+ continue;
+ }
+
+ const { sourceFile, compositionPath } = getSourceFileForElement(
+ current,
+ options.activeCompositionPath,
+ );
+ const selectorIndex = getSelectorIndex(
+ doc,
+ current,
+ selector,
+ sourceFile,
+ options.activeCompositionPath,
+ );
+ const compositionSrc =
+ current.getAttribute("data-composition-src") ??
+ current.getAttribute("data-composition-file") ??
+ undefined;
+ const inlineStyles = getInlineStyles(current);
+ const computedStyles = getCuratedComputedStyles(current);
+ const textFields = collectDomEditTextFields(current);
+ const capabilities = resolveDomEditCapabilities({
+ selector,
+ tagName: current.tagName.toLowerCase(),
+ className: current.className,
+ inlineStyles,
+ computedStyles,
+ isCompositionHost: Boolean(compositionSrc),
+ isMasterView: options.isMasterView,
+ });
+ const rect = current.getBoundingClientRect();
+
+ return {
+ element: current,
+ id: current.id || undefined,
+ selector,
+ selectorIndex,
+ sourceFile,
+ compositionPath,
+ compositionSrc,
+ isCompositionHost: Boolean(compositionSrc),
+ label: buildElementLabel(current),
+ tagName: current.tagName.toLowerCase(),
+ boundingBox: {
+ x: rect.left,
+ y: rect.top,
+ width: rect.width,
+ height: rect.height,
+ },
+ textContent: current.textContent?.trim() || null,
+ dataAttributes: getDataAttributes(current),
+ inlineStyles,
+ computedStyles,
+ textFields,
+ capabilities,
+ };
+ }
+
+ return null;
+}
+
+export function refreshDomEditSelection(
+ selection: DomEditSelection,
+ activeCompositionPath: string | null,
+): DomEditSelection | null {
+ const doc = selection.element.ownerDocument;
+ const nextElement = findElementForSelection(doc, selection, activeCompositionPath);
+ return nextElement
+ ? resolveDomEditSelection(nextElement, {
+ activeCompositionPath,
+ isMasterView: !activeCompositionPath || activeCompositionPath === "index.html",
+ })
+ : null;
+}
+
+export function getDomEditTargetKey(
+ selection: Pick<DomEditSelection, "id" | "selector" | "selectorIndex" | "sourceFile">,
+): string {
+ return [
+ selection.sourceFile || "index.html",
+ selection.id ?? "",
+ selection.selector ?? "",
+ selection.selectorIndex ?? "",
+ ].join("|");
+}
+
+function hasSupportedDirectEdit(capabilities: DomEditCapabilities): boolean {
+ return (
+ capabilities.canEditStyles ||
+ capabilities.canMove ||
+ capabilities.canResize ||
+ capabilities.canApplyManualOffset ||
+ capabilities.canApplyManualSize ||
+ capabilities.canApplyManualRotation
+ );
+}
+
+export function getDomEditNonEditableReason(
+ element: HTMLElement,
+ selection: DomEditSelection | null,
+): string | null {
+ if (!selection) {
+ return "No stable source target";
+ }
+
+ if (selection.element !== element) {
+ return selection.isCompositionHost
+ ? "Nested composition boundary"
+ : `Selection resolves to ${selection.label}`;
+ }
+
+ if (!hasSupportedDirectEdit(selection.capabilities)) {
+ return selection.capabilities.reasonIfDisabled ?? "No supported direct edits";
+ }
+
+ return null;
+}
+
+export function findElementForSelection(
+ doc: Document,
+ selection: Pick<DomEditSelection, "id" | "selector" | "selectorIndex" | "sourceFile">,
+ activeCompositionPath: string | null = null,
+): HTMLElement | null {
+ if (selection.id) {
+ const byId = doc.getElementById(selection.id);
+ if (
+ isHtmlElement(byId) &&
+ (!selection.sourceFile ||
+ getSourceFileForElement(byId, activeCompositionPath).sourceFile === selection.sourceFile)
+ ) {
+ return byId;
+ }
+ }
+
+ if (!selection.selector) return null;
+
+ if (selection.selector.startsWith(".") && selection.selectorIndex != null) {
+ const matches = Array.from(doc.querySelectorAll(selection.selector)).filter(
+ (candidate): candidate is HTMLElement =>
+ isHtmlElement(candidate) &&
+ (!selection.sourceFile ||
+ getSourceFileForElement(candidate, activeCompositionPath).sourceFile ===
+ selection.sourceFile),
+ );
+ return matches[selection.selectorIndex] ?? null;
+ }
+
+ const matches = Array.from(doc.querySelectorAll(selection.selector)).filter(
+ (candidate): candidate is HTMLElement =>
+ isHtmlElement(candidate) &&
+ (!selection.sourceFile ||
+ getSourceFileForElement(candidate, activeCompositionPath).sourceFile ===
+ selection.sourceFile),
+ );
+ return matches[0] ?? null;
+}
+
+export function buildDomEditStylePatchOperation(property: string, value: string): PatchOperation {
+ return {
+ type: "inline-style",
+ property,
+ value,
+ };
+}
+
+export function buildDomEditTextPatchOperation(value: string): PatchOperation {
+ return {
+ type: "text-content",
+ property: "text",
+ value,
+ };
+}
+
+function formatBoundingBox(bounds: DomEditSelection["boundingBox"]): string {
+ return `x=${Math.round(bounds.x)}, y=${Math.round(bounds.y)}, width=${Math.round(bounds.width)}, height=${Math.round(bounds.height)}`;
+}
+
+function formatStyleBlock(styles: Record<string, string>): string {
+ return Object.entries(styles)
+ .filter(([, value]) => value && value !== "initial")
+ .map(([key, value]) => `${key}: ${value}`)
+ .join("\n");
+}
+
+function formatTextFields(fields: DomEditTextField[]): string {
+ return fields
+ .map(
+ (field) =>
+ `- key=${field.key}; tag=<${field.tagName}>; source=${field.source}; text=${JSON.stringify(field.value)}`,
+ )
+ .join("\n");
+}
+
+export function buildElementAgentPrompt({
+ selection,
+ currentTime,
+ tagSnippet,
+ userInstruction,
+ sourceFilePath,
+}: {
+ selection: DomEditSelection;
+ currentTime: number;
+ tagSnippet?: string;
+ userInstruction?: string;
+ sourceFilePath?: string;
+}): string {
+ const displayedSourceFile = sourceFilePath?.trim() || selection.sourceFile;
+ const lines = [
+ "## HyperFrames element edit request v1",
+ "Schema version: 1",
+ "",
+ userInstruction?.trim() || "Edit this selected HyperFrames element.",
+ "",
+ `Composition: ${selection.compositionPath}`,
+ `Playback time: ${formatTime(currentTime)}`,
+ `Source file: ${displayedSourceFile}`,
+ `DOM id: ${selection.id ?? "(none)"}`,
+ `Selector: ${selection.selector ?? "(none)"}`,
+ `Selector index: ${selection.selectorIndex ?? 0}`,
+ `Tag: <${selection.tagName}>`,
+ `Bounds: ${formatBoundingBox(selection.boundingBox)}`,
+ ];
+
+ if (selection.textContent) {
+ lines.push(`Text: ${selection.textContent}`);
+ }
+
+ const textFieldsBlock = formatTextFields(selection.textFields);
+ if (textFieldsBlock) {
+ lines.push("", "Text fields:", textFieldsBlock);
+ }
+
+ const inlineStyleBlock = formatStyleBlock(selection.inlineStyles);
+ if (inlineStyleBlock) {
+ lines.push("", "Inline styles:", inlineStyleBlock);
+ }
+
+ const computedStyleBlock = formatStyleBlock(selection.computedStyles);
+ if (computedStyleBlock) {
+ lines.push("", "Computed styles (browser-resolved):", computedStyleBlock);
+ }
+
+ if (tagSnippet) {
+ lines.push("", "Target HTML:", tagSnippet);
+ }
+
+ lines.push(
+ "",
+ "Guardrails:",
+ "- Make a targeted change to this element only.",
+ "- Preserve the rest of the composition and its timing.",
+ "- Do not modify other elements' data-* attributes or positioning.",
+ "- Prefer existing inline styles or existing CSS rules for this element over adding unrelated selectors.",
+ );
+
+ return lines.join("\n");
+}
+
+export function isTextEditableSelection(selection: DomEditSelection): boolean {
+ return selection.textFields.length > 0 && !selection.isCompositionHost;
+}
diff --git a/packages/studio/src/components/editor/floatingPanel.test.ts b/packages/studio/src/components/editor/floatingPanel.test.ts
new file mode 100644
index 0000000000..98145d6931
--- /dev/null
+++ b/packages/studio/src/components/editor/floatingPanel.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from "vitest";
+import { resolveFloatingPanelPosition } from "./floatingPanel";
+
+describe("resolveFloatingPanelPosition", () => {
+ it("places the panel below the anchor when there is space", () => {
+ expect(
+ resolveFloatingPanelPosition(
+ { left: 100, top: 100, right: 220, bottom: 140, width: 120, height: 40 },
+ { width: 800, height: 600 },
+ { width: 280, height: 220 },
+ ),
+ ).toMatchObject({ top: 148, placement: "bottom" });
+ });
+
+ it("places the panel above the anchor when the bottom would be clipped", () => {
+ expect(
+ resolveFloatingPanelPosition(
+ { left: 100, top: 500, right: 220, bottom: 540, width: 120, height: 40 },
+ { width: 800, height: 600 },
+ { width: 280, height: 220 },
+ ),
+ ).toMatchObject({ top: 272, placement: "top" });
+ });
+
+ it("clamps the panel horizontally inside the viewport", () => {
+ expect(
+ resolveFloatingPanelPosition(
+ { left: 760, top: 100, right: 800, bottom: 140, width: 40, height: 40 },
+ { width: 800, height: 600 },
+ { width: 280, height: 220 },
+ ).left,
+ ).toBe(508);
+ });
+});
diff --git a/packages/studio/src/components/editor/floatingPanel.ts b/packages/studio/src/components/editor/floatingPanel.ts
new file mode 100644
index 0000000000..695d32274c
--- /dev/null
+++ b/packages/studio/src/components/editor/floatingPanel.ts
@@ -0,0 +1,54 @@
+export interface FloatingRect {
+ left: number;
+ top: number;
+ right: number;
+ bottom: number;
+ width: number;
+ height: number;
+}
+
+export interface FloatingSize {
+ width: number;
+ height: number;
+}
+
+export interface FloatingPosition {
+ left: number;
+ top: number;
+ placement: "top" | "bottom";
+}
+
+function clamp(value: number, min: number, max: number): number {
+ return Math.max(min, Math.min(max, value));
+}
+
+export function resolveFloatingPanelPosition(
+ anchor: FloatingRect,
+ viewport: FloatingSize,
+ panel: FloatingSize,
+ options?: { offset?: number; margin?: number },
+): FloatingPosition {
+ const offset = options?.offset ?? 8;
+ const margin = options?.margin ?? 12;
+ const maxLeft = Math.max(margin, viewport.width - panel.width - margin);
+ const preferredLeft = anchor.left + anchor.width / 2 - panel.width / 2;
+ const left = clamp(preferredLeft, margin, maxLeft);
+ const belowTop = anchor.bottom + offset;
+ const aboveTop = anchor.top - panel.height - offset;
+ const fitsBelow = belowTop + panel.height <= viewport.height - margin;
+ const fitsAbove = aboveTop >= margin;
+
+ if (fitsBelow || !fitsAbove) {
+ return {
+ left,
+ top: clamp(belowTop, margin, Math.max(margin, viewport.height - panel.height - margin)),
+ placement: "bottom",
+ };
+ }
+
+ return {
+ left,
+ top: clamp(aboveTop, margin, Math.max(margin, viewport.height - panel.height - margin)),
+ placement: "top",
+ };
+}
diff --git a/packages/studio/src/components/editor/fontAssets.ts b/packages/studio/src/components/editor/fontAssets.ts
new file mode 100644
index 0000000000..579a0f35a3
--- /dev/null
+++ b/packages/studio/src/components/editor/fontAssets.ts
@@ -0,0 +1,32 @@
+export interface ImportedFontAsset {
+ family: string;
+ path: string;
+ url: string;
+}
+
+const FONT_EXT_RE = /\.(eot|otf|ttc|ttf|woff2?)$/i;
+const FONT_STYLE_SUFFIX_RE =
+ /\s+(thin|extralight|extra light|light|regular|roman|medium|semibold|semi bold|bold|extrabold|extra bold|black|italic|oblique|variable)$/i;
+
+export function cssString(value: string): string {
+ return JSON.stringify(value);
+}
+
+export function fontFamilyFromAssetPath(path: string): string {
+ const fileName = decodeURIComponent(path.split(/[\\/]/).pop() ?? path).replace(FONT_EXT_RE, "");
+ let family = fileName
+ .replace(/[_-]+/g, " ")
+ .replace(/([a-z])([A-Z])/g, "$1 $2")
+ .replace(/\s+/g, " ")
+ .trim();
+
+ while (FONT_STYLE_SUFFIX_RE.test(family)) {
+ family = family.replace(FONT_STYLE_SUFFIX_RE, "").trim();
+ }
+
+ return family || fileName;
+}
+
+export function importedFontFaceCss(asset: ImportedFontAsset, url: string = asset.url): string {
+ return `@font-face { font-family: ${cssString(asset.family)}; src: url(${cssString(url)}); font-display: swap; }`;
+}
diff --git a/packages/studio/src/components/editor/fontCatalog.ts b/packages/studio/src/components/editor/fontCatalog.ts
new file mode 100644
index 0000000000..c8691fc314
--- /dev/null
+++ b/packages/studio/src/components/editor/fontCatalog.ts
@@ -0,0 +1,126 @@
+export const POPULAR_GOOGLE_FONT_FAMILIES = [
+ "ABeeZee",
+ "Abel",
+ "Abril Fatface",
+ "Alegreya",
+ "Alegreya Sans",
+ "Anton",
+ "Archivo",
+ "Archivo Black",
+ "Arimo",
+ "Assistant",
+ "Barlow",
+ "Barlow Condensed",
+ "Bebas Neue",
+ "Bitter",
+ "Bricolage Grotesque",
+ "Cabin",
+ "Cardo",
+ "Catamaran",
+ "Caveat",
+ "Chivo",
+ "Cormorant Garamond",
+ "Crimson Text",
+ "Dancing Script",
+ "DM Sans",
+ "DM Serif Display",
+ "Domine",
+ "EB Garamond",
+ "Exo 2",
+ "Figtree",
+ "Fira Code",
+ "Fira Sans",
+ "Fraunces",
+ "Fredoka",
+ "IBM Plex Mono",
+ "IBM Plex Sans",
+ "IBM Plex Serif",
+ "Inconsolata",
+ "Instrument Sans",
+ "Instrument Serif",
+ "Inter",
+ "JetBrains Mono",
+ "Josefin Sans",
+ "Jost",
+ "Kanit",
+ "Karla",
+ "Lato",
+ "League Gothic",
+ "Lexend",
+ "Libre Baskerville",
+ "Libre Franklin",
+ "Lora",
+ "Manrope",
+ "Merriweather",
+ "Montserrat",
+ "Mukta",
+ "Mulish",
+ "Newsreader",
+ "Noto Sans",
+ "Noto Sans JP",
+ "Noto Serif",
+ "Nunito",
+ "Nunito Sans",
+ "Open Sans",
+ "Oswald",
+ "Outfit",
+ "Overpass",
+ "Pacifico",
+ "Pathway Extreme",
+ "Permanent Marker",
+ "Playfair Display",
+ "Plus Jakarta Sans",
+ "Poppins",
+ "Prata",
+ "PT Sans",
+ "PT Serif",
+ "Public Sans",
+ "Quicksand",
+ "Raleway",
+ "Red Hat Display",
+ "Roboto",
+ "Roboto Condensed",
+ "Roboto Mono",
+ "Roboto Serif",
+ "Rubik",
+ "Schibsted Grotesk",
+ "Signika",
+ "Source Code Pro",
+ "Source Sans 3",
+ "Source Serif 4",
+ "Space Grotesk",
+ "Space Mono",
+ "Spectral",
+ "Sora",
+ "Syne",
+ "Teko",
+ "Titillium Web",
+ "Ubuntu",
+ "Ubuntu Mono",
+ "Unbounded",
+ "Urbanist",
+ "Varela Round",
+ "Work Sans",
+ "Young Serif",
+ "Zilla Slab",
+] as const;
+
+export const COMMON_LOCAL_FONT_FAMILIES = [
+ "TT Norms Pro",
+ "SF Pro Display",
+ "SF Pro Text",
+ "Avenir",
+ "Avenir Next",
+ "Helvetica Neue",
+ "Arial",
+ "Georgia",
+ "Times New Roman",
+ "Menlo",
+ "Monaco",
+ "Courier New",
+] as const;
+
+export function googleFontStylesheetUrl(family: string): string {
+ const encodedFamily = encodeURIComponent(family.trim()).replace(/%20/g, "+");
+ return `https://fonts.googleapis.com/css2?family=${encodedFamily}:wght@300;400;500;600;700;800;900&display=swap`;
+}
diff --git a/packages/studio/src/components/editor/gradientValue.test.ts b/packages/studio/src/components/editor/gradientValue.test.ts
new file mode 100644
index 0000000000..4a5dc6ca42
--- /dev/null
+++ b/packages/studio/src/components/editor/gradientValue.test.ts
@@ -0,0 +1,89 @@
+import { describe, expect, it } from "vitest";
+import {
+ buildDefaultGradientModel,
+ insertGradientStop,
+ parseGradient,
+ serializeGradient,
+} from "./gradientValue";
+
+describe("parseGradient", () => {
+ it("parses linear gradients", () => {
+ expect(
+ parseGradient("linear-gradient(135deg, rgba(15, 23, 42, 0.58), rgba(255, 255, 255, 0.04))"),
+ ).toMatchObject({
+ kind: "linear",
+ repeating: false,
+ angle: 135,
+ stops: [
+ { color: "rgba(15, 23, 42, 0.58)", position: 0 },
+ { color: "rgba(255, 255, 255, 0.04)", position: 100 },
+ ],
+ });
+ });
+
+ it("parses radial gradients", () => {
+ expect(
+ parseGradient("radial-gradient(circle closest-side at 20% 35%, #ff0000 10%, #0000ff 90%)"),
+ ).toMatchObject({
+ kind: "radial",
+ shape: "circle",
+ radialSize: "closest-side",
+ centerX: 20,
+ centerY: 35,
+ });
+ });
+
+ it("parses conic gradients", () => {
+ expect(
+ parseGradient("conic-gradient(from 45deg at 40% 60%, #111111 0%, #ffffff 100%)"),
+ ).toMatchObject({
+ kind: "conic",
+ angle: 45,
+ centerX: 40,
+ centerY: 60,
+ });
+ });
+
+ it("parses repeating gradients", () => {
+ expect(
+ parseGradient("repeating-linear-gradient(90deg, #000000 0%, #ffffff 50%)"),
+ ).toMatchObject({
+ kind: "linear",
+ repeating: true,
+ angle: 90,
+ });
+ });
+});
+
+describe("serializeGradient", () => {
+ it("serializes default gradient models", () => {
+ expect(serializeGradient(buildDefaultGradientModel("rgba(60, 230, 172, 0.18)"))).toBe(
+ "linear-gradient(135deg, rgba(60, 230, 172, 0.18) 0%, rgba(255, 255, 255, 0.04) 100%)",
+ );
+ });
+
+ it("round-trips parsed gradients", () => {
+ const parsed = parseGradient(
+ "repeating-conic-gradient(from 90deg at 25% 75%, rgba(0, 0, 0, 0.5) 0%, rgba(255, 255, 255, 0.1) 100%)",
+ );
+ expect(parsed).not.toBeNull();
+ expect(serializeGradient(parsed!)).toBe(
+ "repeating-conic-gradient(from 90deg at 25% 75%, rgba(0, 0, 0, 0.5) 0%, rgba(255, 255, 255, 0.1) 100%)",
+ );
+ });
+});
+
+describe("insertGradientStop", () => {
+ it("inserts a stop at the clicked position with an interpolated color", () => {
+ const parsed = parseGradient("linear-gradient(90deg, #000000 0%, #ffffff 100%)");
+ expect(parsed).not.toBeNull();
+
+ expect(insertGradientStop(parsed!, 25)).toMatchObject({
+ stops: [
+ { color: "#000000", position: 0 },
+ { color: "#404040", position: 25 },
+ { color: "#ffffff", position: 100 },
+ ],
+ });
+ });
+});
diff --git a/packages/studio/src/components/editor/gradientValue.ts b/packages/studio/src/components/editor/gradientValue.ts
new file mode 100644
index 0000000000..a8983f5f90
--- /dev/null
+++ b/packages/studio/src/components/editor/gradientValue.ts
@@ -0,0 +1,445 @@
+export type GradientKind = "linear" | "radial" | "conic";
+
+export type RadialSizeKeyword =
+ | "closest-side"
+ | "closest-corner"
+ | "farthest-side"
+ | "farthest-corner";
+
+export interface GradientStop {
+ color: string;
+ position: number;
+}
+
+export interface GradientModel {
+ kind: GradientKind;
+ repeating: boolean;
+ angle: number;
+ centerX: number;
+ centerY: number;
+ shape: "circle" | "ellipse";
+ radialSize: RadialSizeKeyword;
+ stops: GradientStop[];
+}
+
+const RADIAL_SIZE_KEYWORDS: RadialSizeKeyword[] = [
+ "closest-side",
+ "closest-corner",
+ "farthest-side",
+ "farthest-corner",
+];
+
+function isWhitespace(char: string | undefined): boolean {
+ return char === " " || char === "\n" || char === "\r" || char === "\t" || char === "\f";
+}
+
+function isDigit(char: string | undefined): boolean {
+ return char != null && char >= "0" && char <= "9";
+}
+
+function isSimpleNumber(value: string): boolean {
+ if (!value) return false;
+ let index = value[0] === "-" ? 1 : 0;
+ let digits = 0;
+
+ while (isDigit(value[index])) {
+ index += 1;
+ digits += 1;
+ }
+
+ if (value[index] === ".") {
+ index += 1;
+ while (isDigit(value[index])) {
+ index += 1;
+ digits += 1;
+ }
+ }
+
+ return digits > 0 && index === value.length;
+}
+
+function parseCssNumber(value: string | undefined): number | null {
+ if (!value) return null;
+ const trimmed = value.trim();
+ if (!isSimpleNumber(trimmed)) return null;
+ const parsed = Number(trimmed);
+ return Number.isFinite(parsed) ? parsed : null;
+}
+
+function splitCssWhitespace(value: string): string[] {
+ const tokens: string[] = [];
+ let current = "";
+
+ for (const char of value) {
+ if (isWhitespace(char)) {
+ if (current) {
+ tokens.push(current);
+ current = "";
+ }
+ continue;
+ }
+ current += char;
+ }
+
+ if (current) tokens.push(current);
+ return tokens;
+}
+
+function hasCssWord(value: string, word: string): boolean {
+ return splitCssWhitespace(value.toLowerCase()).includes(word);
+}
+
+function parsePercentToken(value: string | undefined, fallback: number): number {
+ if (!value?.endsWith("%")) return fallback;
+ const parsed = parseCssNumber(value.slice(0, -1));
+ return parsed == null ? fallback : clamp(parsed, 0, 100);
+}
+
+function parseAngleToken(value: string | undefined): number | null {
+ const trimmed = value?.trim().toLowerCase();
+ if (!trimmed?.endsWith("deg")) return null;
+ return parseCssNumber(trimmed.slice(0, -3));
+}
+
+function trailingPercentStart(value: string): number | null {
+ if (!value.endsWith("%")) return null;
+ const withoutUnit = value.slice(0, -1).trimEnd();
+ let start = withoutUnit.length;
+
+ while (start > 0 && (isDigit(withoutUnit[start - 1]) || withoutUnit[start - 1] === ".")) {
+ start -= 1;
+ }
+
+ if (start > 0 && withoutUnit[start - 1] === "-") {
+ start -= 1;
+ }
+
+ const token = withoutUnit.slice(start);
+ if (!isSimpleNumber(token)) return null;
+ if (start === 0 || !isWhitespace(withoutUnit[start - 1])) return null;
+ return start;
+}
+
+function clamp(value: number, min: number, max: number): number {
+ return Math.min(max, Math.max(min, value));
+}
+
+function round(value: number): number {
+ return Math.round(value * 100) / 100;
+}
+
+function parsePercent(value: string | undefined, fallback: number): number {
+ const parsed = parseCssNumber(value);
+ return parsed == null ? fallback : clamp(parsed, 0, 100);
+}
+
+function parseColorStop(raw: string): { color: string; position: number | null } {
+ const trimmed = raw.trim();
+ const percentStart = trailingPercentStart(trimmed);
+ if (percentStart == null) return { color: trimmed, position: null };
+
+ const withoutUnit = trimmed.slice(0, -1).trimEnd();
+ return {
+ color: withoutUnit.slice(0, percentStart).trim(),
+ position: parsePercent(withoutUnit.slice(percentStart), 0),
+ };
+}
+
+function normalizeStops(stops: Array<{ color: string; position: number | null }>): GradientStop[] {
+ if (stops.length === 0) {
+ return [
+ { color: "rgba(60, 230, 172, 0.18)", position: 0 },
+ { color: "rgba(255, 255, 255, 0.04)", position: 100 },
+ ];
+ }
+
+ if (stops.length === 1) {
+ return [
+ { color: stops[0].color, position: 0 },
+ { color: stops[0].color, position: 100 },
+ ];
+ }
+
+ const result = stops.map((stop, index) => ({
+ color: stop.color,
+ position: stop.position ?? (index / (stops.length - 1)) * 100,
+ }));
+
+ return result.map((stop) => ({
+ color: stop.color,
+ position: round(clamp(stop.position, 0, 100)),
+ }));
+}
+
+function splitGradientArgs(value: string): string[] {
+ const parts: string[] = [];
+ let current = "";
+ let depth = 0;
+
+ for (const char of value) {
+ if (char === "(") depth += 1;
+ if (char === ")") depth = Math.max(0, depth - 1);
+
+ if (char === "," && depth === 0) {
+ if (current.trim()) parts.push(current.trim());
+ current = "";
+ continue;
+ }
+
+ current += char;
+ }
+
+ if (current.trim()) parts.push(current.trim());
+ return parts;
+}
+
+function directionToAngle(value: string): number | null {
+ const normalized = value.trim().toLowerCase();
+ const map: Record<string, number> = {
+ "to top": 0,
+ "to top right": 45,
+ "to right top": 45,
+ "to right": 90,
+ "to bottom right": 135,
+ "to right bottom": 135,
+ "to bottom": 180,
+ "to bottom left": 225,
+ "to left bottom": 225,
+ "to left": 270,
+ "to top left": 315,
+ "to left top": 315,
+ };
+ return normalized in map ? map[normalized] : null;
+}
+
+function parseLinearArgs(parts: string[]): GradientModel {
+ const first = parts[0] ?? "";
+ const angleFromDirection = directionToAngle(first);
+ const parsedAngle = parseAngleToken(first);
+ const firstIsAngle = parsedAngle != null;
+ const angle = parsedAngle ?? angleFromDirection ?? 180;
+ const stopParts = firstIsAngle || angleFromDirection != null ? parts.slice(1) : parts;
+
+ return {
+ kind: "linear",
+ repeating: false,
+ angle,
+ centerX: 50,
+ centerY: 50,
+ shape: "ellipse",
+ radialSize: "farthest-corner",
+ stops: normalizeStops(stopParts.map(parseColorStop)),
+ };
+}
+
+function parseRadialArgs(parts: string[]): GradientModel {
+ const first = parts[0] ?? "";
+ const firstLower = first.toLowerCase();
+ const hasConfig =
+ hasCssWord(firstLower, "at") ||
+ hasCssWord(firstLower, "circle") ||
+ hasCssWord(firstLower, "ellipse") ||
+ firstLower.includes("closest-") ||
+ firstLower.includes("farthest-");
+ const config = hasConfig ? first : "";
+ const stopParts = hasConfig ? parts.slice(1) : parts;
+ const configLower = config.toLowerCase();
+ const configTokens = splitCssWhitespace(configLower);
+ const atIndex = configTokens.indexOf("at");
+
+ const shape = hasCssWord(configLower, "circle") ? "circle" : "ellipse";
+ const radialSize =
+ RADIAL_SIZE_KEYWORDS.find((keyword) => configTokens.includes(keyword)) ?? "farthest-corner";
+
+ return {
+ kind: "radial",
+ repeating: false,
+ angle: 180,
+ centerX: parsePercentToken(configTokens[atIndex + 1], 50),
+ centerY: parsePercentToken(configTokens[atIndex + 2], 50),
+ shape,
+ radialSize,
+ stops: normalizeStops(stopParts.map(parseColorStop)),
+ };
+}
+
+function parseConicArgs(parts: string[]): GradientModel {
+ const first = parts[0] ?? "";
+ const firstLower = first.toLowerCase();
+ const hasConfig = hasCssWord(firstLower, "from") || hasCssWord(firstLower, "at");
+ const config = hasConfig ? first : "";
+ const stopParts = hasConfig ? parts.slice(1) : parts;
+ const configTokens = splitCssWhitespace(config.toLowerCase());
+ const fromIndex = configTokens.indexOf("from");
+ const atIndex = configTokens.indexOf("at");
+ const angle = parseAngleToken(configTokens[fromIndex + 1]);
+
+ return {
+ kind: "conic",
+ repeating: false,
+ angle: angle ?? 0,
+ centerX: parsePercentToken(configTokens[atIndex + 1], 50),
+ centerY: parsePercentToken(configTokens[atIndex + 2], 50),
+ shape: "ellipse",
+ radialSize: "farthest-corner",
+ stops: normalizeStops(stopParts.map(parseColorStop)),
+ };
+}
+
+export function buildDefaultGradientModel(fallbackColor?: string): GradientModel {
+ return {
+ kind: "linear",
+ repeating: false,
+ angle: 135,
+ centerX: 50,
+ centerY: 50,
+ shape: "ellipse",
+ radialSize: "farthest-corner",
+ stops: normalizeStops([
+ {
+ color:
+ fallbackColor && fallbackColor !== "transparent"
+ ? fallbackColor
+ : "rgba(60, 230, 172, 0.18)",
+ position: 0,
+ },
+ { color: "rgba(255, 255, 255, 0.04)", position: 100 },
+ ]),
+ };
+}
+
+export function parseGradient(value: string | undefined): GradientModel | null {
+ if (!value || value === "none") return null;
+ const trimmed = value.trim();
+ const openParenIndex = trimmed.indexOf("(");
+ if (openParenIndex <= 0 || !trimmed.endsWith(")")) return null;
+
+ const functionName = trimmed.slice(0, openParenIndex).toLowerCase();
+ const kindByFunctionName: Record<string, { kind: GradientKind; repeating: boolean }> = {
+ "linear-gradient": { kind: "linear", repeating: false },
+ "radial-gradient": { kind: "radial", repeating: false },
+ "conic-gradient": { kind: "conic", repeating: false },
+ "repeating-linear-gradient": { kind: "linear", repeating: true },
+ "repeating-radial-gradient": { kind: "radial", repeating: true },
+ "repeating-conic-gradient": { kind: "conic", repeating: true },
+ };
+ const parsedFunction = kindByFunctionName[functionName];
+ if (!parsedFunction) return null;
+
+ const { kind, repeating } = parsedFunction;
+ const parts = splitGradientArgs(trimmed.slice(openParenIndex + 1, -1));
+
+ const parsed =
+ kind === "linear"
+ ? parseLinearArgs(parts)
+ : kind === "radial"
+ ? parseRadialArgs(parts)
+ : parseConicArgs(parts);
+
+ return { ...parsed, repeating };
+}
+
+function formatStop(stop: GradientStop): string {
+ return `${stop.color} ${round(stop.position)}%`;
+}
+
+export function serializeGradient(model: GradientModel): string {
+ const fn = `${model.repeating ? "repeating-" : ""}${model.kind}-gradient`;
+ const stops = model.stops.map(formatStop).join(", ");
+
+ if (model.kind === "linear") {
+ return `${fn}(${round(model.angle)}deg, ${stops})`;
+ }
+
+ if (model.kind === "radial") {
+ return `${fn}(${model.shape} ${model.radialSize} at ${round(model.centerX)}% ${round(
+ model.centerY,
+ )}%, ${stops})`;
+ }
+
+ return `${fn}(from ${round(model.angle)}deg at ${round(model.centerX)}% ${round(
+ model.centerY,
+ )}%, ${stops})`;
+}
+
+function blendChannel(start: number, end: number, ratio: number): number {
+ return Math.round(start + (end - start) * ratio);
+}
+
+function formatHex(channel: number): string {
+ return channel.toString(16).padStart(2, "0");
+}
+
+export function interpolateGradientStopColor(model: GradientModel, position: number): string {
+ const clampedPosition = clamp(position, 0, 100);
+ const sortedStops = [...model.stops].sort((a, b) => a.position - b.position);
+ const exact = sortedStops.find((stop) => Math.abs(stop.position - clampedPosition) < 0.001);
+ if (exact) return exact.color;
+
+ const right = sortedStops.find((stop) => stop.position > clampedPosition) ?? sortedStops.at(-1);
+ const left =
+ [...sortedStops].reverse().find((stop) => stop.position < clampedPosition) ?? sortedStops[0];
+ if (!left || !right) return sortedStops[0]?.color ?? "rgba(255, 255, 255, 1)";
+ if (left === right) return left.color;
+
+ const leftColor = left.color;
+ const rightColor = right.color;
+ const leftParsed = leftColor ? parseColorString(leftColor) : null;
+ const rightParsed = rightColor ? parseColorString(rightColor) : null;
+ if (!leftParsed || !rightParsed) return left.color;
+
+ const ratio = (clampedPosition - left.position) / Math.max(1, right.position - left.position);
+ const red = blendChannel(leftParsed.red, rightParsed.red, ratio);
+ const green = blendChannel(leftParsed.green, rightParsed.green, ratio);
+ const blue = blendChannel(leftParsed.blue, rightParsed.blue, ratio);
+ const alpha = round(leftParsed.alpha + (rightParsed.alpha - leftParsed.alpha) * ratio);
+
+ if (alpha >= 1) {
+ return `#${formatHex(red)}${formatHex(green)}${formatHex(blue)}`.toUpperCase();
+ }
+
+ return `rgba(${red}, ${green}, ${blue}, ${alpha})`;
+}
+
+export function insertGradientStop(model: GradientModel, position: number): GradientModel {
+ const clampedPosition = round(clamp(position, 0, 100));
+ const color = interpolateGradientStopColor(model, clampedPosition);
+ const nextStops = [...model.stops, { color, position: clampedPosition }].sort(
+ (a, b) => a.position - b.position,
+ );
+ return {
+ ...model,
+ stops: nextStops,
+ };
+}
+
+function parseColorString(
+ value: string,
+): { red: number; green: number; blue: number; alpha: number } | null {
+ const trimmed = value.trim().toLowerCase();
+ if (trimmed === "transparent") {
+ return { red: 0, green: 0, blue: 0, alpha: 0 };
+ }
+
+ const hex = trimmed.match(/^#([0-9a-f]{6})$/i);
+ if (hex) {
+ return {
+ red: Number.parseInt(hex[1].slice(0, 2), 16),
+ green: Number.parseInt(hex[1].slice(2, 4), 16),
+ blue: Number.parseInt(hex[1].slice(4, 6), 16),
+ alpha: 1,
+ };
+ }
+
+ const rgba = trimmed.match(
+ /^rgba?\(\s*([0-9.]+)\s*,\s*([0-9.]+)\s*,\s*([0-9.]+)(?:\s*,\s*([0-9.]+))?\s*\)$/i,
+ );
+ if (!rgba) return null;
+
+ return {
+ red: Number.parseFloat(rgba[1]),
+ green: Number.parseFloat(rgba[2]),
+ blue: Number.parseFloat(rgba[3]),
+ alpha: rgba[4] != null ? Number.parseFloat(rgba[4]) : 1,
+ };
+}
diff --git a/packages/studio/src/components/editor/manualEdits.test.ts b/packages/studio/src/components/editor/manualEdits.test.ts
new file mode 100644
index 0000000000..4be1db5dd8
--- /dev/null
+++ b/packages/studio/src/components/editor/manualEdits.test.ts
@@ -0,0 +1,945 @@
+import { describe, expect, it, vi } from "vitest";
+import { Window } from "happy-dom";
+import type { DomEditSelection } from "./domEditing";
+import {
+ STUDIO_OFFSET_X_PROP,
+ STUDIO_OFFSET_Y_PROP,
+ STUDIO_ROTATION_PROP,
+ STUDIO_WIDTH_PROP,
+ applyStudioBoxSize,
+ applyStudioBoxSizeDraft,
+ applyStudioManualEditManifest,
+ applyStudioPathOffset,
+ applyStudioPathOffsetDraft,
+ applyStudioRotation,
+ applyStudioRotationDraft,
+ beginStudioManualEditGesture,
+ captureStudioBoxSize,
+ captureStudioRotation,
+ emptyStudioManualEditManifest,
+ endStudioManualEditGesture,
+ installStudioManualEditSeekReapply,
+ isStudioManualEditManifestPath,
+ parseStudioManualEditManifest,
+ readStudioFileChangePath,
+ readStudioBoxSize,
+ readStudioPathOffset,
+ readStudioRotation,
+ removeStudioManualEditsForSelection,
+ restoreStudioBoxSize,
+ restoreStudioRotation,
+ serializeStudioManualEditManifest,
+ upsertStudioBoxSizeEdit,
+ upsertStudioPathOffsetEdit,
+ upsertStudioRotationEdit,
+} from "./manualEdits";
+
+function createDocument(markup: string): Document {
+ const window = new Window();
+ window.document.body.innerHTML = markup;
+ return window.document;
+}
+
+function createSelection(): DomEditSelection {
+ return {
+ element: {} as HTMLElement,
+ id: "card",
+ selector: "#card",
+ selectorIndex: undefined,
+ sourceFile: "index.html",
+ compositionPath: "index.html",
+ compositionSrc: undefined,
+ isCompositionHost: false,
+ label: "Card",
+ tagName: "div",
+ boundingBox: { x: 0, y: 0, width: 100, height: 100 },
+ textContent: null,
+ dataAttributes: {},
+ inlineStyles: {},
+ computedStyles: {},
+ textFields: [],
+ capabilities: {
+ canSelect: true,
+ canEditStyles: true,
+ canMove: false,
+ canResize: false,
+ canApplyManualOffset: true,
+ canApplyManualSize: true,
+ canApplyManualRotation: true,
+ },
+ };
+}
+
+function mockBoundingRect(element: HTMLElement, width: number, height: number): void {
+ element.getBoundingClientRect = () =>
+ ({
+ x: 0,
+ y: 0,
+ left: 0,
+ top: 0,
+ right: width,
+ bottom: height,
+ width,
+ height,
+ toJSON: () => ({}),
+ }) as DOMRect;
+}
+
+function mockComputedStyle(element: HTMLElement, values: Record<string, string>): void {
+ const win = element.ownerDocument.defaultView;
+ if (!win) throw new Error("defaultView fixture missing");
+ win.getComputedStyle = ((target: Element) =>
+ ({
+ getPropertyValue: (property: string) => (target === element ? (values[property] ?? "") : ""),
+ }) as CSSStyleDeclaration) as typeof win.getComputedStyle;
+}
+
+describe("studio manual edits", () => {
+ it("upserts path offsets by stable target", () => {
+ const manifest = upsertStudioPathOffsetEdit(
+ emptyStudioManualEditManifest(),
+ createSelection(),
+ {
+ x: 12.4,
+ y: 30.6,
+ },
+ );
+ const updated = upsertStudioPathOffsetEdit(manifest, createSelection(), {
+ x: 20,
+ y: 42,
+ });
+
+ expect(updated.edits).toHaveLength(1);
+ expect(updated.edits[0]).toMatchObject({
+ kind: "path-offset",
+ target: { sourceFile: "index.html", selector: "#card", id: "card" },
+ x: 20,
+ y: 42,
+ });
+ });
+
+ it("upserts box sizes without replacing path offsets for the same target", () => {
+ const selection = createSelection();
+ const manifest = upsertStudioPathOffsetEdit(emptyStudioManualEditManifest(), selection, {
+ x: 12,
+ y: 30,
+ });
+ const updated = upsertStudioBoxSizeEdit(manifest, selection, {
+ width: 240.4,
+ height: 120.6,
+ });
+ const resized = upsertStudioBoxSizeEdit(updated, selection, {
+ width: 260,
+ height: 140,
+ });
+
+ expect(resized.edits).toHaveLength(2);
+ expect(resized.edits).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ kind: "path-offset", x: 12, y: 30 }),
+ expect.objectContaining({ kind: "box-size", width: 260, height: 140 }),
+ ]),
+ );
+ });
+
+ it("upserts rotations without replacing other manual edits for the same target", () => {
+ const selection = createSelection();
+ const manifest = upsertStudioPathOffsetEdit(emptyStudioManualEditManifest(), selection, {
+ x: 12,
+ y: 30,
+ });
+ const resized = upsertStudioBoxSizeEdit(manifest, selection, {
+ width: 240,
+ height: 120,
+ });
+ const rotated = upsertStudioRotationEdit(resized, selection, { angle: 32.34 });
+ const updated = upsertStudioRotationEdit(rotated, selection, { angle: -14.96 });
+
+ expect(updated.edits).toHaveLength(3);
+ expect(updated.edits).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ kind: "path-offset", x: 12, y: 30 }),
+ expect.objectContaining({ kind: "box-size", width: 240, height: 120 }),
+ expect.objectContaining({ kind: "rotation", angle: -15 }),
+ ]),
+ );
+ });
+
+ it("removes all manual edits for the selected target", () => {
+ const selection = createSelection();
+ const otherSelection = {
+ ...createSelection(),
+ id: "other-card",
+ selector: "#other-card",
+ label: "Other card",
+ };
+ const moved = upsertStudioPathOffsetEdit(emptyStudioManualEditManifest(), selection, {
+ x: 12,
+ y: 30,
+ });
+ const resized = upsertStudioBoxSizeEdit(moved, selection, {
+ width: 240,
+ height: 120,
+ });
+ const rotated = upsertStudioRotationEdit(resized, selection, { angle: 32 });
+ const manifest = upsertStudioPathOffsetEdit(rotated, otherSelection, { x: 4, y: 8 });
+
+ const updated = removeStudioManualEditsForSelection(manifest, selection);
+
+ expect(updated.edits).toHaveLength(1);
+ expect(updated.edits[0]).toMatchObject({
+ kind: "path-offset",
+ target: { id: "other-card", selector: "#other-card" },
+ x: 4,
+ y: 8,
+ });
+ });
+
+ it("round-trips valid manifest entries and drops invalid entries", () => {
+ const content = serializeStudioManualEditManifest({
+ version: 1,
+ edits: [
+ {
+ kind: "path-offset",
+ target: { sourceFile: "index.html", selector: "#card", id: "card" },
+ x: 10,
+ y: 20,
+ },
+ {
+ kind: "box-size",
+ target: { sourceFile: "index.html", selector: "#card", id: "card" },
+ width: 320,
+ height: 180,
+ },
+ {
+ kind: "rotation",
+ target: { sourceFile: "index.html", selector: "#card", id: "card" },
+ angle: 22.5,
+ },
+ ],
+ });
+
+ expect(parseStudioManualEditManifest(content).edits).toHaveLength(3);
+ expect(parseStudioManualEditManifest('{ "edits": [{ "kind": "path-offset" }] }').edits).toEqual(
+ [],
+ );
+ });
+
+ it("recognizes manual edit manifest file-change payloads", () => {
+ expect(readStudioFileChangePath({ path: ".hyperframes/studio-manual-edits.json" })).toBe(
+ ".hyperframes/studio-manual-edits.json",
+ );
+ expect(readStudioFileChangePath({ data: '{"path":"nested/file.html"}' })).toBe(
+ "nested/file.html",
+ );
+ expect(
+ isStudioManualEditManifestPath(
+ "/Users/example/project/.hyperframes/studio-manual-edits.json",
+ ),
+ ).toBe(true);
+ expect(isStudioManualEditManifestPath("index.html")).toBe(false);
+ });
+
+ it("applies offsets through CSS translate longhand", () => {
+ const document = createDocument(`<div id="card"></div>`);
+ const card = document.getElementById("card") as HTMLElement;
+
+ applyStudioPathOffset(card, { x: 14, y: -8 });
+
+ expect(readStudioPathOffset(card)).toEqual({ x: 14, y: -8 });
+ expect(card.style.getPropertyValue(STUDIO_OFFSET_X_PROP)).toBe("14px");
+ expect(card.style.getPropertyValue(STUDIO_OFFSET_Y_PROP)).toBe("-8px");
+ expect(card.style.getPropertyValue("translate")).toContain(STUDIO_OFFSET_X_PROP);
+ });
+
+ it("preserves authored inline translate as the additive path offset base", () => {
+ const document = createDocument(`<div id="card" style="translate: 10px 20px"></div>`);
+ const card = document.getElementById("card") as HTMLElement;
+
+ applyStudioPathOffset(card, { x: 14, y: -8 });
+
+ expect(card.style.getPropertyValue("translate")).toContain("calc(10px +");
+ expect(card.style.getPropertyValue("translate")).toContain("calc(20px +");
+ expect(card.style.getPropertyValue("translate")).toContain(STUDIO_OFFSET_X_PROP);
+ expect(card.style.getPropertyValue("translate")).toContain(STUDIO_OFFSET_Y_PROP);
+ });
+
+ it("preserves stylesheet-authored transform longhands as additive bases", () => {
+ const document = createDocument(`<div id="card"></div>`);
+ const card = document.getElementById("card") as HTMLElement;
+ mockComputedStyle(card, {
+ translate: "10px 20px",
+ rotate: "8deg",
+ });
+
+ applyStudioPathOffset(card, { x: 14, y: -8 });
+ applyStudioRotation(card, { angle: 12 });
+
+ expect(card.style.getPropertyValue("translate")).toContain("calc(10px +");
+ expect(card.style.getPropertyValue("translate")).toContain("calc(20px +");
+ expect(card.style.getPropertyValue("translate")).toContain(STUDIO_OFFSET_X_PROP);
+ expect(card.style.getPropertyValue("rotate")).toContain("8deg");
+ expect(card.style.getPropertyValue("rotate")).toContain(STUDIO_ROTATION_PROP);
+ });
+
+ it("clears computed transform bases without freezing them inline", () => {
+ const document = createDocument(`<div id="card"></div>`);
+ const card = document.getElementById("card") as HTMLElement;
+ mockComputedStyle(card, {
+ translate: "10px 20px",
+ rotate: "8deg",
+ });
+
+ applyStudioPathOffset(card, { x: 14, y: -8 });
+ applyStudioRotation(card, { angle: 12 });
+
+ expect(
+ applyStudioManualEditManifest(document, emptyStudioManualEditManifest(), "index.html"),
+ ).toBe(0);
+
+ expect(card.style.getPropertyValue("translate")).toBe("");
+ expect(card.style.getPropertyValue("rotate")).toBe("");
+ });
+
+ it("does not compound stale studio variables as authored transform bases", () => {
+ const document = createDocument(`<div id="card"></div>`);
+ const card = document.getElementById("card") as HTMLElement;
+
+ card.style.setProperty(
+ "translate",
+ `var(${STUDIO_OFFSET_X_PROP}, 0px) var(${STUDIO_OFFSET_Y_PROP}, 0px)`,
+ );
+ card.style.setProperty("rotate", `var(${STUDIO_ROTATION_PROP}, 0deg)`);
+
+ applyStudioPathOffset(card, { x: 14, y: -8 });
+ applyStudioRotation(card, { angle: 12 });
+
+ expect(card.style.getPropertyValue("translate")).toBe(
+ `var(${STUDIO_OFFSET_X_PROP}, 0px) var(${STUDIO_OFFSET_Y_PROP}, 0px)`,
+ );
+ expect(card.style.getPropertyValue("rotate")).toBe(`var(${STUDIO_ROTATION_PROP}, 0deg)`);
+ });
+
+ it("applies box sizes through CSS dimensions and flex sizing overrides", () => {
+ const document = createDocument(`
+ <div style="display: flex; flex-direction: row">
+ <div id="card" style="width: 160px; height: 90px"></div>
+ </div>
+ `);
+ const card = document.getElementById("card") as HTMLElement;
+ mockBoundingRect(card, 160, 90);
+
+ applyStudioBoxSize(card, { width: 240, height: 135 });
+
+ expect(readStudioBoxSize(card)).toEqual({ width: 240, height: 135 });
+ expect(card.style.getPropertyValue(STUDIO_WIDTH_PROP)).toBe("240px");
+ expect(card.style.getPropertyValue("width")).toBe("240px");
+ expect(card.style.getPropertyValue("height")).toBe("135px");
+ expect(card.style.getPropertyValue("flex-basis")).toBe("240px");
+ expect(card.style.getPropertyValue("flex-grow")).toBe("0");
+ expect(card.style.getPropertyValue("flex-shrink")).toBe("0");
+ expect(card.style.getPropertyValue("box-sizing")).toBe("border-box");
+ expect(card.style.getPropertyValue("scale")).toBe("");
+
+ applyStudioBoxSizeDraft(card, { width: 260, height: 150 });
+ expect(readStudioBoxSize(card)).toEqual({ width: 260, height: 150 });
+ expect(card.style.getPropertyValue("width")).toBe("260px");
+ expect(card.style.getPropertyValue("height")).toBe("150px");
+ expect(card.style.getPropertyValue("flex-basis")).toBe("260px");
+
+ const snapshot = captureStudioBoxSize(card);
+ applyStudioBoxSizeDraft(card, { width: 280, height: 160 });
+ restoreStudioBoxSize(card, snapshot);
+ expect(readStudioBoxSize(card)).toEqual({ width: 260, height: 150 });
+ expect(card.style.getPropertyValue("width")).toBe("260px");
+ expect(card.style.getPropertyValue("height")).toBe("150px");
+ expect(card.style.getPropertyValue("flex-basis")).toBe("260px");
+ });
+
+ it("applies rotations through CSS rotate longhand around the element center", () => {
+ const document = createDocument(
+ `<div id="card" style="rotate: 8deg; transform-origin: left top"></div>`,
+ );
+ const card = document.getElementById("card") as HTMLElement;
+
+ applyStudioRotation(card, { angle: 24.24 });
+
+ expect(readStudioRotation(card)).toEqual({ angle: 24.2 });
+ expect(card.style.getPropertyValue(STUDIO_ROTATION_PROP)).toBe("24.2deg");
+ expect(card.style.getPropertyValue("rotate")).toContain("8deg");
+ expect(card.style.getPropertyValue("rotate")).toContain(STUDIO_ROTATION_PROP);
+ expect(card.style.getPropertyValue("transform-origin")).toBe("center center");
+
+ applyStudioRotationDraft(card, { angle: -12.26 });
+ expect(readStudioRotation(card)).toEqual({ angle: -12.3 });
+ expect(card.style.getPropertyValue("rotate")).toBe("calc(8deg + -12.3deg)");
+ expect(card.style.getPropertyValue("transform-origin")).toBe("center center");
+
+ const snapshot = captureStudioRotation(card);
+ applyStudioRotationDraft(card, { angle: 45 });
+ restoreStudioRotation(card, snapshot);
+ expect(readStudioRotation(card)).toEqual({ angle: -12.3 });
+ expect(card.style.getPropertyValue("rotate")).toBe("calc(8deg + -12.3deg)");
+ expect(card.style.getPropertyValue("transform-origin")).toBe("center center");
+ });
+
+ it("does not recapture a studio rotation draft as the authored base", () => {
+ const document = createDocument(`<div id="card" style="rotate: 8deg"></div>`);
+ const card = document.getElementById("card") as HTMLElement;
+ const manifest = parseStudioManualEditManifest(`{
+ "version": 1,
+ "edits": [
+ {
+ "kind": "rotation",
+ "target": { "sourceFile": "index.html", "selector": "#card", "id": "card" },
+ "angle": 35
+ }
+ ]
+ }`);
+
+ applyStudioRotation(card, { angle: 12 });
+ applyStudioRotationDraft(card, { angle: 35 });
+ expect(card.style.getPropertyValue("rotate")).toBe("calc(8deg + 35deg)");
+
+ expect(applyStudioManualEditManifest(document, manifest, "index.html")).toBe(1);
+
+ expect(card.style.getPropertyValue("rotate")).toBe(
+ `calc(8deg + var(${STUDIO_ROTATION_PROP}, 0deg))`,
+ );
+ });
+
+ it("does not treat a base-free studio rotation draft as authored rotation", () => {
+ const document = createDocument(`<div id="card"></div>`);
+ const card = document.getElementById("card") as HTMLElement;
+ const manifest = parseStudioManualEditManifest(`{
+ "version": 1,
+ "edits": [
+ {
+ "kind": "rotation",
+ "target": { "sourceFile": "index.html", "selector": "#card", "id": "card" },
+ "angle": 35
+ }
+ ]
+ }`);
+
+ applyStudioRotation(card, { angle: 12 });
+ applyStudioRotationDraft(card, { angle: 35 });
+ expect(card.style.getPropertyValue("rotate")).toBe("35deg");
+
+ expect(applyStudioManualEditManifest(document, manifest, "index.html")).toBe(1);
+
+ expect(card.style.getPropertyValue("rotate")).toBe(`var(${STUDIO_ROTATION_PROP}, 0deg)`);
+ });
+
+ it("uses height for flex-basis inside column flex containers", () => {
+ const document = createDocument(`
+ <div style="display: flex; flex-direction: column">
+ <div id="card" style="width: 160px; height: 90px"></div>
+ </div>
+ `);
+ const card = document.getElementById("card") as HTMLElement;
+
+ applyStudioBoxSize(card, { width: 240, height: 135 });
+
+ expect(card.style.getPropertyValue("width")).toBe("240px");
+ expect(card.style.getPropertyValue("height")).toBe("135px");
+ expect(card.style.getPropertyValue("flex-basis")).toBe("135px");
+ });
+
+ it("uses additive CSS translate without mutating GSAP tweens during path-offset moves", () => {
+ const document = createDocument(`<div id="card"></div>`);
+ const card = document.getElementById("card") as HTMLElement;
+ const getTweensOf = vi.fn();
+ const getProperty = vi.fn();
+ const set = vi.fn();
+ const tickerTick = vi.fn();
+ const tween = {
+ vars: { x: 0, y: 10, startAt: { x: -240, y: -20 } },
+ targets: () => [card],
+ invalidate: vi.fn(),
+ parent: {
+ time: () => 1.25,
+ totalTime: vi.fn(),
+ invalidate: vi.fn(),
+ },
+ _startAt: {
+ vars: { x: -240, y: -20 },
+ invalidate: vi.fn(),
+ },
+ };
+
+ (
+ document.defaultView as unknown as {
+ gsap: {
+ getTweensOf: () => Array<typeof tween>;
+ getProperty: (_target: Element, property: string) => unknown;
+ set: (_target: Element, vars: Record<string, unknown>) => void;
+ ticker: { tick: () => void };
+ };
+ }
+ ).gsap = {
+ getTweensOf,
+ getProperty,
+ set,
+ ticker: { tick: tickerTick },
+ };
+
+ applyStudioPathOffset(card, { x: 30, y: -12 });
+
+ expect(tween.vars).toMatchObject({
+ x: 0,
+ y: 10,
+ startAt: { x: -240, y: -20 },
+ });
+ expect(tween._startAt.vars).toEqual({ x: -240, y: -20 });
+ expect(readStudioPathOffset(card)).toEqual({ x: 30, y: -12 });
+ expect(card.style.getPropertyValue("translate")).toContain(STUDIO_OFFSET_X_PROP);
+ expect(getTweensOf).not.toHaveBeenCalled();
+ expect(getProperty).not.toHaveBeenCalled();
+ expect(set).not.toHaveBeenCalled();
+ expect(tickerTick).not.toHaveBeenCalled();
+
+ beginStudioManualEditGesture(card);
+ applyStudioPathOffsetDraft(card, { x: 35, y: -6 });
+
+ expect(readStudioPathOffset(card)).toEqual({ x: 35, y: -6 });
+ expect(card.style.getPropertyValue("translate")).toBe("35px -6px");
+ expect(tween.vars).toMatchObject({
+ x: 0,
+ y: 10,
+ startAt: { x: -240, y: -20 },
+ });
+ expect(tween._startAt.vars).toEqual({ x: -240, y: -20 });
+ expect(tickerTick).not.toHaveBeenCalled();
+
+ applyStudioPathOffset(card, { x: 35, y: -6 });
+ endStudioManualEditGesture(card);
+
+ expect(tween.vars).toMatchObject({
+ x: 0,
+ y: 10,
+ startAt: { x: -240, y: -20 },
+ });
+ expect(tween._startAt.vars).toEqual({ x: -240, y: -20 });
+ expect(card.style.getPropertyValue("translate")).toContain(STUDIO_OFFSET_X_PROP);
+
+ expect(
+ applyStudioManualEditManifest(document, emptyStudioManualEditManifest(), "index.html"),
+ ).toBe(0);
+ expect(tween.vars).toMatchObject({
+ x: 0,
+ y: 10,
+ startAt: { x: -240, y: -20 },
+ });
+ expect(tween._startAt.vars).toEqual({ x: -240, y: -20 });
+ expect(card.style.getPropertyValue(STUDIO_OFFSET_X_PROP)).toBe("");
+ expect(card.style.getPropertyValue(STUDIO_OFFSET_Y_PROP)).toBe("");
+ expect(card.style.getPropertyValue("translate")).toBe("");
+ });
+
+ it("applies manifest offsets to matching preview elements", () => {
+ const document = createDocument(`<div id="card"></div>`);
+ const manifest = parseStudioManualEditManifest(`{
+ "version": 1,
+ "edits": [
+ {
+ "kind": "path-offset",
+ "target": { "sourceFile": "index.html", "selector": "#card", "id": "card" },
+ "x": 32,
+ "y": 18
+ }
+ ]
+ }`);
+
+ expect(applyStudioManualEditManifest(document, manifest, "index.html")).toBe(1);
+ expect(readStudioPathOffset(document.getElementById("card") as HTMLElement)).toEqual({
+ x: 32,
+ y: 18,
+ });
+ });
+
+ it("resolves manifest targets within the matching source file", () => {
+ const document = createDocument(`
+ <div data-composition-id="root">
+ <div id="card" class="tile"></div>
+ <div data-composition-id="nested" data-composition-file="scenes/nested.html">
+ <div id="card" class="tile"></div>
+ <div class="tile"></div>
+ </div>
+ </div>
+ `);
+ const htmlElement = document.defaultView?.HTMLElement;
+ if (!htmlElement) throw new Error("HTMLElement fixture missing");
+ const cards = Array.from(document.getElementsByTagName("*")).filter(
+ (element): element is HTMLElement => element instanceof htmlElement && element.id === "card",
+ );
+ const rootCard = cards[0];
+ const nestedCard = cards[1];
+ const tiles = Array.from(document.getElementsByTagName("*")).filter(
+ (element): element is HTMLElement =>
+ element instanceof htmlElement && element.classList.contains("tile"),
+ );
+ const nestedSecondTile = tiles[2];
+ if (!rootCard || !nestedCard || !nestedSecondTile) {
+ throw new Error("source-scoped fixture missing");
+ }
+
+ const manifest = parseStudioManualEditManifest(`{
+ "version": 1,
+ "edits": [
+ {
+ "kind": "path-offset",
+ "target": {
+ "sourceFile": "scenes/nested.html",
+ "selector": "#card",
+ "id": "card"
+ },
+ "x": 48,
+ "y": 16
+ },
+ {
+ "kind": "box-size",
+ "target": {
+ "sourceFile": "scenes/nested.html",
+ "selector": ".tile",
+ "selectorIndex": 1
+ },
+ "width": 220,
+ "height": 80
+ }
+ ]
+ }`);
+
+ expect(applyStudioManualEditManifest(document, manifest, "index.html")).toBe(2);
+ expect(readStudioPathOffset(rootCard)).toEqual({ x: 0, y: 0 });
+ expect(readStudioPathOffset(nestedCard)).toEqual({ x: 48, y: 16 });
+ expect(readStudioBoxSize(nestedSecondTile)).toEqual({ width: 220, height: 80 });
+ });
+
+ it("resolves manifest targets inside composition-file hosts without composition ids", () => {
+ const document = createDocument(`
+ <div data-composition-id="root">
+ <div id="card"></div>
+ <div data-composition-file="scenes/anonymous.html">
+ <div id="card"></div>
+ </div>
+ </div>
+ `);
+ const htmlElement = document.defaultView?.HTMLElement;
+ if (!htmlElement) throw new Error("HTMLElement fixture missing");
+ const cards = Array.from(document.getElementsByTagName("*")).filter(
+ (element): element is HTMLElement => element instanceof htmlElement && element.id === "card",
+ );
+ const rootCard = cards[0];
+ const nestedCard = cards[1];
+ if (!rootCard || !nestedCard) {
+ throw new Error("anonymous composition fixture missing");
+ }
+
+ const manifest = parseStudioManualEditManifest(`{
+ "version": 1,
+ "edits": [
+ {
+ "kind": "path-offset",
+ "target": {
+ "sourceFile": "scenes/anonymous.html",
+ "selector": "#card",
+ "id": "card"
+ },
+ "x": 24,
+ "y": 12
+ }
+ ]
+ }`);
+
+ expect(applyStudioManualEditManifest(document, manifest, "index.html")).toBe(1);
+ expect(readStudioPathOffset(rootCard)).toEqual({ x: 0, y: 0 });
+ expect(readStudioPathOffset(nestedCard)).toEqual({ x: 24, y: 12 });
+ });
+
+ it("applies nested source edits while previewing a non-index parent composition", () => {
+ const document = createDocument(`
+ <div data-composition-id="parent">
+ <div id="parent-card"></div>
+ <div data-composition-file="scenes/child.html">
+ <div id="child-card"></div>
+ </div>
+ </div>
+ `);
+ const parentCard = document.getElementById("parent-card") as HTMLElement;
+ const childCard = document.getElementById("child-card") as HTMLElement;
+ const manifest = parseStudioManualEditManifest(`{
+ "version": 1,
+ "edits": [
+ {
+ "kind": "path-offset",
+ "target": {
+ "sourceFile": "scenes/parent.html",
+ "selector": "#parent-card",
+ "id": "parent-card"
+ },
+ "x": 12,
+ "y": 8
+ },
+ {
+ "kind": "path-offset",
+ "target": {
+ "sourceFile": "scenes/child.html",
+ "selector": "#child-card",
+ "id": "child-card"
+ },
+ "x": 36,
+ "y": 18
+ }
+ ]
+ }`);
+
+ expect(applyStudioManualEditManifest(document, manifest, "scenes/parent.html")).toBe(2);
+ expect(readStudioPathOffset(parentCard)).toEqual({ x: 12, y: 8 });
+ expect(readStudioPathOffset(childCard)).toEqual({ x: 36, y: 18 });
+ });
+
+ it("applies and clears manifest box sizes while restoring authored inline size", () => {
+ const document = createDocument(`
+ <div style="display: flex; flex-direction: row">
+ <div id="card" style="width: 160px; height: 90px"></div>
+ </div>
+ `);
+ const manifest = parseStudioManualEditManifest(`{
+ "version": 1,
+ "edits": [
+ {
+ "kind": "box-size",
+ "target": { "sourceFile": "index.html", "selector": "#card", "id": "card" },
+ "width": 320,
+ "height": 180
+ }
+ ]
+ }`);
+ const card = document.getElementById("card") as HTMLElement;
+ mockBoundingRect(card, 160, 90);
+
+ expect(applyStudioManualEditManifest(document, manifest, "index.html")).toBe(1);
+ expect(readStudioBoxSize(card)).toEqual({ width: 320, height: 180 });
+ expect(card.style.getPropertyValue("width")).toBe("320px");
+ expect(card.style.getPropertyValue("height")).toBe("180px");
+ expect(card.style.getPropertyValue("flex-basis")).toBe("320px");
+
+ expect(
+ applyStudioManualEditManifest(document, emptyStudioManualEditManifest(), "index.html"),
+ ).toBe(0);
+ expect(readStudioBoxSize(card)).toEqual({ width: 0, height: 0 });
+ expect(card.style.getPropertyValue("width")).toBe("160px");
+ expect(card.style.getPropertyValue("height")).toBe("90px");
+ expect(card.style.getPropertyValue("flex-basis")).toBe("");
+ expect(card.style.getPropertyValue("flex-grow")).toBe("");
+ expect(card.style.getPropertyValue("flex-shrink")).toBe("");
+ expect(card.style.getPropertyValue("scale")).toBe("");
+ });
+
+ it("applies and clears manifest rotations while restoring authored inline rotation", () => {
+ const document = createDocument(
+ `<div id="card" style="rotate: 8deg; transform-origin: left top"></div>`,
+ );
+ const manifest = parseStudioManualEditManifest(`{
+ "version": 1,
+ "edits": [
+ {
+ "kind": "rotation",
+ "target": { "sourceFile": "index.html", "selector": "#card", "id": "card" },
+ "angle": 37.5
+ }
+ ]
+ }`);
+ const card = document.getElementById("card") as HTMLElement;
+
+ expect(applyStudioManualEditManifest(document, manifest, "index.html")).toBe(1);
+ expect(readStudioRotation(card)).toEqual({ angle: 37.5 });
+ expect(card.style.getPropertyValue("rotate")).toContain(STUDIO_ROTATION_PROP);
+ expect(card.style.getPropertyValue("rotate")).toContain("8deg");
+ expect(card.style.getPropertyValue("transform-origin")).toBe("center center");
+
+ expect(
+ applyStudioManualEditManifest(document, emptyStudioManualEditManifest(), "index.html"),
+ ).toBe(0);
+ expect(readStudioRotation(card)).toEqual({ angle: 0 });
+ expect(card.style.getPropertyValue("rotate")).toBe("8deg");
+ expect(card.style.getPropertyValue("transform-origin")).toBe("left top");
+ });
+
+ it("clears stale preview offsets that are no longer in the manifest", () => {
+ const document = createDocument(`<div id="card"></div>`);
+ const card = document.getElementById("card") as HTMLElement;
+
+ applyStudioPathOffset(card, { x: 24, y: 12 });
+ expect(readStudioPathOffset(card)).toEqual({ x: 24, y: 12 });
+
+ expect(
+ applyStudioManualEditManifest(document, emptyStudioManualEditManifest(), "index.html"),
+ ).toBe(0);
+
+ expect(readStudioPathOffset(card)).toEqual({ x: 0, y: 0 });
+ expect(card.style.getPropertyValue(STUDIO_OFFSET_X_PROP)).toBe("");
+ expect(card.style.getPropertyValue(STUDIO_OFFSET_Y_PROP)).toBe("");
+ expect(card.style.getPropertyValue("translate")).toBe("");
+ });
+
+ it("restores authored inline translate when clearing offsets", () => {
+ const document = createDocument(`<div id="card" style="translate: 10px 20px"></div>`);
+ const card = document.getElementById("card") as HTMLElement;
+
+ applyStudioPathOffset(card, { x: 24, y: 12 });
+ expect(card.style.getPropertyValue("translate")).toContain(STUDIO_OFFSET_X_PROP);
+
+ expect(
+ applyStudioManualEditManifest(document, emptyStudioManualEditManifest(), "index.html"),
+ ).toBe(0);
+
+ expect(card.style.getPropertyValue("translate")).toBe("10px 20px");
+ });
+
+ it("does not replay the manifest over an active manual edit gesture", () => {
+ const document = createDocument(`<div id="card"></div>`);
+ const card = document.getElementById("card") as HTMLElement;
+ const manifest = parseStudioManualEditManifest(`{
+ "version": 1,
+ "edits": [
+ {
+ "kind": "path-offset",
+ "target": { "sourceFile": "index.html", "selector": "#card", "id": "card" },
+ "x": 8,
+ "y": 4
+ }
+ ]
+ }`);
+
+ applyStudioPathOffset(card, { x: 40, y: 24 });
+ const firstToken = beginStudioManualEditGesture(card);
+ const secondToken = beginStudioManualEditGesture(card);
+ endStudioManualEditGesture(card, firstToken);
+
+ expect(applyStudioManualEditManifest(document, manifest, "index.html")).toBe(0);
+ expect(readStudioPathOffset(card)).toEqual({ x: 40, y: 24 });
+
+ endStudioManualEditGesture(card, secondToken);
+ expect(applyStudioManualEditManifest(document, manifest, "index.html")).toBe(1);
+ expect(readStudioPathOffset(card)).toEqual({ x: 8, y: 4 });
+ });
+
+ it("reapplies the latest preview manifest after wrapped seeks", () => {
+ const window = new Window();
+ const seekArgs: unknown[][] = [];
+ const previewWindow = window as unknown as Parameters<
+ typeof installStudioManualEditSeekReapply
+ >[0] & {
+ __player: Record<string, unknown>;
+ };
+ previewWindow.__player = {
+ seek: (...args: unknown[]) => {
+ seekArgs.push(args);
+ },
+ };
+
+ let applied = 0;
+ expect(
+ installStudioManualEditSeekReapply(previewWindow, () => {
+ applied += 1;
+ }),
+ ).toBe(true);
+ (previewWindow.__player.seek as (time: number, suppressEvents: boolean) => void)(1, false);
+ expect(applied).toBe(1);
+ expect(seekArgs).toEqual([[1, false]]);
+
+ expect(
+ installStudioManualEditSeekReapply(previewWindow, () => {
+ applied += 10;
+ }),
+ ).toBe(true);
+ (previewWindow.__player.seek as (time: number) => void)(2);
+ expect(applied).toBe(11);
+ });
+
+ it("reapplies manual edits while fresh playback is active", () => {
+ const window = new Window();
+ const frames: FrameRequestCallback[] = [];
+ let playing = false;
+ const previewWindow = window as unknown as Parameters<
+ typeof installStudioManualEditSeekReapply
+ >[0] & {
+ __player: Record<string, unknown>;
+ requestAnimationFrame: (callback: FrameRequestCallback) => number;
+ };
+ previewWindow.requestAnimationFrame = (callback: FrameRequestCallback) => {
+ frames.push(callback);
+ return frames.length;
+ };
+ previewWindow.__player = {
+ play: () => {
+ playing = true;
+ },
+ isPlaying: () => playing,
+ };
+
+ let applied = 0;
+ expect(
+ installStudioManualEditSeekReapply(previewWindow, () => {
+ applied += 1;
+ }),
+ ).toBe(true);
+
+ (previewWindow.__player.play as () => void)();
+ expect(applied).toBe(1);
+ expect(frames).toHaveLength(1);
+
+ frames.shift()?.(16);
+ expect(applied).toBe(2);
+ expect(frames).toHaveLength(1);
+
+ playing = false;
+ frames.shift()?.(32);
+ expect(applied).toBe(3);
+ expect(frames).toHaveLength(0);
+ });
+
+ it("stops playback reapply after an unpaused timeline has completed", () => {
+ const window = new Window();
+ const frames: FrameRequestCallback[] = [];
+ let currentTime = 0;
+ let paused = true;
+ const previewWindow = window as unknown as Parameters<
+ typeof installStudioManualEditSeekReapply
+ >[0] & {
+ __timeline: Record<string, unknown>;
+ requestAnimationFrame: (callback: FrameRequestCallback) => number;
+ };
+ previewWindow.requestAnimationFrame = (callback: FrameRequestCallback) => {
+ frames.push(callback);
+ return frames.length;
+ };
+ previewWindow.__timeline = {
+ play: () => {
+ paused = false;
+ },
+ paused: () => paused,
+ isActive: () => false,
+ time: () => currentTime,
+ duration: () => 2,
+ };
+
+ let applied = 0;
+ expect(
+ installStudioManualEditSeekReapply(previewWindow, () => {
+ applied += 1;
+ }),
+ ).toBe(true);
+
+ (previewWindow.__timeline.play as () => void)();
+ expect(applied).toBe(1);
+ expect(frames).toHaveLength(1);
+
+ currentTime = 2;
+ frames.shift()?.(16);
+ expect(applied).toBe(2);
+ expect(frames).toHaveLength(0);
+ });
+});
diff --git a/packages/studio/src/components/editor/manualEdits.ts b/packages/studio/src/components/editor/manualEdits.ts
new file mode 100644
index 0000000000..04afec3c0b
--- /dev/null
+++ b/packages/studio/src/components/editor/manualEdits.ts
@@ -0,0 +1,1397 @@
+import type { DomEditSelection } from "./domEditing";
+
+export const STUDIO_MANUAL_EDITS_PATH = ".hyperframes/studio-manual-edits.json";
+export const STUDIO_OFFSET_X_PROP = "--hf-studio-offset-x";
+export const STUDIO_OFFSET_Y_PROP = "--hf-studio-offset-y";
+export const STUDIO_WIDTH_PROP = "--hf-studio-width";
+export const STUDIO_HEIGHT_PROP = "--hf-studio-height";
+export const STUDIO_ROTATION_PROP = "--hf-studio-rotation";
+const STUDIO_PATH_OFFSET_ATTR = "data-hf-studio-path-offset";
+const STUDIO_MANUAL_EDIT_GESTURE_ATTR = "data-hf-studio-manual-edit-gesture";
+const STUDIO_BOX_SIZE_ATTR = "data-hf-studio-box-size";
+const STUDIO_ROTATION_ATTR = "data-hf-studio-rotation";
+const STUDIO_ORIGINAL_TRANSLATE_ATTR = "data-hf-studio-original-translate";
+const STUDIO_ORIGINAL_INLINE_TRANSLATE_ATTR = "data-hf-studio-original-inline-translate";
+const STUDIO_ORIGINAL_WIDTH_ATTR = "data-hf-studio-original-width";
+const STUDIO_ORIGINAL_HEIGHT_ATTR = "data-hf-studio-original-height";
+const STUDIO_ORIGINAL_MIN_WIDTH_ATTR = "data-hf-studio-original-min-width";
+const STUDIO_ORIGINAL_MIN_HEIGHT_ATTR = "data-hf-studio-original-min-height";
+const STUDIO_ORIGINAL_MAX_WIDTH_ATTR = "data-hf-studio-original-max-width";
+const STUDIO_ORIGINAL_MAX_HEIGHT_ATTR = "data-hf-studio-original-max-height";
+const STUDIO_ORIGINAL_FLEX_BASIS_ATTR = "data-hf-studio-original-flex-basis";
+const STUDIO_ORIGINAL_FLEX_GROW_ATTR = "data-hf-studio-original-flex-grow";
+const STUDIO_ORIGINAL_FLEX_SHRINK_ATTR = "data-hf-studio-original-flex-shrink";
+const STUDIO_ORIGINAL_BOX_SIZING_ATTR = "data-hf-studio-original-box-sizing";
+const STUDIO_ORIGINAL_SCALE_ATTR = "data-hf-studio-original-scale";
+const STUDIO_ORIGINAL_TRANSFORM_ORIGIN_ATTR = "data-hf-studio-original-transform-origin";
+const STUDIO_ORIGINAL_DISPLAY_ATTR = "data-hf-studio-original-display";
+const STUDIO_ORIGINAL_ROTATE_ATTR = "data-hf-studio-original-rotate";
+const STUDIO_ORIGINAL_INLINE_ROTATE_ATTR = "data-hf-studio-original-inline-rotate";
+const STUDIO_ORIGINAL_ROTATION_TRANSFORM_ORIGIN_ATTR =
+ "data-hf-studio-original-rotation-transform-origin";
+const STUDIO_ROTATION_DRAFT_ATTR = "data-hf-studio-rotation-draft";
+const STUDIO_MANUAL_EDITS_APPLY_PROP = "__hfStudioManualEditsApply";
+const STUDIO_MANUAL_EDITS_WRAPPED_PROP = "__hfStudioManualEditsWrapped";
+const STUDIO_MANUAL_EDITS_PLAYBACK_FRAME_PROP = "__hfStudioManualEditsPlaybackFrame";
+const STUDIO_ROTATION_TRANSFORM_ORIGIN = "center center";
+let studioManualEditGestureId = 0;
+
+export interface StudioManualEditTarget {
+ sourceFile: string;
+ selector?: string;
+ selectorIndex?: number;
+ id?: string;
+}
+
+export interface StudioPathOffsetEdit {
+ kind: "path-offset";
+ target: StudioManualEditTarget;
+ x: number;
+ y: number;
+ updatedAt?: string;
+}
+
+export interface StudioBoxSizeEdit {
+ kind: "box-size";
+ target: StudioManualEditTarget;
+ width: number;
+ height: number;
+ updatedAt?: string;
+}
+
+export interface StudioRotationEdit {
+ kind: "rotation";
+ target: StudioManualEditTarget;
+ angle: number;
+ updatedAt?: string;
+}
+
+export type StudioManualEdit = StudioPathOffsetEdit | StudioBoxSizeEdit | StudioRotationEdit;
+
+export interface StudioManualEditManifest {
+ version: 1;
+ edits: StudioManualEdit[];
+}
+
+type StudioManualEditSeekWindow = Window & {
+ __hf?: Record<string, unknown>;
+ __player?: Record<string, unknown>;
+ __timeline?: Record<string, unknown>;
+ __timelines?: Record<string, Record<string, unknown>>;
+ __hfStudioManualEditsApply?: () => void;
+ __hfStudioManualEditsPlaybackFrame?: number | null;
+};
+
+export function emptyStudioManualEditManifest(): StudioManualEditManifest {
+ return { version: 1, edits: [] };
+}
+
+function finiteNumber(value: unknown): number | null {
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
+}
+
+function parsePathOffsetEdit(value: unknown): StudioPathOffsetEdit | null {
+ if (!value || typeof value !== "object") return null;
+ const record = value as Record<string, unknown>;
+ if (record.kind !== "path-offset") return null;
+ const target = record.target;
+ if (!target || typeof target !== "object") return null;
+ const targetRecord = target as Record<string, unknown>;
+ const sourceFile = typeof targetRecord.sourceFile === "string" ? targetRecord.sourceFile : "";
+ if (!sourceFile) return null;
+
+ const selector = typeof targetRecord.selector === "string" ? targetRecord.selector : undefined;
+ const id = typeof targetRecord.id === "string" ? targetRecord.id : undefined;
+ if (!selector && !id) return null;
+
+ const x = finiteNumber(record.x);
+ const y = finiteNumber(record.y);
+ if (x == null || y == null) return null;
+
+ return {
+ kind: "path-offset",
+ target: {
+ sourceFile,
+ selector,
+ selectorIndex: finiteNumber(targetRecord.selectorIndex) ?? undefined,
+ id,
+ },
+ x,
+ y,
+ updatedAt: typeof record.updatedAt === "string" ? record.updatedAt : undefined,
+ };
+}
+
+function parseBoxSizeEdit(value: unknown): StudioBoxSizeEdit | null {
+ if (!value || typeof value !== "object") return null;
+ const record = value as Record<string, unknown>;
+ if (record.kind !== "box-size") return null;
+ const target = record.target;
+ if (!target || typeof target !== "object") return null;
+ const targetRecord = target as Record<string, unknown>;
+ const sourceFile = typeof targetRecord.sourceFile === "string" ? targetRecord.sourceFile : "";
+ if (!sourceFile) return null;
+
+ const selector = typeof targetRecord.selector === "string" ? targetRecord.selector : undefined;
+ const id = typeof targetRecord.id === "string" ? targetRecord.id : undefined;
+ if (!selector && !id) return null;
+
+ const width = finiteNumber(record.width);
+ const height = finiteNumber(record.height);
+ if (width == null || height == null || width <= 0 || height <= 0) return null;
+
+ return {
+ kind: "box-size",
+ target: {
+ sourceFile,
+ selector,
+ selectorIndex: finiteNumber(targetRecord.selectorIndex) ?? undefined,
+ id,
+ },
+ width,
+ height,
+ updatedAt: typeof record.updatedAt === "string" ? record.updatedAt : undefined,
+ };
+}
+
+function parseRotationEdit(value: unknown): StudioRotationEdit | null {
+ if (!value || typeof value !== "object") return null;
+ const record = value as Record<string, unknown>;
+ if (record.kind !== "rotation") return null;
+ const target = record.target;
+ if (!target || typeof target !== "object") return null;
+ const targetRecord = target as Record<string, unknown>;
+ const sourceFile = typeof targetRecord.sourceFile === "string" ? targetRecord.sourceFile : "";
+ if (!sourceFile) return null;
+
+ const selector = typeof targetRecord.selector === "string" ? targetRecord.selector : undefined;
+ const id = typeof targetRecord.id === "string" ? targetRecord.id : undefined;
+ if (!selector && !id) return null;
+
+ const angle = finiteNumber(record.angle);
+ if (angle == null) return null;
+
+ return {
+ kind: "rotation",
+ target: {
+ sourceFile,
+ selector,
+ selectorIndex: finiteNumber(targetRecord.selectorIndex) ?? undefined,
+ id,
+ },
+ angle,
+ updatedAt: typeof record.updatedAt === "string" ? record.updatedAt : undefined,
+ };
+}
+
+function parseManualEdit(value: unknown): StudioManualEdit | null {
+ return parsePathOffsetEdit(value) ?? parseBoxSizeEdit(value) ?? parseRotationEdit(value);
+}
+
+export function parseStudioManualEditManifest(content: string): StudioManualEditManifest {
+ if (!content.trim()) return emptyStudioManualEditManifest();
+
+ try {
+ const parsed = JSON.parse(content) as unknown;
+ if (!parsed || typeof parsed !== "object") return emptyStudioManualEditManifest();
+ const edits = (parsed as { edits?: unknown }).edits;
+ if (!Array.isArray(edits)) return emptyStudioManualEditManifest();
+ return {
+ version: 1,
+ edits: edits.map(parseManualEdit).filter((edit): edit is StudioManualEdit => edit !== null),
+ };
+ } catch {
+ return emptyStudioManualEditManifest();
+ }
+}
+
+export function serializeStudioManualEditManifest(manifest: StudioManualEditManifest): string {
+ return `${JSON.stringify(manifest, null, 2)}\n`;
+}
+
+function normalizeStudioFileChangePath(path: string): string {
+ return path
+ .trim()
+ .replace(/\\/g, "/")
+ .replace(/^\.?\//, "");
+}
+
+function readStudioFileChangePathFromValue(value: unknown): string | null {
+ if (typeof value === "string") {
+ const trimmed = value.trim();
+ if (!trimmed) return null;
+ if (trimmed.startsWith("{")) {
+ try {
+ return readStudioFileChangePathFromValue(JSON.parse(trimmed) as unknown);
+ } catch {
+ return normalizeStudioFileChangePath(trimmed);
+ }
+ }
+ return normalizeStudioFileChangePath(trimmed);
+ }
+
+ if (!value || typeof value !== "object") return null;
+ const record = value as Record<string, unknown>;
+ if (typeof record.path === "string") return normalizeStudioFileChangePath(record.path);
+ if (typeof record.filePath === "string") return normalizeStudioFileChangePath(record.filePath);
+ if ("data" in record) return readStudioFileChangePathFromValue(record.data);
+ return null;
+}
+
+export function readStudioFileChangePath(payload: unknown): string | null {
+ return readStudioFileChangePathFromValue(payload);
+}
+
+export function isStudioManualEditManifestPath(path: string | null): boolean {
+ if (!path) return false;
+ const normalized = normalizeStudioFileChangePath(path);
+ return (
+ normalized === STUDIO_MANUAL_EDITS_PATH || normalized.endsWith(`/${STUDIO_MANUAL_EDITS_PATH}`)
+ );
+}
+
+function selectionTarget(selection: DomEditSelection): StudioManualEditTarget {
+ return {
+ sourceFile: selection.sourceFile || "index.html",
+ selector: selection.selector,
+ selectorIndex: selection.selectorIndex,
+ id: selection.id ?? undefined,
+ };
+}
+
+function targetKey(target: StudioManualEditTarget): string {
+ return [
+ target.sourceFile,
+ target.id ?? "",
+ target.selector ?? "",
+ target.selectorIndex ?? "",
+ ].join("|");
+}
+
+function roundRotationAngle(angle: number): number {
+ return Math.round(angle * 10) / 10;
+}
+
+export function upsertStudioPathOffsetEdit(
+ manifest: StudioManualEditManifest,
+ selection: DomEditSelection,
+ offset: { x: number; y: number },
+): StudioManualEditManifest {
+ const target = selectionTarget(selection);
+ const key = targetKey(target);
+ const nextEdit: StudioPathOffsetEdit = {
+ kind: "path-offset",
+ target,
+ x: Math.round(offset.x),
+ y: Math.round(offset.y),
+ updatedAt: new Date().toISOString(),
+ };
+
+ const edits = manifest.edits.filter(
+ (edit) => edit.kind !== "path-offset" || targetKey(edit.target) !== key,
+ );
+ edits.push(nextEdit);
+ return { version: 1, edits };
+}
+
+export function upsertStudioBoxSizeEdit(
+ manifest: StudioManualEditManifest,
+ selection: DomEditSelection,
+ size: { width: number; height: number },
+): StudioManualEditManifest {
+ const target = selectionTarget(selection);
+ const key = targetKey(target);
+ const nextEdit: StudioBoxSizeEdit = {
+ kind: "box-size",
+ target,
+ width: Math.round(Math.max(1, size.width)),
+ height: Math.round(Math.max(1, size.height)),
+ updatedAt: new Date().toISOString(),
+ };
+
+ const edits = manifest.edits.filter(
+ (edit) => edit.kind !== "box-size" || targetKey(edit.target) !== key,
+ );
+ edits.push(nextEdit);
+ return { version: 1, edits };
+}
+
+export function upsertStudioRotationEdit(
+ manifest: StudioManualEditManifest,
+ selection: DomEditSelection,
+ rotation: { angle: number },
+): StudioManualEditManifest {
+ const target = selectionTarget(selection);
+ const key = targetKey(target);
+ const nextEdit: StudioRotationEdit = {
+ kind: "rotation",
+ target,
+ angle: roundRotationAngle(rotation.angle),
+ updatedAt: new Date().toISOString(),
+ };
+
+ const edits = manifest.edits.filter(
+ (edit) => edit.kind !== "rotation" || targetKey(edit.target) !== key,
+ );
+ edits.push(nextEdit);
+ return { version: 1, edits };
+}
+
+export function removeStudioManualEditsForSelection(
+ manifest: StudioManualEditManifest,
+ selection: DomEditSelection,
+): StudioManualEditManifest {
+ const key = targetKey(selectionTarget(selection));
+ const edits = manifest.edits.filter((edit) => targetKey(edit.target) !== key);
+ if (edits.length === manifest.edits.length) return manifest;
+ return { version: 1, edits };
+}
+
+function readPxCustomProperty(element: HTMLElement, property: string): number {
+ const value = Number.parseFloat(element.style.getPropertyValue(property));
+ return Number.isFinite(value) ? value : 0;
+}
+
+function readDegreeCustomProperty(element: HTMLElement, property: string): number {
+ const value = Number.parseFloat(element.style.getPropertyValue(property));
+ return Number.isFinite(value) ? value : 0;
+}
+
+export function readStudioPathOffset(element: HTMLElement): { x: number; y: number } {
+ return {
+ x: readPxCustomProperty(element, STUDIO_OFFSET_X_PROP),
+ y: readPxCustomProperty(element, STUDIO_OFFSET_Y_PROP),
+ };
+}
+
+export function readStudioBoxSize(element: HTMLElement): { width: number; height: number } {
+ return {
+ width: readPxCustomProperty(element, STUDIO_WIDTH_PROP),
+ height: readPxCustomProperty(element, STUDIO_HEIGHT_PROP),
+ };
+}
+
+export function readStudioRotation(element: HTMLElement): { angle: number } {
+ return {
+ angle: readDegreeCustomProperty(element, STUDIO_ROTATION_PROP),
+ };
+}
+
+export function beginStudioManualEditGesture(element: HTMLElement): string {
+ studioManualEditGestureId += 1;
+ const token = `gesture-${studioManualEditGestureId}`;
+ element.setAttribute(STUDIO_MANUAL_EDIT_GESTURE_ATTR, token);
+ return token;
+}
+
+export function endStudioManualEditGesture(element: HTMLElement, token?: string): void {
+ if (token && element.getAttribute(STUDIO_MANUAL_EDIT_GESTURE_ATTR) !== token) return;
+ element.removeAttribute(STUDIO_MANUAL_EDIT_GESTURE_ATTR);
+}
+
+function isStudioManualEditGestureActive(element: HTMLElement): boolean {
+ return element.hasAttribute(STUDIO_MANUAL_EDIT_GESTURE_ATTR);
+}
+
+export function isStudioManualEditGestureCurrent(element: HTMLElement, token: string): boolean {
+ return element.getAttribute(STUDIO_MANUAL_EDIT_GESTURE_ATTR) === token;
+}
+
+function splitTopLevelWhitespace(value: string): string[] {
+ const parts: string[] = [];
+ let depth = 0;
+ let current = "";
+ for (const char of value.trim()) {
+ if (char === "(") depth += 1;
+ if (char === ")") depth = Math.max(0, depth - 1);
+ if (/\s/.test(char) && depth === 0) {
+ if (current) parts.push(current);
+ current = "";
+ } else {
+ current += char;
+ }
+ }
+ if (current) parts.push(current);
+ return parts;
+}
+
+function composeTranslateValue(element: HTMLElement, x: string, y: string): string {
+ const original = element.getAttribute(STUDIO_ORIGINAL_TRANSLATE_ATTR)?.trim();
+ if (!original || original === "none") return `${x} ${y}`;
+
+ const parts = splitTopLevelWhitespace(original);
+ if (parts.length === 1) return `calc(${parts[0]} + ${x}) ${y}`;
+ if (parts.length === 2) return `calc(${parts[0]} + ${x}) calc(${parts[1]} + ${y})`;
+ if (parts.length === 3) {
+ return `calc(${parts[0]} + ${x}) calc(${parts[1]} + ${y}) ${parts[2]}`;
+ }
+ return `${x} ${y}`;
+}
+
+function readTransformLonghandBase(element: HTMLElement, property: "translate" | "rotate"): string {
+ const value = readStyleOrComputed(element, property).trim();
+ return value === "none" ? "" : value;
+}
+
+function prepareStudioPathOffsetBase(element: HTMLElement, updateBase: boolean): void {
+ const inlineTranslate = element.style.getPropertyValue("translate");
+ const currentTranslate = readTransformLonghandBase(element, "translate");
+ const hasMarker = element.hasAttribute(STUDIO_PATH_OFFSET_ATTR);
+ const wasResetByAnimation = !styleUsesStudioOffset(currentTranslate);
+ if (!hasMarker) {
+ element.setAttribute(
+ STUDIO_ORIGINAL_INLINE_TRANSLATE_ATTR,
+ styleUsesStudioOffset(inlineTranslate) ? "" : inlineTranslate,
+ );
+ element.setAttribute(
+ STUDIO_ORIGINAL_TRANSLATE_ATTR,
+ wasResetByAnimation ? currentTranslate : "",
+ );
+ } else if (updateBase && wasResetByAnimation && !isStudioManualEditGestureActive(element)) {
+ element.setAttribute(STUDIO_ORIGINAL_TRANSLATE_ATTR, currentTranslate);
+ }
+}
+
+function writeStudioPathOffsetVars(
+ element: HTMLElement,
+ offset: { x: number; y: number },
+ options: { updateBase?: boolean } = {},
+): void {
+ prepareStudioPathOffsetBase(element, options.updateBase ?? true);
+ element.setAttribute(STUDIO_PATH_OFFSET_ATTR, "true");
+ element.style.setProperty(STUDIO_OFFSET_X_PROP, `${Math.round(offset.x)}px`);
+ element.style.setProperty(STUDIO_OFFSET_Y_PROP, `${Math.round(offset.y)}px`);
+}
+
+function writeStudioBoxSizeVars(
+ element: HTMLElement,
+ size: { width: number; height: number },
+): void {
+ if (!element.hasAttribute(STUDIO_BOX_SIZE_ATTR)) {
+ element.setAttribute(STUDIO_ORIGINAL_WIDTH_ATTR, element.style.getPropertyValue("width"));
+ element.setAttribute(STUDIO_ORIGINAL_HEIGHT_ATTR, element.style.getPropertyValue("height"));
+ element.setAttribute(
+ STUDIO_ORIGINAL_MIN_WIDTH_ATTR,
+ element.style.getPropertyValue("min-width"),
+ );
+ element.setAttribute(
+ STUDIO_ORIGINAL_MIN_HEIGHT_ATTR,
+ element.style.getPropertyValue("min-height"),
+ );
+ element.setAttribute(
+ STUDIO_ORIGINAL_MAX_WIDTH_ATTR,
+ element.style.getPropertyValue("max-width"),
+ );
+ element.setAttribute(
+ STUDIO_ORIGINAL_MAX_HEIGHT_ATTR,
+ element.style.getPropertyValue("max-height"),
+ );
+ element.setAttribute(
+ STUDIO_ORIGINAL_FLEX_BASIS_ATTR,
+ element.style.getPropertyValue("flex-basis"),
+ );
+ element.setAttribute(
+ STUDIO_ORIGINAL_FLEX_GROW_ATTR,
+ element.style.getPropertyValue("flex-grow"),
+ );
+ element.setAttribute(
+ STUDIO_ORIGINAL_FLEX_SHRINK_ATTR,
+ element.style.getPropertyValue("flex-shrink"),
+ );
+ element.setAttribute(
+ STUDIO_ORIGINAL_BOX_SIZING_ATTR,
+ element.style.getPropertyValue("box-sizing"),
+ );
+ element.setAttribute(STUDIO_ORIGINAL_SCALE_ATTR, element.style.getPropertyValue("scale"));
+ element.setAttribute(
+ STUDIO_ORIGINAL_TRANSFORM_ORIGIN_ATTR,
+ element.style.getPropertyValue("transform-origin"),
+ );
+ element.setAttribute(STUDIO_ORIGINAL_DISPLAY_ATTR, element.style.getPropertyValue("display"));
+ }
+
+ element.setAttribute(STUDIO_BOX_SIZE_ATTR, "true");
+ element.style.setProperty(STUDIO_WIDTH_PROP, `${Math.round(Math.max(1, size.width))}px`);
+ element.style.setProperty(STUDIO_HEIGHT_PROP, `${Math.round(Math.max(1, size.height))}px`);
+}
+
+function prepareStudioRotationBase(element: HTMLElement, updateBase: boolean): void {
+ const inlineRotate = element.style.getPropertyValue("rotate");
+ const currentRotate = readTransformLonghandBase(element, "rotate");
+ const hasMarker = element.hasAttribute(STUDIO_ROTATION_ATTR);
+ const wasResetByAnimation =
+ !styleUsesStudioRotation(currentRotate) &&
+ !styleMatchesStudioRotationDraft(element, currentRotate);
+ if (!hasMarker) {
+ element.setAttribute(
+ STUDIO_ORIGINAL_INLINE_ROTATE_ATTR,
+ styleUsesStudioRotation(inlineRotate) ? "" : inlineRotate,
+ );
+ element.setAttribute(STUDIO_ORIGINAL_ROTATE_ATTR, wasResetByAnimation ? currentRotate : "");
+ } else if (updateBase && wasResetByAnimation && !isStudioManualEditGestureActive(element)) {
+ element.setAttribute(STUDIO_ORIGINAL_ROTATE_ATTR, currentRotate);
+ }
+ if (!element.hasAttribute(STUDIO_ORIGINAL_ROTATION_TRANSFORM_ORIGIN_ATTR)) {
+ element.setAttribute(
+ STUDIO_ORIGINAL_ROTATION_TRANSFORM_ORIGIN_ATTR,
+ element.style.getPropertyValue("transform-origin"),
+ );
+ }
+}
+
+function writeStudioRotationVars(
+ element: HTMLElement,
+ rotation: { angle: number },
+ options: { updateBase?: boolean } = {},
+): void {
+ prepareStudioRotationBase(element, options.updateBase ?? true);
+ element.setAttribute(STUDIO_ROTATION_ATTR, "true");
+ element.style.setProperty(STUDIO_ROTATION_PROP, `${roundRotationAngle(rotation.angle)}deg`);
+ element.style.setProperty("transform-origin", STUDIO_ROTATION_TRANSFORM_ORIGIN);
+}
+
+function isSimpleRotateAngle(value: string): boolean {
+ return /^-?(?:\d+(?:\.\d+)?|\.\d+)(?:deg|rad|turn|grad)$/.test(value.trim());
+}
+
+function composeStudioRotationValue(element: HTMLElement, rotationValue: string): string {
+ const original = element.getAttribute(STUDIO_ORIGINAL_ROTATE_ATTR)?.trim();
+ if (!original || original === "none" || !isSimpleRotateAngle(original)) {
+ return rotationValue;
+ }
+ return `calc(${original} + ${rotationValue})`;
+}
+
+function safeComputedStyleProperty(element: HTMLElement, property: string): string {
+ try {
+ return (
+ element.ownerDocument.defaultView?.getComputedStyle(element).getPropertyValue(property) ?? ""
+ );
+ } catch {
+ return "";
+ }
+}
+
+function readStyleOrComputed(element: HTMLElement, property: string): string {
+ return element.style.getPropertyValue(property) || safeComputedStyleProperty(element, property);
+}
+
+function readParentFlexBasisPixels(
+ element: HTMLElement,
+ size: { width: number; height: number },
+): number | null {
+ const parent = element.parentElement;
+ if (!parent) return null;
+
+ const display = readStyleOrComputed(parent, "display").trim();
+ if (display !== "flex" && display !== "inline-flex") return null;
+
+ const direction = readStyleOrComputed(parent, "flex-direction").trim();
+ return Math.round(Math.max(1, direction.startsWith("column") ? size.height : size.width));
+}
+
+function restoreStaleStudioScaleResize(element: HTMLElement): void {
+ if (!element.hasAttribute(STUDIO_ORIGINAL_SCALE_ATTR)) return;
+ restoreOriginalBoxSizeProperty(element, "scale", STUDIO_ORIGINAL_SCALE_ATTR);
+ restoreOriginalBoxSizeProperty(
+ element,
+ "transform-origin",
+ STUDIO_ORIGINAL_TRANSFORM_ORIGIN_ATTR,
+ );
+}
+
+function applyStudioBoxSizeDimensions(
+ element: HTMLElement,
+ size: { width: number; height: number },
+): void {
+ writeStudioBoxSizeVars(element, size);
+ restoreStaleStudioScaleResize(element);
+
+ const width = Math.round(Math.max(1, size.width));
+ const height = Math.round(Math.max(1, size.height));
+ element.style.setProperty("box-sizing", "border-box");
+ element.style.setProperty("width", `${width}px`);
+ element.style.setProperty("height", `${height}px`);
+ element.style.setProperty("min-width", "0px");
+ element.style.setProperty("min-height", "0px");
+ element.style.setProperty("max-width", "none");
+ element.style.setProperty("max-height", "none");
+ const flexBasis = readParentFlexBasisPixels(element, size);
+ if (flexBasis != null) {
+ element.style.setProperty("flex-basis", `${flexBasis}px`);
+ element.style.setProperty("flex-grow", "0");
+ element.style.setProperty("flex-shrink", "0");
+ }
+ const computedDisplay = safeComputedStyleProperty(element, "display");
+ if (computedDisplay === "inline") {
+ element.style.setProperty("display", "inline-block");
+ }
+}
+
+function styleUsesStudioOffset(value: string): boolean {
+ return value.includes(STUDIO_OFFSET_X_PROP) || value.includes(STUDIO_OFFSET_Y_PROP);
+}
+
+function styleUsesStudioSize(value: string): boolean {
+ return value.includes(STUDIO_WIDTH_PROP) || value.includes(STUDIO_HEIGHT_PROP);
+}
+
+function styleUsesStudioRotation(value: string): boolean {
+ return value.includes(STUDIO_ROTATION_PROP);
+}
+
+function compactStyleValue(value: string): string {
+ return value.replace(/\s+/g, "").toLowerCase();
+}
+
+function styleMatchesStudioRotationDraft(element: HTMLElement, value: string): boolean {
+ if (!element.hasAttribute(STUDIO_ROTATION_DRAFT_ATTR)) return false;
+ const rotation = element.style.getPropertyValue(STUDIO_ROTATION_PROP).trim();
+ if (!rotation || !value.trim()) return false;
+ return (
+ compactStyleValue(value) === compactStyleValue(composeStudioRotationValue(element, rotation))
+ );
+}
+
+export function applyStudioPathOffset(
+ element: HTMLElement,
+ offset: { x: number; y: number },
+): void {
+ writeStudioPathOffsetVars(element, offset);
+ element.style.setProperty(
+ "translate",
+ composeTranslateValue(
+ element,
+ `var(${STUDIO_OFFSET_X_PROP}, 0px)`,
+ `var(${STUDIO_OFFSET_Y_PROP}, 0px)`,
+ ),
+ );
+}
+
+export function applyStudioPathOffsetDraft(
+ element: HTMLElement,
+ offset: { x: number; y: number },
+): void {
+ writeStudioPathOffsetVars(element, offset, { updateBase: false });
+ element.style.setProperty(
+ "translate",
+ composeTranslateValue(element, `${Math.round(offset.x)}px`, `${Math.round(offset.y)}px`),
+ );
+}
+
+export function applyStudioBoxSize(
+ element: HTMLElement,
+ size: { width: number; height: number },
+): void {
+ applyStudioBoxSizeDimensions(element, size);
+}
+
+export function applyStudioBoxSizeDraft(
+ element: HTMLElement,
+ size: { width: number; height: number },
+): void {
+ applyStudioBoxSizeDimensions(element, size);
+}
+
+export function applyStudioRotation(element: HTMLElement, rotation: { angle: number }): void {
+ writeStudioRotationVars(element, rotation);
+ element.removeAttribute(STUDIO_ROTATION_DRAFT_ATTR);
+ element.style.setProperty(
+ "rotate",
+ composeStudioRotationValue(element, `var(${STUDIO_ROTATION_PROP}, 0deg)`),
+ );
+}
+
+export function applyStudioRotationDraft(element: HTMLElement, rotation: { angle: number }): void {
+ writeStudioRotationVars(element, rotation, { updateBase: false });
+ element.setAttribute(STUDIO_ROTATION_DRAFT_ATTR, "true");
+ element.style.setProperty(
+ "rotate",
+ composeStudioRotationValue(element, `${roundRotationAngle(rotation.angle)}deg`),
+ );
+}
+
+function clearStudioPathOffset(element: HTMLElement): void {
+ if (
+ element.hasAttribute(STUDIO_PATH_OFFSET_ATTR) ||
+ styleUsesStudioOffset(element.style.getPropertyValue("translate"))
+ ) {
+ restoreOriginalTranslateProperty(element);
+ }
+ element.style.removeProperty(STUDIO_OFFSET_X_PROP);
+ element.style.removeProperty(STUDIO_OFFSET_Y_PROP);
+ element.removeAttribute(STUDIO_PATH_OFFSET_ATTR);
+ element.removeAttribute(STUDIO_ORIGINAL_TRANSLATE_ATTR);
+ element.removeAttribute(STUDIO_ORIGINAL_INLINE_TRANSLATE_ATTR);
+}
+
+function clearStudioRotation(element: HTMLElement): void {
+ if (
+ element.hasAttribute(STUDIO_ROTATION_ATTR) ||
+ styleUsesStudioRotation(element.style.getPropertyValue("rotate"))
+ ) {
+ restoreOriginalRotationProperty(element);
+ }
+
+ element.style.removeProperty(STUDIO_ROTATION_PROP);
+ element.removeAttribute(STUDIO_ROTATION_ATTR);
+ element.removeAttribute(STUDIO_ROTATION_DRAFT_ATTR);
+ element.removeAttribute(STUDIO_ORIGINAL_ROTATE_ATTR);
+ element.removeAttribute(STUDIO_ORIGINAL_INLINE_ROTATE_ATTR);
+ element.removeAttribute(STUDIO_ORIGINAL_ROTATION_TRANSFORM_ORIGIN_ATTR);
+}
+
+function restoreOriginalBoxSizeProperty(
+ element: HTMLElement,
+ property:
+ | "width"
+ | "height"
+ | "min-width"
+ | "min-height"
+ | "max-width"
+ | "max-height"
+ | "flex-basis"
+ | "flex-grow"
+ | "flex-shrink"
+ | "box-sizing"
+ | "scale"
+ | "transform-origin"
+ | "display",
+ attribute: string,
+): void {
+ const original = element.getAttribute(attribute);
+ if (original == null || original === "") element.style.removeProperty(property);
+ else element.style.setProperty(property, original);
+ element.removeAttribute(attribute);
+}
+
+function restoreOriginalRotationProperty(element: HTMLElement): void {
+ const original = element.getAttribute(STUDIO_ORIGINAL_INLINE_ROTATE_ATTR);
+ if (original == null || original === "") element.style.removeProperty("rotate");
+ else element.style.setProperty("rotate", original);
+ element.removeAttribute(STUDIO_ORIGINAL_INLINE_ROTATE_ATTR);
+ element.removeAttribute(STUDIO_ORIGINAL_ROTATE_ATTR);
+
+ const originalTransformOrigin = element.getAttribute(
+ STUDIO_ORIGINAL_ROTATION_TRANSFORM_ORIGIN_ATTR,
+ );
+ if (originalTransformOrigin != null) {
+ if (originalTransformOrigin === "") element.style.removeProperty("transform-origin");
+ else element.style.setProperty("transform-origin", originalTransformOrigin);
+ }
+ element.removeAttribute(STUDIO_ORIGINAL_ROTATION_TRANSFORM_ORIGIN_ATTR);
+}
+
+function restoreOriginalTranslateProperty(element: HTMLElement): void {
+ const original = element.getAttribute(STUDIO_ORIGINAL_INLINE_TRANSLATE_ATTR);
+ if (original == null || original === "") element.style.removeProperty("translate");
+ else element.style.setProperty("translate", original);
+ element.removeAttribute(STUDIO_ORIGINAL_INLINE_TRANSLATE_ATTR);
+ element.removeAttribute(STUDIO_ORIGINAL_TRANSLATE_ATTR);
+}
+
+function clearStudioBoxSize(element: HTMLElement): void {
+ if (
+ element.hasAttribute(STUDIO_BOX_SIZE_ATTR) ||
+ styleUsesStudioSize(element.style.getPropertyValue("width")) ||
+ styleUsesStudioSize(element.style.getPropertyValue("height")) ||
+ element.hasAttribute(STUDIO_ORIGINAL_SCALE_ATTR)
+ ) {
+ restoreOriginalBoxSizeProperty(element, "width", STUDIO_ORIGINAL_WIDTH_ATTR);
+ restoreOriginalBoxSizeProperty(element, "height", STUDIO_ORIGINAL_HEIGHT_ATTR);
+ restoreOriginalBoxSizeProperty(element, "min-width", STUDIO_ORIGINAL_MIN_WIDTH_ATTR);
+ restoreOriginalBoxSizeProperty(element, "min-height", STUDIO_ORIGINAL_MIN_HEIGHT_ATTR);
+ restoreOriginalBoxSizeProperty(element, "max-width", STUDIO_ORIGINAL_MAX_WIDTH_ATTR);
+ restoreOriginalBoxSizeProperty(element, "max-height", STUDIO_ORIGINAL_MAX_HEIGHT_ATTR);
+ restoreOriginalBoxSizeProperty(element, "flex-basis", STUDIO_ORIGINAL_FLEX_BASIS_ATTR);
+ restoreOriginalBoxSizeProperty(element, "flex-grow", STUDIO_ORIGINAL_FLEX_GROW_ATTR);
+ restoreOriginalBoxSizeProperty(element, "flex-shrink", STUDIO_ORIGINAL_FLEX_SHRINK_ATTR);
+ restoreOriginalBoxSizeProperty(element, "box-sizing", STUDIO_ORIGINAL_BOX_SIZING_ATTR);
+ restoreOriginalBoxSizeProperty(element, "scale", STUDIO_ORIGINAL_SCALE_ATTR);
+ restoreOriginalBoxSizeProperty(
+ element,
+ "transform-origin",
+ STUDIO_ORIGINAL_TRANSFORM_ORIGIN_ATTR,
+ );
+ restoreOriginalBoxSizeProperty(element, "display", STUDIO_ORIGINAL_DISPLAY_ATTR);
+ }
+
+ element.style.removeProperty(STUDIO_WIDTH_PROP);
+ element.style.removeProperty(STUDIO_HEIGHT_PROP);
+ element.removeAttribute(STUDIO_BOX_SIZE_ATTR);
+}
+
+export interface StudioBoxSizeSnapshot {
+ width: string;
+ height: string;
+ minWidth: string;
+ minHeight: string;
+ maxWidth: string;
+ maxHeight: string;
+ flexBasis: string;
+ flexGrow: string;
+ flexShrink: string;
+ boxSizing: string;
+ scale: string;
+ transformOrigin: string;
+ display: string;
+ studioWidth: string;
+ studioHeight: string;
+ marker: string | null;
+ originalWidth: string | null;
+ originalHeight: string | null;
+ originalMinWidth: string | null;
+ originalMinHeight: string | null;
+ originalMaxWidth: string | null;
+ originalMaxHeight: string | null;
+ originalFlexBasis: string | null;
+ originalFlexGrow: string | null;
+ originalFlexShrink: string | null;
+ originalBoxSizing: string | null;
+ originalScale: string | null;
+ originalTransformOrigin: string | null;
+ originalDisplay: string | null;
+}
+
+export interface StudioRotationSnapshot {
+ rotate: string;
+ transformOrigin: string;
+ studioRotation: string;
+ marker: string | null;
+ draftMarker: string | null;
+ originalRotate: string | null;
+ originalInlineRotate: string | null;
+ originalTransformOrigin: string | null;
+}
+
+export interface StudioPathOffsetSnapshot {
+ translate: string;
+ x: string;
+ y: string;
+ marker: string | null;
+ originalTranslate: string | null;
+ originalInlineTranslate: string | null;
+}
+
+export function captureStudioBoxSize(element: HTMLElement): StudioBoxSizeSnapshot {
+ return {
+ width: element.style.getPropertyValue("width"),
+ height: element.style.getPropertyValue("height"),
+ minWidth: element.style.getPropertyValue("min-width"),
+ minHeight: element.style.getPropertyValue("min-height"),
+ maxWidth: element.style.getPropertyValue("max-width"),
+ maxHeight: element.style.getPropertyValue("max-height"),
+ flexBasis: element.style.getPropertyValue("flex-basis"),
+ flexGrow: element.style.getPropertyValue("flex-grow"),
+ flexShrink: element.style.getPropertyValue("flex-shrink"),
+ boxSizing: element.style.getPropertyValue("box-sizing"),
+ scale: element.style.getPropertyValue("scale"),
+ transformOrigin: element.style.getPropertyValue("transform-origin"),
+ display: element.style.getPropertyValue("display"),
+ studioWidth: element.style.getPropertyValue(STUDIO_WIDTH_PROP),
+ studioHeight: element.style.getPropertyValue(STUDIO_HEIGHT_PROP),
+ marker: element.getAttribute(STUDIO_BOX_SIZE_ATTR),
+ originalWidth: element.getAttribute(STUDIO_ORIGINAL_WIDTH_ATTR),
+ originalHeight: element.getAttribute(STUDIO_ORIGINAL_HEIGHT_ATTR),
+ originalMinWidth: element.getAttribute(STUDIO_ORIGINAL_MIN_WIDTH_ATTR),
+ originalMinHeight: element.getAttribute(STUDIO_ORIGINAL_MIN_HEIGHT_ATTR),
+ originalMaxWidth: element.getAttribute(STUDIO_ORIGINAL_MAX_WIDTH_ATTR),
+ originalMaxHeight: element.getAttribute(STUDIO_ORIGINAL_MAX_HEIGHT_ATTR),
+ originalFlexBasis: element.getAttribute(STUDIO_ORIGINAL_FLEX_BASIS_ATTR),
+ originalFlexGrow: element.getAttribute(STUDIO_ORIGINAL_FLEX_GROW_ATTR),
+ originalFlexShrink: element.getAttribute(STUDIO_ORIGINAL_FLEX_SHRINK_ATTR),
+ originalBoxSizing: element.getAttribute(STUDIO_ORIGINAL_BOX_SIZING_ATTR),
+ originalScale: element.getAttribute(STUDIO_ORIGINAL_SCALE_ATTR),
+ originalTransformOrigin: element.getAttribute(STUDIO_ORIGINAL_TRANSFORM_ORIGIN_ATTR),
+ originalDisplay: element.getAttribute(STUDIO_ORIGINAL_DISPLAY_ATTR),
+ };
+}
+
+export function captureStudioRotation(element: HTMLElement): StudioRotationSnapshot {
+ return {
+ rotate: element.style.getPropertyValue("rotate"),
+ transformOrigin: element.style.getPropertyValue("transform-origin"),
+ studioRotation: element.style.getPropertyValue(STUDIO_ROTATION_PROP),
+ marker: element.getAttribute(STUDIO_ROTATION_ATTR),
+ draftMarker: element.getAttribute(STUDIO_ROTATION_DRAFT_ATTR),
+ originalRotate: element.getAttribute(STUDIO_ORIGINAL_ROTATE_ATTR),
+ originalInlineRotate: element.getAttribute(STUDIO_ORIGINAL_INLINE_ROTATE_ATTR),
+ originalTransformOrigin: element.getAttribute(STUDIO_ORIGINAL_ROTATION_TRANSFORM_ORIGIN_ATTR),
+ };
+}
+
+export function captureStudioPathOffset(element: HTMLElement): StudioPathOffsetSnapshot {
+ return {
+ translate: element.style.getPropertyValue("translate"),
+ x: element.style.getPropertyValue(STUDIO_OFFSET_X_PROP),
+ y: element.style.getPropertyValue(STUDIO_OFFSET_Y_PROP),
+ marker: element.getAttribute(STUDIO_PATH_OFFSET_ATTR),
+ originalTranslate: element.getAttribute(STUDIO_ORIGINAL_TRANSLATE_ATTR),
+ originalInlineTranslate: element.getAttribute(STUDIO_ORIGINAL_INLINE_TRANSLATE_ATTR),
+ };
+}
+
+function restoreAttribute(element: HTMLElement, attribute: string, value: string | null): void {
+ if (value == null) element.removeAttribute(attribute);
+ else element.setAttribute(attribute, value);
+}
+
+function restoreStyleProperty(element: HTMLElement, property: string, value: string): void {
+ if (value) element.style.setProperty(property, value);
+ else element.style.removeProperty(property);
+}
+
+export function restoreStudioBoxSize(element: HTMLElement, previous: StudioBoxSizeSnapshot): void {
+ restoreStyleProperty(element, "width", previous.width);
+ restoreStyleProperty(element, "height", previous.height);
+ restoreStyleProperty(element, "min-width", previous.minWidth);
+ restoreStyleProperty(element, "min-height", previous.minHeight);
+ restoreStyleProperty(element, "max-width", previous.maxWidth);
+ restoreStyleProperty(element, "max-height", previous.maxHeight);
+ restoreStyleProperty(element, "flex-basis", previous.flexBasis);
+ restoreStyleProperty(element, "flex-grow", previous.flexGrow);
+ restoreStyleProperty(element, "flex-shrink", previous.flexShrink);
+ restoreStyleProperty(element, "box-sizing", previous.boxSizing);
+ restoreStyleProperty(element, "scale", previous.scale);
+ restoreStyleProperty(element, "transform-origin", previous.transformOrigin);
+ restoreStyleProperty(element, "display", previous.display);
+ restoreStyleProperty(element, STUDIO_WIDTH_PROP, previous.studioWidth);
+ restoreStyleProperty(element, STUDIO_HEIGHT_PROP, previous.studioHeight);
+ restoreAttribute(element, STUDIO_BOX_SIZE_ATTR, previous.marker);
+ restoreAttribute(element, STUDIO_ORIGINAL_WIDTH_ATTR, previous.originalWidth);
+ restoreAttribute(element, STUDIO_ORIGINAL_HEIGHT_ATTR, previous.originalHeight);
+ restoreAttribute(element, STUDIO_ORIGINAL_MIN_WIDTH_ATTR, previous.originalMinWidth);
+ restoreAttribute(element, STUDIO_ORIGINAL_MIN_HEIGHT_ATTR, previous.originalMinHeight);
+ restoreAttribute(element, STUDIO_ORIGINAL_MAX_WIDTH_ATTR, previous.originalMaxWidth);
+ restoreAttribute(element, STUDIO_ORIGINAL_MAX_HEIGHT_ATTR, previous.originalMaxHeight);
+ restoreAttribute(element, STUDIO_ORIGINAL_FLEX_BASIS_ATTR, previous.originalFlexBasis);
+ restoreAttribute(element, STUDIO_ORIGINAL_FLEX_GROW_ATTR, previous.originalFlexGrow);
+ restoreAttribute(element, STUDIO_ORIGINAL_FLEX_SHRINK_ATTR, previous.originalFlexShrink);
+ restoreAttribute(element, STUDIO_ORIGINAL_BOX_SIZING_ATTR, previous.originalBoxSizing);
+ restoreAttribute(element, STUDIO_ORIGINAL_SCALE_ATTR, previous.originalScale);
+ restoreAttribute(
+ element,
+ STUDIO_ORIGINAL_TRANSFORM_ORIGIN_ATTR,
+ previous.originalTransformOrigin,
+ );
+ restoreAttribute(element, STUDIO_ORIGINAL_DISPLAY_ATTR, previous.originalDisplay);
+}
+
+export function restoreStudioRotation(
+ element: HTMLElement,
+ previous: StudioRotationSnapshot,
+): void {
+ restoreStyleProperty(element, "rotate", previous.rotate);
+ restoreStyleProperty(element, "transform-origin", previous.transformOrigin);
+ restoreStyleProperty(element, STUDIO_ROTATION_PROP, previous.studioRotation);
+ restoreAttribute(element, STUDIO_ROTATION_ATTR, previous.marker);
+ restoreAttribute(element, STUDIO_ROTATION_DRAFT_ATTR, previous.draftMarker);
+ restoreAttribute(element, STUDIO_ORIGINAL_ROTATE_ATTR, previous.originalRotate);
+ restoreAttribute(element, STUDIO_ORIGINAL_INLINE_ROTATE_ATTR, previous.originalInlineRotate);
+ restoreAttribute(
+ element,
+ STUDIO_ORIGINAL_ROTATION_TRANSFORM_ORIGIN_ATTR,
+ previous.originalTransformOrigin,
+ );
+}
+
+export function restoreStudioPathOffset(
+ element: HTMLElement,
+ previous: StudioPathOffsetSnapshot,
+): void {
+ if (previous.translate) element.style.setProperty("translate", previous.translate);
+ else element.style.removeProperty("translate");
+
+ if (previous.x) element.style.setProperty(STUDIO_OFFSET_X_PROP, previous.x);
+ else element.style.removeProperty(STUDIO_OFFSET_X_PROP);
+
+ if (previous.y) element.style.setProperty(STUDIO_OFFSET_Y_PROP, previous.y);
+ else element.style.removeProperty(STUDIO_OFFSET_Y_PROP);
+
+ restoreAttribute(element, STUDIO_PATH_OFFSET_ATTR, previous.marker);
+ restoreAttribute(element, STUDIO_ORIGINAL_TRANSLATE_ATTR, previous.originalTranslate);
+ restoreAttribute(
+ element,
+ STUDIO_ORIGINAL_INLINE_TRANSLATE_ATTR,
+ previous.originalInlineTranslate,
+ );
+}
+
+function markWrapped(fn: (...args: unknown[]) => unknown): void {
+ try {
+ Object.defineProperty(fn, STUDIO_MANUAL_EDITS_WRAPPED_PROP, {
+ configurable: false,
+ enumerable: false,
+ value: true,
+ });
+ } catch {
+ try {
+ (fn as unknown as Record<string, unknown>)[STUDIO_MANUAL_EDITS_WRAPPED_PROP] = true;
+ } catch {
+ // Ignore non-extensible functions.
+ }
+ }
+}
+
+function isWrapped(fn: (...args: unknown[]) => unknown): boolean {
+ return Boolean((fn as unknown as Record<string, unknown>)[STUDIO_MANUAL_EDITS_WRAPPED_PROP]);
+}
+
+function wrapSeekReapplyFunction(
+ win: StudioManualEditSeekWindow,
+ owner: Record<string, unknown> | undefined,
+ key: string,
+): boolean {
+ const fn = owner?.[key];
+ if (!owner || typeof fn !== "function") return false;
+ const seek = fn as (...args: unknown[]) => unknown;
+ if (isWrapped(seek)) return true;
+
+ const wrappedSeek = function (this: unknown, ...args: unknown[]): unknown {
+ const result = seek.apply(this, args);
+ win.__hfStudioManualEditsApply?.();
+ return result;
+ };
+ markWrapped(wrappedSeek);
+ owner[key] = wrappedSeek;
+ return true;
+}
+
+function readOwnerNumber(owner: Record<string, unknown>, key: string): number | null {
+ const fn = owner[key];
+ if (typeof fn !== "function") return null;
+ try {
+ return finiteNumber(fn.call(owner));
+ } catch {
+ return null;
+ }
+}
+
+function hasRemainingTimelineTime(owner: Record<string, unknown>): boolean {
+ const duration = readOwnerNumber(owner, "duration") ?? readOwnerNumber(owner, "getDuration");
+ if (duration == null) return true;
+ if (duration <= 0) return false;
+
+ const time =
+ readOwnerNumber(owner, "time") ??
+ readOwnerNumber(owner, "totalTime") ??
+ readOwnerNumber(owner, "getTime");
+ if (time == null) return true;
+ return time < duration;
+}
+
+function isTimelinePlaying(owner: Record<string, unknown> | undefined): boolean {
+ if (!owner) return false;
+ const isPlaying = owner.isPlaying;
+ if (typeof isPlaying === "function") {
+ try {
+ return Boolean(isPlaying.call(owner));
+ } catch {
+ return false;
+ }
+ }
+
+ const paused = owner.paused;
+ if (typeof paused === "function") {
+ try {
+ if (paused.call(owner)) return false;
+ } catch {
+ return false;
+ }
+
+ const isActive = owner.isActive;
+ if (typeof isActive === "function") {
+ try {
+ if (isActive.call(owner)) return true;
+ } catch {
+ return false;
+ }
+ }
+
+ return hasRemainingTimelineTime(owner);
+ }
+
+ const isActive = owner.isActive;
+ if (typeof isActive === "function") {
+ try {
+ return Boolean(isActive.call(owner));
+ } catch {
+ return false;
+ }
+ }
+
+ return false;
+}
+
+function isStudioManualEditPlaybackActive(win: StudioManualEditSeekWindow): boolean {
+ if (isTimelinePlaying(win.__player)) return true;
+ if (isTimelinePlaying(win.__timeline)) return true;
+ return Object.values(win.__timelines ?? {}).some(isTimelinePlaying);
+}
+
+function startStudioManualEditPlaybackReapply(win: StudioManualEditSeekWindow): void {
+ win.__hfStudioManualEditsApply?.();
+ if (win[STUDIO_MANUAL_EDITS_PLAYBACK_FRAME_PROP] != null) return;
+
+ const tick = () => {
+ win.__hfStudioManualEditsApply?.();
+ if (!isStudioManualEditPlaybackActive(win)) {
+ win[STUDIO_MANUAL_EDITS_PLAYBACK_FRAME_PROP] = null;
+ return;
+ }
+ win[STUDIO_MANUAL_EDITS_PLAYBACK_FRAME_PROP] = win.requestAnimationFrame(tick);
+ };
+
+ win[STUDIO_MANUAL_EDITS_PLAYBACK_FRAME_PROP] = win.requestAnimationFrame(tick);
+}
+
+function wrapPlayReapplyFunction(
+ win: StudioManualEditSeekWindow,
+ owner: Record<string, unknown> | undefined,
+ key: string,
+): boolean {
+ const fn = owner?.[key];
+ if (!owner || typeof fn !== "function") return false;
+ const play = fn as (...args: unknown[]) => unknown;
+ if (isWrapped(play)) return true;
+
+ const wrappedPlay = function (this: unknown, ...args: unknown[]): unknown {
+ const result = play.apply(this, args);
+ startStudioManualEditPlaybackReapply(win);
+ return result;
+ };
+ markWrapped(wrappedPlay);
+ owner[key] = wrappedPlay;
+ return true;
+}
+
+function wrapApplyAfterFunction(
+ win: StudioManualEditSeekWindow,
+ owner: Record<string, unknown> | undefined,
+ key: string,
+): boolean {
+ const fn = owner?.[key];
+ if (!owner || typeof fn !== "function") return false;
+ const applyAfter = fn as (...args: unknown[]) => unknown;
+ if (isWrapped(applyAfter)) return true;
+
+ const wrappedApplyAfter = function (this: unknown, ...args: unknown[]): unknown {
+ const result = applyAfter.apply(this, args);
+ win.__hfStudioManualEditsApply?.();
+ return result;
+ };
+ markWrapped(wrappedApplyAfter);
+ owner[key] = wrappedApplyAfter;
+ return true;
+}
+
+export function installStudioManualEditSeekReapply(win: Window, apply: () => void): boolean {
+ const studioWin = win as StudioManualEditSeekWindow;
+ studioWin[STUDIO_MANUAL_EDITS_APPLY_PROP] = apply;
+
+ const wrappedHfSeek = wrapSeekReapplyFunction(studioWin, studioWin.__hf, "seek");
+ const wrappedPlayerSeek = wrapSeekReapplyFunction(studioWin, studioWin.__player, "seek");
+ const wrappedPlayerRenderSeek = wrapSeekReapplyFunction(
+ studioWin,
+ studioWin.__player,
+ "renderSeek",
+ );
+ const wrappedTimelineSeek = wrapSeekReapplyFunction(studioWin, studioWin.__timeline, "seek");
+ const wrappedPlayerPlay = wrapPlayReapplyFunction(studioWin, studioWin.__player, "play");
+ const wrappedTimelinePlay = wrapPlayReapplyFunction(studioWin, studioWin.__timeline, "play");
+ const wrappedPlayerPause = wrapApplyAfterFunction(studioWin, studioWin.__player, "pause");
+ const wrappedTimelinePause = wrapApplyAfterFunction(studioWin, studioWin.__timeline, "pause");
+ let wrappedNamedTimelineSeek = false;
+ let wrappedNamedTimelinePlay = false;
+ let wrappedNamedTimelinePause = false;
+ for (const timeline of Object.values(studioWin.__timelines ?? {})) {
+ wrappedNamedTimelineSeek =
+ wrapSeekReapplyFunction(studioWin, timeline, "seek") || wrappedNamedTimelineSeek;
+ wrappedNamedTimelinePlay =
+ wrapPlayReapplyFunction(studioWin, timeline, "play") || wrappedNamedTimelinePlay;
+ wrappedNamedTimelinePause =
+ wrapApplyAfterFunction(studioWin, timeline, "pause") || wrappedNamedTimelinePause;
+ }
+
+ if (isStudioManualEditPlaybackActive(studioWin)) {
+ startStudioManualEditPlaybackReapply(studioWin);
+ }
+
+ return (
+ wrappedHfSeek ||
+ wrappedPlayerSeek ||
+ wrappedPlayerRenderSeek ||
+ wrappedTimelineSeek ||
+ wrappedPlayerPlay ||
+ wrappedTimelinePlay ||
+ wrappedPlayerPause ||
+ wrappedTimelinePause ||
+ wrappedNamedTimelineSeek ||
+ wrappedNamedTimelinePlay ||
+ wrappedNamedTimelinePause
+ );
+}
+
+function getManualEditSourceFileForElement(
+ el: HTMLElement,
+ activeCompositionPath: string | null,
+): string {
+ let current: HTMLElement | null = el;
+ while (current) {
+ const sourceFile =
+ current.getAttribute("data-composition-file") ?? current.getAttribute("data-composition-src");
+ if (sourceFile) return sourceFile;
+ current = current.parentElement;
+ }
+ return activeCompositionPath ?? "index.html";
+}
+
+function elementMatchesManualEditSourceFile(
+ element: HTMLElement,
+ sourceFile: string,
+ activeCompositionPath: string | null,
+): boolean {
+ return getManualEditSourceFileForElement(element, activeCompositionPath) === sourceFile;
+}
+
+function queryManualEditSelectorCandidates(
+ doc: Document,
+ selector: string,
+ htmlElement: typeof HTMLElement,
+): HTMLElement[] {
+ const isCandidate = (element: Element): element is HTMLElement => element instanceof htmlElement;
+
+ const className = selector.match(/^\.([A-Za-z0-9_-]+)$/)?.[1];
+ if (className) {
+ return Array.from(doc.getElementsByTagName("*")).filter(
+ (element): element is HTMLElement =>
+ isCandidate(element) && element.classList.contains(className),
+ );
+ }
+
+ if (/^[A-Za-z][A-Za-z0-9-]*$/.test(selector)) {
+ return Array.from(doc.getElementsByTagName(selector)).filter(isCandidate);
+ }
+
+ return Array.from(doc.querySelectorAll(selector)).filter(isCandidate);
+}
+
+function resolveManualEditTarget(
+ doc: Document,
+ edit: StudioManualEdit,
+ activeCompositionPath: string | null,
+): HTMLElement | null {
+ const htmlElement = doc.defaultView?.HTMLElement;
+ if (!htmlElement) return null;
+
+ if (edit.target.id) {
+ const byId = doc.getElementById(edit.target.id);
+ if (
+ byId instanceof htmlElement &&
+ elementMatchesManualEditSourceFile(byId, edit.target.sourceFile, activeCompositionPath)
+ ) {
+ return byId;
+ }
+
+ const matchesById = [doc.documentElement, ...Array.from(doc.getElementsByTagName("*"))].filter(
+ (element): element is HTMLElement =>
+ element instanceof htmlElement &&
+ element.id === edit.target.id &&
+ elementMatchesManualEditSourceFile(element, edit.target.sourceFile, activeCompositionPath),
+ );
+ if (matchesById[0]) return matchesById[0];
+ }
+
+ if (!edit.target.selector) return null;
+ try {
+ const matches = queryManualEditSelectorCandidates(
+ doc,
+ edit.target.selector,
+ htmlElement,
+ ).filter((element) =>
+ elementMatchesManualEditSourceFile(element, edit.target.sourceFile, activeCompositionPath),
+ );
+ return matches[edit.target.selectorIndex ?? 0] ?? null;
+ } catch {
+ return null;
+ }
+}
+
+function collectStudioManualEditElements(doc: Document): HTMLElement[] {
+ const htmlElement = doc.defaultView?.HTMLElement;
+ if (!htmlElement) return [];
+
+ const elements = [doc.documentElement, ...Array.from(doc.getElementsByTagName("*"))].filter(
+ (element): element is HTMLElement => element instanceof htmlElement,
+ );
+
+ return elements.filter(
+ (element) =>
+ element.hasAttribute(STUDIO_PATH_OFFSET_ATTR) ||
+ element.hasAttribute(STUDIO_MANUAL_EDIT_GESTURE_ATTR) ||
+ element.hasAttribute(STUDIO_BOX_SIZE_ATTR) ||
+ element.hasAttribute(STUDIO_ROTATION_ATTR) ||
+ element.hasAttribute(STUDIO_ROTATION_DRAFT_ATTR) ||
+ element.hasAttribute(STUDIO_ORIGINAL_TRANSLATE_ATTR) ||
+ element.hasAttribute(STUDIO_ORIGINAL_INLINE_TRANSLATE_ATTR) ||
+ element.hasAttribute(STUDIO_ORIGINAL_MIN_WIDTH_ATTR) ||
+ element.hasAttribute(STUDIO_ORIGINAL_FLEX_BASIS_ATTR) ||
+ element.hasAttribute(STUDIO_ORIGINAL_SCALE_ATTR) ||
+ element.hasAttribute(STUDIO_ORIGINAL_ROTATE_ATTR) ||
+ element.hasAttribute(STUDIO_ORIGINAL_INLINE_ROTATE_ATTR) ||
+ Boolean(element.style.getPropertyValue(STUDIO_OFFSET_X_PROP)) ||
+ Boolean(element.style.getPropertyValue(STUDIO_OFFSET_Y_PROP)) ||
+ Boolean(element.style.getPropertyValue(STUDIO_WIDTH_PROP)) ||
+ Boolean(element.style.getPropertyValue(STUDIO_HEIGHT_PROP)) ||
+ Boolean(element.style.getPropertyValue(STUDIO_ROTATION_PROP)),
+ );
+}
+
+export function applyStudioManualEditManifest(
+ doc: Document,
+ manifest: StudioManualEditManifest,
+ activeCompositionPath: string | null,
+): number {
+ const resolvedEdits: Array<{ edit: StudioManualEdit; element: HTMLElement }> = [];
+ const pathOffsetTargets = new Set<HTMLElement>();
+ const boxSizeTargets = new Set<HTMLElement>();
+ const rotationTargets = new Set<HTMLElement>();
+
+ for (const edit of manifest.edits) {
+ const element = resolveManualEditTarget(doc, edit, activeCompositionPath);
+ if (!element) continue;
+ if (isStudioManualEditGestureActive(element)) {
+ continue;
+ }
+ resolvedEdits.push({ edit, element });
+ if (edit.kind === "path-offset") pathOffsetTargets.add(element);
+ if (edit.kind === "box-size") boxSizeTargets.add(element);
+ if (edit.kind === "rotation") rotationTargets.add(element);
+ }
+
+ for (const element of collectStudioManualEditElements(doc)) {
+ if (isStudioManualEditGestureActive(element)) continue;
+ if (!pathOffsetTargets.has(element)) {
+ clearStudioPathOffset(element);
+ }
+ if (!boxSizeTargets.has(element)) {
+ clearStudioBoxSize(element);
+ }
+ if (!rotationTargets.has(element)) {
+ clearStudioRotation(element);
+ }
+ }
+
+ let applied = 0;
+ for (const { edit, element } of resolvedEdits) {
+ if (edit.kind === "path-offset") {
+ applyStudioPathOffset(element, { x: edit.x, y: edit.y });
+ } else if (edit.kind === "box-size") {
+ applyStudioBoxSize(element, { width: edit.width, height: edit.height });
+ } else {
+ applyStudioRotation(element, { angle: edit.angle });
+ }
+ applied += 1;
+ }
+ return applied;
+}
diff --git a/packages/studio/src/components/editor/manualOffsetDrag.test.ts b/packages/studio/src/components/editor/manualOffsetDrag.test.ts
new file mode 100644
index 0000000000..0289732b3b
--- /dev/null
+++ b/packages/studio/src/components/editor/manualOffsetDrag.test.ts
@@ -0,0 +1,140 @@
+import { Window } from "happy-dom";
+import { describe, expect, it } from "vitest";
+import {
+ applyManualOffsetDragMatrix,
+ invertManualOffsetDragMatrix,
+ measureManualOffsetDragScreenToOffsetMatrix,
+ resolveManualOffsetForPointerDelta,
+ type ManualOffsetDragMatrix,
+} from "./manualOffsetDrag";
+import { STUDIO_OFFSET_X_PROP, STUDIO_OFFSET_Y_PROP } from "./manualEdits";
+
+function expectMatrixClose(actual: ManualOffsetDragMatrix, expected: ManualOffsetDragMatrix): void {
+ expect(actual.a).toBeCloseTo(expected.a, 6);
+ expect(actual.b).toBeCloseTo(expected.b, 6);
+ expect(actual.c).toBeCloseTo(expected.c, 6);
+ expect(actual.d).toBeCloseTo(expected.d, 6);
+}
+
+describe("manual offset drag matrix helpers", () => {
+ it("inverts identity movement", () => {
+ const inverse = invertManualOffsetDragMatrix({ a: 1, b: 0, c: 0, d: 1 });
+ if (!inverse) throw new Error("identity matrix should be invertible");
+
+ expectMatrixClose(inverse, { a: 1, b: 0, c: 0, d: 1 });
+ });
+
+ it("maps screen movement through a rotated coordinate system", () => {
+ const screenToOffset = invertManualOffsetDragMatrix({ a: 0, b: 1, c: -1, d: 0 });
+ if (!screenToOffset) throw new Error("rotation matrix should be invertible");
+
+ const offsetDelta = applyManualOffsetDragMatrix(screenToOffset, { x: 0, y: 10 });
+
+ expect(offsetDelta.x).toBeCloseTo(10, 6);
+ expect(offsetDelta.y).toBeCloseTo(0, 6);
+ });
+
+ it("rejects singular movement matrices", () => {
+ expect(invertManualOffsetDragMatrix({ a: 1, b: 1, c: 2, d: 2 })).toBeNull();
+ });
+
+ it("resolves final offsets from the measured inverse matrix", () => {
+ const offsetToScreen = { a: 2, b: 3, c: -1, d: 4 };
+ const screenToOffset = invertManualOffsetDragMatrix(offsetToScreen);
+ if (!screenToOffset) throw new Error("fixture matrix should be invertible");
+
+ const nextOffset = resolveManualOffsetForPointerDelta({
+ initialOffset: { x: 5, y: -2 },
+ screenToOffset,
+ dx: 7,
+ dy: 11,
+ });
+ const screenDelta = applyManualOffsetDragMatrix(offsetToScreen, {
+ x: nextOffset.x - 5,
+ y: nextOffset.y + 2,
+ });
+
+ expect(screenDelta.x).toBeCloseTo(7, 6);
+ expect(screenDelta.y).toBeCloseTo(11, 6);
+ });
+});
+
+describe("measureManualOffsetDragScreenToOffsetMatrix", () => {
+ it("measures the element center response and restores probe styles", () => {
+ const window = new Window();
+ const element = window.document.createElement("div");
+ window.document.body.append(element);
+
+ element.getBoundingClientRect = () => {
+ const offsetX = Number.parseFloat(element.style.getPropertyValue(STUDIO_OFFSET_X_PROP)) || 0;
+ const offsetY = Number.parseFloat(element.style.getPropertyValue(STUDIO_OFFSET_Y_PROP)) || 0;
+ return new window.DOMRect(10 + 2 * offsetX - offsetY, 20 + 3 * offsetX + 4 * offsetY, 12, 8);
+ };
+
+ const measured = measureManualOffsetDragScreenToOffsetMatrix(element, { x: 0, y: 0 });
+ if (!measured.ok) throw new Error(measured.reason);
+
+ const expected = invertManualOffsetDragMatrix({ a: 2, b: 3, c: -1, d: 4 });
+ if (!expected) throw new Error("fixture matrix should be invertible");
+
+ expectMatrixClose(measured.matrix, expected);
+ expect(element.style.getPropertyValue(STUDIO_OFFSET_X_PROP)).toBe("");
+ expect(element.style.getPropertyValue(STUDIO_OFFSET_Y_PROP)).toBe("");
+ expect(element.style.getPropertyValue("translate")).toBe("");
+ });
+
+ it("measures movement in parent viewport pixels when the element is inside a scaled iframe", () => {
+ const window = new Window();
+ const iframe = window.document.createElement("iframe");
+ window.document.body.append(iframe);
+ const iframeWindow = iframe.contentWindow;
+ const iframeDocument = iframe.contentDocument;
+ if (!iframeWindow || !iframeDocument) throw new Error("iframe fixture failed to initialize");
+
+ Object.defineProperty(iframeWindow, "frameElement", {
+ configurable: true,
+ value: iframe,
+ });
+ Object.defineProperty(iframeWindow, "innerWidth", {
+ configurable: true,
+ value: 200,
+ });
+ Object.defineProperty(iframeWindow, "innerHeight", {
+ configurable: true,
+ value: 100,
+ });
+ iframe.getBoundingClientRect = () => new window.DOMRect(50, 40, 100, 50);
+
+ const element = iframeDocument.createElement("div");
+ iframeDocument.body.append(element);
+ element.getBoundingClientRect = () => {
+ const offsetX = Number.parseFloat(element.style.getPropertyValue(STUDIO_OFFSET_X_PROP)) || 0;
+ const offsetY = Number.parseFloat(element.style.getPropertyValue(STUDIO_OFFSET_Y_PROP)) || 0;
+ return new iframeWindow.DOMRect(20 + offsetX, 30 + offsetY, 40, 20);
+ };
+
+ const measured = measureManualOffsetDragScreenToOffsetMatrix(element, { x: 0, y: 0 });
+ if (!measured.ok) throw new Error(measured.reason);
+
+ expectMatrixClose(measured.matrix, { a: 2, b: -0, c: -0, d: 2 });
+
+ const nextOffset = resolveManualOffsetForPointerDelta({
+ initialOffset: { x: 0, y: 0 },
+ screenToOffset: measured.matrix,
+ dx: 50,
+ dy: 25,
+ });
+ expect(nextOffset).toEqual({ x: 100, y: 50 });
+ });
+
+ it("rejects elements whose movement response cannot be measured", () => {
+ const window = new Window();
+ const element = window.document.createElement("div");
+ window.document.body.append(element);
+ element.getBoundingClientRect = () => new window.DOMRect(10, 20, 12, 8);
+
+ const measured = measureManualOffsetDragScreenToOffsetMatrix(element, { x: 0, y: 0 });
+
+ expect(measured.ok).toBe(false);
+ });
+});
diff --git a/packages/studio/src/components/editor/manualOffsetDrag.ts b/packages/studio/src/components/editor/manualOffsetDrag.ts
new file mode 100644
index 0000000000..596209cf6a
--- /dev/null
+++ b/packages/studio/src/components/editor/manualOffsetDrag.ts
@@ -0,0 +1,307 @@
+import type { DomEditSelection } from "./domEditing";
+import {
+ applyStudioPathOffset,
+ applyStudioPathOffsetDraft,
+ beginStudioManualEditGesture,
+ captureStudioPathOffset,
+ endStudioManualEditGesture,
+ readStudioPathOffset,
+ restoreStudioPathOffset,
+ type StudioPathOffsetSnapshot,
+} from "./manualEdits";
+
+const DEFAULT_OFFSET_PROBE_PX = 100;
+const MIN_PROBE_VECTOR_LENGTH_PX = 0.01;
+const MIN_MATRIX_DETERMINANT = 0.000001;
+
+export interface ManualOffsetDragMatrix {
+ a: number;
+ b: number;
+ c: number;
+ d: number;
+}
+
+export interface ManualOffsetDragRect {
+ left: number;
+ top: number;
+ width: number;
+ height: number;
+ editScaleX: number;
+ editScaleY: number;
+}
+
+export interface ManualOffsetDragMember {
+ key: string;
+ selection: DomEditSelection;
+ element: HTMLElement;
+ initialOffset: { x: number; y: number };
+ initialPathOffset: StudioPathOffsetSnapshot;
+ gestureToken: string;
+ screenToOffset: ManualOffsetDragMatrix;
+ originRect: ManualOffsetDragRect;
+}
+
+export type ManualOffsetDragMemberResult =
+ | { ok: true; member: ManualOffsetDragMember }
+ | { ok: false; reason: string; selection: DomEditSelection };
+
+type Point = { x: number; y: number };
+
+function finitePoint(point: Point): boolean {
+ return Number.isFinite(point.x) && Number.isFinite(point.y);
+}
+
+function vectorLength(point: Point): number {
+ return Math.hypot(point.x, point.y);
+}
+
+function finiteRect(rect: DOMRect): boolean {
+ return (
+ Number.isFinite(rect.left) &&
+ Number.isFinite(rect.top) &&
+ Number.isFinite(rect.width) &&
+ Number.isFinite(rect.height)
+ );
+}
+
+function readViewportSize(win: Window): { width: number; height: number } {
+ const docEl = win.document.documentElement;
+ const width = win.innerWidth || docEl.clientWidth || 1;
+ const height = win.innerHeight || docEl.clientHeight || 1;
+ return {
+ width: width > 0 ? width : 1,
+ height: height > 0 ? height : 1,
+ };
+}
+
+function getFrameElement(win: Window): HTMLElement | null {
+ try {
+ const frameElement = win.frameElement;
+ if (!frameElement) return null;
+ const ownerWin = frameElement.ownerDocument.defaultView;
+ const htmlElement = ownerWin?.HTMLElement;
+ return htmlElement && frameElement instanceof htmlElement ? frameElement : null;
+ } catch {
+ return null;
+ }
+}
+
+function getRectCenter(element: HTMLElement): Point | null {
+ const rect = element.getBoundingClientRect();
+ if (!finiteRect(rect) || (rect.width <= 0 && rect.height <= 0)) {
+ return null;
+ }
+
+ let point = {
+ x: rect.left + rect.width / 2,
+ y: rect.top + rect.height / 2,
+ };
+
+ let win: Window | null = element.ownerDocument.defaultView;
+ while (win) {
+ const frameElement = getFrameElement(win);
+ if (!frameElement) break;
+
+ const frameRect = frameElement.getBoundingClientRect();
+ if (!finiteRect(frameRect) || frameRect.width <= 0 || frameRect.height <= 0) return null;
+
+ const viewport = readViewportSize(win);
+ point = {
+ x: frameRect.left + point.x * (frameRect.width / viewport.width),
+ y: frameRect.top + point.y * (frameRect.height / viewport.height),
+ };
+ win = frameElement.ownerDocument.defaultView;
+ }
+
+ return point;
+}
+
+export function invertManualOffsetDragMatrix(
+ matrix: ManualOffsetDragMatrix,
+): ManualOffsetDragMatrix | null {
+ const determinant = matrix.a * matrix.d - matrix.b * matrix.c;
+ if (!Number.isFinite(determinant) || Math.abs(determinant) < MIN_MATRIX_DETERMINANT) {
+ return null;
+ }
+
+ return {
+ a: matrix.d / determinant,
+ b: -matrix.b / determinant,
+ c: -matrix.c / determinant,
+ d: matrix.a / determinant,
+ };
+}
+
+export function applyManualOffsetDragMatrix(matrix: ManualOffsetDragMatrix, point: Point): Point {
+ return {
+ x: matrix.a * point.x + matrix.c * point.y,
+ y: matrix.b * point.x + matrix.d * point.y,
+ };
+}
+
+export function measureManualOffsetDragScreenToOffsetMatrix(
+ element: HTMLElement,
+ initialOffset: { x: number; y: number },
+ options: { probeSize?: number } = {},
+): { ok: true; matrix: ManualOffsetDragMatrix } | { ok: false; reason: string } {
+ const probeSize = options.probeSize ?? DEFAULT_OFFSET_PROBE_PX;
+ if (!Number.isFinite(probeSize) || probeSize <= 0) {
+ return { ok: false, reason: "Invalid movement probe size." };
+ }
+
+ const snapshot = captureStudioPathOffset(element);
+ try {
+ applyStudioPathOffsetDraft(element, initialOffset);
+ const origin = getRectCenter(element);
+ if (!origin) {
+ return { ok: false, reason: "Element has no measurable box." };
+ }
+
+ applyStudioPathOffsetDraft(element, {
+ x: initialOffset.x + probeSize,
+ y: initialOffset.y,
+ });
+ const probeX = getRectCenter(element);
+ if (!probeX) {
+ return { ok: false, reason: "Element X movement could not be measured." };
+ }
+
+ applyStudioPathOffsetDraft(element, {
+ x: initialOffset.x,
+ y: initialOffset.y + probeSize,
+ });
+ const probeY = getRectCenter(element);
+ if (!probeY) {
+ return { ok: false, reason: "Element Y movement could not be measured." };
+ }
+
+ const xColumn = {
+ x: (probeX.x - origin.x) / probeSize,
+ y: (probeX.y - origin.y) / probeSize,
+ };
+ const yColumn = {
+ x: (probeY.x - origin.x) / probeSize,
+ y: (probeY.y - origin.y) / probeSize,
+ };
+ if (
+ !finitePoint(xColumn) ||
+ !finitePoint(yColumn) ||
+ vectorLength(xColumn) < MIN_PROBE_VECTOR_LENGTH_PX ||
+ vectorLength(yColumn) < MIN_PROBE_VECTOR_LENGTH_PX
+ ) {
+ return { ok: false, reason: "Element movement response is too small to measure." };
+ }
+
+ const offsetToScreen = {
+ a: xColumn.x,
+ b: xColumn.y,
+ c: yColumn.x,
+ d: yColumn.y,
+ };
+ const screenToOffset = invertManualOffsetDragMatrix(offsetToScreen);
+ if (!screenToOffset) {
+ return { ok: false, reason: "Element movement response is not invertible." };
+ }
+
+ return { ok: true, matrix: screenToOffset };
+ } finally {
+ restoreStudioPathOffset(element, snapshot);
+ }
+}
+
+export function resolveManualOffsetForPointerDelta(input: {
+ initialOffset: { x: number; y: number };
+ screenToOffset: ManualOffsetDragMatrix;
+ dx: number;
+ dy: number;
+}): { x: number; y: number } {
+ const offsetDelta = applyManualOffsetDragMatrix(input.screenToOffset, {
+ x: input.dx,
+ y: input.dy,
+ });
+ return {
+ x: input.initialOffset.x + offsetDelta.x,
+ y: input.initialOffset.y + offsetDelta.y,
+ };
+}
+
+export function createManualOffsetDragMember(input: {
+ key: string;
+ selection: DomEditSelection;
+ element: HTMLElement;
+ rect: ManualOffsetDragRect;
+}): ManualOffsetDragMemberResult {
+ const initialOffset = readStudioPathOffset(input.element);
+ const initialPathOffset = captureStudioPathOffset(input.element);
+ const gestureToken = beginStudioManualEditGesture(input.element);
+ const measured = measureManualOffsetDragScreenToOffsetMatrix(input.element, initialOffset);
+ if (!measured.ok) {
+ restoreStudioPathOffset(input.element, initialPathOffset);
+ endStudioManualEditGesture(input.element, gestureToken);
+ return { ok: false, reason: measured.reason, selection: input.selection };
+ }
+
+ return {
+ ok: true,
+ member: {
+ key: input.key,
+ selection: input.selection,
+ element: input.element,
+ initialOffset,
+ initialPathOffset,
+ gestureToken,
+ screenToOffset: measured.matrix,
+ originRect: input.rect,
+ },
+ };
+}
+
+export function resolveManualOffsetDragMemberOffset(
+ member: ManualOffsetDragMember,
+ dx: number,
+ dy: number,
+): { x: number; y: number } {
+ return resolveManualOffsetForPointerDelta({
+ initialOffset: member.initialOffset,
+ screenToOffset: member.screenToOffset,
+ dx,
+ dy,
+ });
+}
+
+export function applyManualOffsetDragDraft(
+ member: ManualOffsetDragMember,
+ dx: number,
+ dy: number,
+): { x: number; y: number } {
+ const offset = resolveManualOffsetDragMemberOffset(member, dx, dy);
+ applyStudioPathOffsetDraft(member.element, offset);
+ return offset;
+}
+
+export function applyManualOffsetDragCommit(
+ member: ManualOffsetDragMember,
+ dx: number,
+ dy: number,
+): { x: number; y: number } {
+ const offset = resolveManualOffsetDragMemberOffset(member, dx, dy);
+ applyStudioPathOffset(member.element, offset);
+ return offset;
+}
+
+export function restoreManualOffsetDragMember(member: ManualOffsetDragMember): void {
+ restoreStudioPathOffset(member.element, member.initialPathOffset);
+ endStudioManualEditGesture(member.element, member.gestureToken);
+}
+
+export function restoreManualOffsetDragMembers(members: ManualOffsetDragMember[]): void {
+ for (const member of members) {
+ restoreManualOffsetDragMember(member);
+ }
+}
+
+export function endManualOffsetDragMembers(members: ManualOffsetDragMember[]): void {
+ for (const member of members) {
+ endStudioManualEditGesture(member.element, member.gestureToken);
+ }
+}
diff --git a/packages/studio/src/components/nle/NLELayout.tsx b/packages/studio/src/components/nle/NLELayout.tsx
index 79757b081e..5c56b800e5 100644
--- a/packages/studio/src/components/nle/NLELayout.tsx
+++ b/packages/studio/src/components/nle/NLELayout.tsx
@@ -89,7 +89,6 @@ export const NLELayout = memo(function NLELayout({
togglePlay,
seek,
onIframeLoad: baseOnIframeLoad,
- refreshPlayer,
saveSeekPosition,
} = useTimelinePlayer();
@@ -103,13 +102,15 @@ export const NLELayout = memo(function NLELayout({
usePlayerStore.getState().reset();
}
- // Refresh the existing iframe in place when source files change.
+ // Save seek position before the Player component creates a new player
+ // on refreshKey change. The Player handles the actual reload via the
+ // dual-player crossfade; we just need to persist the current time.
const prevRefreshKeyRef = useRef(refreshKey);
useEffect(() => {
if (refreshKey === prevRefreshKeyRef.current) return;
prevRefreshKeyRef.current = refreshKey;
- refreshPlayer();
- }, [refreshKey, refreshPlayer]);
+ saveSeekPosition();
+ }, [refreshKey, saveSeekPosition]);
// Wrap onIframeLoad to also notify parent of iframe ref
const onIframeLoad = useCallback(() => {
@@ -209,6 +210,10 @@ export const NLELayout = memo(function NLELayout({
const currentLevel = compositionStack[compositionStack.length - 1];
const directUrl = compositionStack.length > 1 ? currentLevel.previewUrl : undefined;
+ useEffect(() => {
+ onIframeRef?.(iframeRef.current);
+ }, [compositionStack.length, onIframeRef, refreshKey, iframeRef]);
+
// Save master seek position before drilling down so we can restore it on back-navigation.
// saveSeekPosition() sets pendingSeekRef in useTimelinePlayer which onIframeLoad reads.
const masterSeekRef = useRef(0);
diff --git a/packages/studio/src/components/nle/NLEPreview.tsx b/packages/studio/src/components/nle/NLEPreview.tsx
index dab649edcc..ebe3dc2828 100644
--- a/packages/studio/src/components/nle/NLEPreview.tsx
+++ b/packages/studio/src/components/nle/NLEPreview.tsx
@@ -1,4 +1,4 @@
-import { memo, type Ref } from "react";
+import { memo, useRef, useState, type Ref } from "react";
import { Player } from "../../player";
interface NLEPreviewProps {
@@ -21,6 +21,17 @@ export function getPreviewPlayerKey({
return directUrl ?? projectId;
}
+/**
+ * Manages the composition preview with crossfade on reload.
+ *
+ * When refreshKey changes, a new Player is mounted alongside the old one.
+ * The old Player stays visible (opacity 1) until the new one fires onLoad,
+ * at which point the old is removed. This avoids the flash that a simple
+ * key-swap remount would cause.
+ *
+ * Uses the render-time state adjustment pattern (React-sanctioned) to detect
+ * refreshKey changes — no useEffect needed.
+ */
export const NLEPreview = memo(function NLEPreview({
projectId,
iframeRef,
@@ -29,22 +40,56 @@ export const NLEPreview = memo(function NLEPreview({
directUrl,
refreshKey,
}: NLEPreviewProps) {
- const playerKey = getPreviewPlayerKey({ projectId, directUrl, refreshKey });
+ const baseKey = getPreviewPlayerKey({ projectId, directUrl, refreshKey });
+ const prevRefreshKeyRef = useRef(refreshKey);
+ const [retiringKey, setRetiringKey] = useState<string | null>(null);
+ const retiringTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ // Detect refreshKey change during render (React-sanctioned derived state pattern).
+ // When the key changes, the current active player becomes the retiring player
+ // and a new active player is mounted alongside it.
+ if (refreshKey !== prevRefreshKeyRef.current) {
+ const oldKey = `${baseKey}:${prevRefreshKeyRef.current ?? 0}`;
+ prevRefreshKeyRef.current = refreshKey;
+ setRetiringKey(oldKey);
+ }
+
+ const activeKey = `${baseKey}:${refreshKey ?? 0}`;
+
+ const handleNewPlayerLoad = () => {
+ onIframeLoad();
+ if (retiringTimerRef.current) clearTimeout(retiringTimerRef.current);
+ retiringTimerRef.current = setTimeout(() => {
+ setRetiringKey(null);
+ retiringTimerRef.current = null;
+ }, 160);
+ };
return (
<div className="flex flex-col h-full min-h-0">
<div
- className="flex-1 flex items-center justify-center p-2 overflow-hidden min-h-0 outline-none focus:ring-1 focus:ring-studio-accent/40"
+ className="relative flex-1 flex items-center justify-center p-2 overflow-hidden min-h-0 outline-none focus:ring-1 focus:ring-studio-accent/40"
tabIndex={0}
aria-label="Composition preview"
>
+ {retiringKey && (
+ <Player
+ key={retiringKey}
+ projectId={directUrl ? undefined : projectId}
+ directUrl={directUrl}
+ onLoad={() => {}}
+ portrait={portrait}
+ style={{ position: "absolute", inset: 0, zIndex: 0, opacity: 1 }}
+ />
+ )}
<Player
- key={playerKey}
+ key={activeKey}
ref={iframeRef}
projectId={directUrl ? undefined : projectId}
directUrl={directUrl}
- onLoad={onIframeLoad}
+ onLoad={retiringKey ? handleNewPlayerLoad : onIframeLoad}
portrait={portrait}
+ style={retiringKey ? { position: "absolute", inset: 0, zIndex: 1 } : undefined}
/>
</div>
</div>
diff --git a/packages/studio/src/components/renders/RenderQueue.tsx b/packages/studio/src/components/renders/RenderQueue.tsx
index 8a6e69909b..32f705ba28 100644
--- a/packages/studio/src/components/renders/RenderQueue.tsx
+++ b/packages/studio/src/components/renders/RenderQueue.tsx
@@ -2,12 +2,17 @@ import { memo, useState, useRef, useEffect } from "react";
import { RenderQueueItem } from "./RenderQueueItem";
import type { RenderJob } from "./useRenderQueue";
+type StartRenderHandler = (
+ format: "mp4" | "webm" | "mov",
+ quality: "draft" | "standard" | "high",
+) => void | Promise<void>;
+
interface RenderQueueProps {
jobs: RenderJob[];
projectId: string;
onDelete: (jobId: string) => void;
onClearCompleted: () => void;
- onStartRender: (format: "mp4" | "webm" | "mov", quality: "draft" | "standard" | "high") => void;
+ onStartRender: StartRenderHandler;
isRendering: boolean;
}
@@ -91,7 +96,7 @@ function FormatExportButton({
onStartRender,
isRendering,
}: {
- onStartRender: (format: "mp4" | "webm" | "mov", quality: "draft" | "standard" | "high") => void;
+ onStartRender: StartRenderHandler;
isRendering: boolean;
}) {
const [format, setFormat] = useState<"mp4" | "webm" | "mov">("mp4");
@@ -129,7 +134,9 @@ function FormatExportButton({
<option value="webm">WebM</option>
</select>
<button
- onClick={() => onStartRender(format, quality)}
+ onClick={() => {
+ void onStartRender(format, quality);
+ }}
disabled={isRendering}
className="flex items-center gap-1 px-2 py-0.5 text-[10px] font-semibold rounded-r bg-studio-accent text-[#09090B] hover:brightness-110 transition-colors disabled:opacity-50"
>
diff --git a/packages/studio/src/components/sidebar/AssetsTab.tsx b/packages/studio/src/components/sidebar/AssetsTab.tsx
index eccbf9d880..4272c543dc 100644
--- a/packages/studio/src/components/sidebar/AssetsTab.tsx
+++ b/packages/studio/src/components/sidebar/AssetsTab.tsx
@@ -2,6 +2,7 @@ import { memo, useState, useCallback, useRef } from "react";
import { VideoFrameThumbnail } from "../ui/VideoFrameThumbnail";
import { MEDIA_EXT, IMAGE_EXT, VIDEO_EXT, AUDIO_EXT } from "../../utils/mediaTypes";
import { TIMELINE_ASSET_MIME } from "../../utils/timelineAssetDrop";
+import { copyTextToClipboard } from "../../utils/clipboard";
interface AssetsTabProps {
projectId: string;
@@ -298,12 +299,10 @@ export const AssetsTab = memo(function AssetsTab({
);
const handleCopyPath = useCallback(async (path: string) => {
- try {
- await navigator.clipboard.writeText(path);
+ const copied = await copyTextToClipboard(path);
+ if (copied) {
setCopiedPath(path);
setTimeout(() => setCopiedPath(null), 1500);
- } catch {
- // ignore
}
}, []);
diff --git a/packages/studio/src/components/sidebar/CompositionsTab.test.ts b/packages/studio/src/components/sidebar/CompositionsTab.test.ts
index 25549f1ea4..22de6c129c 100644
--- a/packages/studio/src/components/sidebar/CompositionsTab.test.ts
+++ b/packages/studio/src/components/sidebar/CompositionsTab.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import { resolveCompositionPreviewScale } from "./CompositionsTab";
+import { resolveCompositionPreviewScale, resolveThumbnailSeekTime } from "./CompositionsTab";
describe("resolveCompositionPreviewScale", () => {
it("scales a 16:9 stage to fit the composition card", () => {
@@ -35,3 +35,18 @@ describe("resolveCompositionPreviewScale", () => {
).toBeCloseTo(80 / 1920);
});
});
+
+describe("resolveThumbnailSeekTime", () => {
+ it("uses the default 3s frame for compositions longer than 3s", () => {
+ expect(resolveThumbnailSeekTime(6)).toBe(3);
+ });
+
+ it("uses the midpoint for compositions shorter than 3s", () => {
+ expect(resolveThumbnailSeekTime(2)).toBe(1);
+ });
+
+ it("falls back to the default 3s frame when duration is unknown", () => {
+ expect(resolveThumbnailSeekTime(null)).toBe(3);
+ expect(resolveThumbnailSeekTime(Number.NaN)).toBe(3);
+ });
+});
diff --git a/packages/studio/src/components/sidebar/CompositionsTab.tsx b/packages/studio/src/components/sidebar/CompositionsTab.tsx
index 12dc558da3..c5a5e5e27e 100644
--- a/packages/studio/src/components/sidebar/CompositionsTab.tsx
+++ b/packages/studio/src/components/sidebar/CompositionsTab.tsx
@@ -1,4 +1,4 @@
-import { memo, useRef, useState } from "react";
+import { memo, useCallback, useEffect, useRef, useState } from "react";
interface CompositionsTabProps {
projectId: string;
@@ -8,6 +8,17 @@ interface CompositionsTabProps {
}
const DEFAULT_PREVIEW_STAGE = { width: 1920, height: 1080 };
+const THUMBNAIL_SEEK_TIME_SECONDS = 3;
+const THUMBNAIL_PLAYBACK_SYNC_ATTEMPTS = 10;
+
+type PreviewWindow = Window & {
+ __player?: {
+ play?: () => void;
+ pause?: () => void;
+ seek?: (time: number) => void;
+ getDuration?: () => number;
+ };
+};
export function resolveCompositionPreviewScale(input: {
cardWidth: number;
@@ -28,6 +39,54 @@ export function resolveCompositionPreviewScale(input: {
return Math.min(scaleX, scaleY);
}
+export function resolveThumbnailSeekTime(durationSeconds: number | null | undefined): number {
+ if (
+ Number.isFinite(durationSeconds) &&
+ durationSeconds != null &&
+ durationSeconds > 0 &&
+ durationSeconds < THUMBNAIL_SEEK_TIME_SECONDS
+ ) {
+ return durationSeconds / 2;
+ }
+
+ return THUMBNAIL_SEEK_TIME_SECONDS;
+}
+
+function parsePositiveNumber(value: string | null): number | null {
+ if (value == null) return null;
+ const parsed = Number.parseFloat(value);
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
+}
+
+function resolveIframeDuration(iframe: HTMLIFrameElement | null): number | null {
+ const win = iframe?.contentWindow as PreviewWindow | null;
+ const playerDuration = win?.__player?.getDuration?.();
+ if (Number.isFinite(playerDuration) && playerDuration != null && playerDuration > 0) {
+ return playerDuration;
+ }
+
+ const doc = iframe?.contentDocument;
+ const root = doc?.querySelector("[data-composition-id]") ?? doc?.documentElement ?? null;
+ return (
+ parsePositiveNumber(root?.getAttribute("data-composition-duration") ?? null) ??
+ parsePositiveNumber(root?.getAttribute("data-duration") ?? null)
+ );
+}
+
+function syncIframePlayback(iframe: HTMLIFrameElement | null, shouldPlay: boolean): boolean {
+ const player = (iframe?.contentWindow as PreviewWindow | null)?.__player;
+ if (!player) return false;
+
+ if (shouldPlay) {
+ player.play?.();
+ return true;
+ }
+
+ player.pause?.();
+ player.seek?.(resolveThumbnailSeekTime(resolveIframeDuration(iframe)));
+ return true;
+}
+
function CompCard({
projectId,
comp,
@@ -41,7 +100,25 @@ function CompCard({
}) {
const [hovered, setHovered] = useState(false);
const [stageSize, setStageSize] = useState(DEFAULT_PREVIEW_STAGE);
+ const iframeRef = useRef<HTMLIFrameElement | null>(null);
const hoverTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const syncTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ const requestIframePlaybackSync = useCallback((shouldPlay: boolean) => {
+ if (syncTimer.current) {
+ clearTimeout(syncTimer.current);
+ syncTimer.current = null;
+ }
+
+ const sync = (remainingAttempts: number) => {
+ if (syncIframePlayback(iframeRef.current, shouldPlay) || remainingAttempts <= 0) return;
+
+ syncTimer.current = setTimeout(() => sync(remainingAttempts - 1), 100);
+ };
+
+ sync(THUMBNAIL_PLAYBACK_SYNC_ATTEMPTS);
+ }, []);
+
const handleEnter = () => {
hoverTimer.current = setTimeout(() => setHovered(true), 300);
};
@@ -53,7 +130,6 @@ function CompCard({
setHovered(false);
};
const name = comp.replace(/^compositions\//, "").replace(/\.html$/, "");
- const thumbnailUrl = `/api/projects/${projectId}/thumbnail/${comp}?t=2`;
const previewUrl = `/api/projects/${projectId}/preview/comp/${comp}`;
const previewScale = resolveCompositionPreviewScale({
cardWidth: 80,
@@ -62,6 +138,17 @@ function CompCard({
stageHeight: stageSize.height,
});
+ useEffect(() => {
+ requestIframePlaybackSync(hovered);
+ }, [hovered, requestIframePlaybackSync]);
+
+ useEffect(() => {
+ return () => {
+ if (hoverTimer.current) clearTimeout(hoverTimer.current);
+ if (syncTimer.current) clearTimeout(syncTimer.current);
+ };
+ }, []);
+
return (
<div
onClick={onSelect}
@@ -74,49 +161,34 @@ function CompCard({
}`}
>
<div className="w-20 h-[45px] rounded overflow-hidden bg-neutral-900 flex-shrink-0 relative">
- {/* Live iframe preview on hover */}
- {hovered && (
- <iframe
- src={previewUrl}
- sandbox="allow-scripts allow-same-origin"
- className="absolute left-0 top-0 border-none pointer-events-none"
- style={{
- transformOrigin: "0 0",
- width: stageSize.width,
- height: stageSize.height,
- transform: `scale(${previewScale})`,
- }}
- onLoad={(e) => {
- try {
- const iframe = e.currentTarget;
- const root = iframe.contentDocument?.querySelector("[data-composition-id]");
- const width =
- Number(root?.getAttribute("data-width")) || DEFAULT_PREVIEW_STAGE.width;
- const height =
- Number(root?.getAttribute("data-height")) || DEFAULT_PREVIEW_STAGE.height;
- setStageSize({ width, height });
- } catch {
- setStageSize(DEFAULT_PREVIEW_STAGE);
- }
- }}
- tabIndex={-1}
- />
- )}
- {/* Static thumbnail — hidden while hovering */}
- <div
- className="absolute inset-0 transition-opacity duration-150"
- style={{ opacity: hovered ? 0 : 1 }}
- >
- <img
- src={thumbnailUrl}
- alt={name}
- loading="lazy"
- className="w-full h-full object-contain"
- onError={(e) => {
- (e.target as HTMLImageElement).style.display = "none";
- }}
- />
- </div>
+ <iframe
+ ref={iframeRef}
+ src={previewUrl}
+ sandbox="allow-scripts allow-same-origin"
+ loading="lazy"
+ className="absolute left-0 top-0 border-none pointer-events-none"
+ style={{
+ transformOrigin: "0 0",
+ width: stageSize.width,
+ height: stageSize.height,
+ transform: `scale(${previewScale})`,
+ }}
+ onLoad={(e) => {
+ try {
+ const iframe = e.currentTarget;
+ const root = iframe.contentDocument?.querySelector("[data-composition-id]");
+ const width = Number(root?.getAttribute("data-width")) || DEFAULT_PREVIEW_STAGE.width;
+ const height =
+ Number(root?.getAttribute("data-height")) || DEFAULT_PREVIEW_STAGE.height;
+ setStageSize({ width, height });
+ requestIframePlaybackSync(hovered);
+ } catch {
+ setStageSize(DEFAULT_PREVIEW_STAGE);
+ }
+ }}
+ title={`${name} preview`}
+ tabIndex={-1}
+ />
</div>
<div className="min-w-0 flex-1">
<span className="text-[11px] font-medium text-neutral-300 truncate block">{name}</span>
diff --git a/packages/studio/src/components/sidebar/LeftSidebar.tsx b/packages/studio/src/components/sidebar/LeftSidebar.tsx
index a4172888c1..4864ce9a6c 100644
--- a/packages/studio/src/components/sidebar/LeftSidebar.tsx
+++ b/packages/studio/src/components/sidebar/LeftSidebar.tsx
@@ -90,64 +90,71 @@ export const LeftSidebar = memo(function LeftSidebar({
style={{ width }}
>
{/* Tabs — Code first */}
- <div className="flex border-b border-neutral-800/50 flex-shrink-0">
- <button
- type="button"
- onClick={() => selectTab("code")}
- className={`flex-1 py-2 text-[11px] font-medium transition-colors ${
- tab === "code"
- ? "text-neutral-200 border-b-2 border-studio-accent"
- : "text-neutral-500 hover:text-neutral-400"
- }`}
- >
- Code
- </button>
- <button
- type="button"
- onClick={() => selectTab("compositions")}
- className={`flex-1 py-2 text-[11px] font-medium transition-colors ${
- tab === "compositions"
- ? "text-neutral-200 border-b-2 border-studio-accent"
- : "text-neutral-500 hover:text-neutral-400"
- }`}
- >
- Compositions
- </button>
- <button
- type="button"
- onClick={() => selectTab("assets")}
- className={`flex-1 py-2 text-[11px] font-medium transition-colors ${
- tab === "assets"
- ? "text-neutral-200 border-b-2 border-studio-accent"
- : "text-neutral-500 hover:text-neutral-400"
- }`}
- >
- Assets
- </button>
- {onToggleCollapse && (
- <button
- type="button"
- onClick={onToggleCollapse}
- className="mx-1 my-1 flex h-7 w-7 flex-shrink-0 items-center justify-center rounded-md border border-transparent text-neutral-500 transition-colors hover:border-neutral-800 hover:bg-neutral-900 hover:text-neutral-300"
- title="Hide sidebar"
- aria-label="Hide sidebar"
+ <div className="border-b border-neutral-800/50 px-3 py-3 flex-shrink-0">
+ <div className="flex items-center gap-2">
+ <div
+ className="grid min-w-0 flex-1 gap-1 rounded-[18px] bg-neutral-900 p-1 shadow-[inset_0_1px_0_rgba(255,255,255,0.03)]"
+ style={{ gridTemplateColumns: "0.9fr 1.25fr 0.9fr" }}
>
- <svg
- width="14"
- height="14"
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- strokeWidth="1.5"
- strokeLinecap="round"
- strokeLinejoin="round"
- aria-hidden="true"
+ <button
+ type="button"
+ onClick={() => selectTab("code")}
+ className={`rounded-[14px] px-2.5 py-2 text-[10px] font-semibold transition-all ${
+ tab === "code"
+ ? "bg-neutral-800 text-white"
+ : "text-neutral-500 hover:text-neutral-200"
+ }`}
>
- <path d="m14 7-5 5 5 5" />
- <path d="M19 4v16" />
- </svg>
- </button>
- )}
+ Code
+ </button>
+ <button
+ type="button"
+ onClick={() => selectTab("compositions")}
+ className={`rounded-[14px] px-2.5 py-2 text-[10px] font-semibold transition-all ${
+ tab === "compositions"
+ ? "bg-neutral-800 text-white"
+ : "text-neutral-500 hover:text-neutral-200"
+ }`}
+ >
+ Compositions
+ </button>
+ <button
+ type="button"
+ onClick={() => selectTab("assets")}
+ className={`rounded-[14px] px-2.5 py-2 text-[10px] font-semibold transition-all ${
+ tab === "assets"
+ ? "bg-neutral-800 text-white"
+ : "text-neutral-500 hover:text-neutral-200"
+ }`}
+ >
+ Assets
+ </button>
+ </div>
+ {onToggleCollapse && (
+ <button
+ type="button"
+ onClick={onToggleCollapse}
+ className="flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-md border border-transparent text-neutral-500 transition-colors hover:border-neutral-800 hover:bg-neutral-900 hover:text-neutral-300"
+ title="Hide sidebar"
+ aria-label="Hide sidebar"
+ >
+ <svg
+ width="14"
+ height="14"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="1.5"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ aria-hidden="true"
+ >
+ <path d="m14 7-5 5 5 5" />
+ <path d="M19 4v16" />
+ </svg>
+ </button>
+ )}
+ </div>
</div>
{/* Tab content */}
diff --git a/packages/studio/src/hooks/usePersistentEditHistory.test.ts b/packages/studio/src/hooks/usePersistentEditHistory.test.ts
new file mode 100644
index 0000000000..3128ab0bb1
--- /dev/null
+++ b/packages/studio/src/hooks/usePersistentEditHistory.test.ts
@@ -0,0 +1,256 @@
+import { describe, expect, it } from "vitest";
+import { createEmptyEditHistory } from "../utils/editHistory";
+import type { EditHistoryStorageAdapter } from "../utils/editHistoryStorage";
+import { createMemoryEditHistoryStorage } from "../utils/editHistoryStorage";
+import {
+ createPersistentEditHistoryController,
+ createPersistentEditHistoryStore,
+} from "./usePersistentEditHistory";
+
+describe("createPersistentEditHistoryController", () => {
+ it("records history and reloads it for the same project", async () => {
+ const storage = createMemoryEditHistoryStorage();
+ const first = await createPersistentEditHistoryController({
+ projectId: "project-1",
+ storage,
+ now: () => 100,
+ onChange: () => {},
+ });
+
+ await first.recordEdit({
+ label: "Move layer",
+ kind: "manual",
+ files: { "index.html": { before: "a", after: "b" } },
+ });
+
+ const second = await createPersistentEditHistoryController({
+ projectId: "project-1",
+ storage,
+ now: () => 200,
+ onChange: () => {},
+ });
+
+ expect(second.snapshot().canUndo).toBe(true);
+ expect(second.snapshot().undoLabel).toBe("Move layer");
+ expect(second.snapshot().undoPaths).toEqual(["index.html"]);
+ });
+
+ it("undo applies files through the provided callback and persists redo state", async () => {
+ const storage = createMemoryEditHistoryStorage();
+ const controller = await createPersistentEditHistoryController({
+ projectId: "project-1",
+ storage,
+ now: () => 100,
+ onChange: () => {},
+ });
+ await controller.recordEdit({
+ label: "Move layer",
+ kind: "manual",
+ files: { "index.html": { before: "a", after: "b" } },
+ });
+
+ const result = await controller.undo({
+ readFile: async (path) => {
+ expect(path).toBe("index.html");
+ return "b";
+ },
+ writeFile: async (path, content) => {
+ expect(path).toBe("index.html");
+ expect(content).toBe("a");
+ },
+ });
+ expect(result.ok).toBe(true);
+ expect(result.paths).toEqual(["index.html"]);
+
+ expect(controller.snapshot().canUndo).toBe(false);
+ expect(controller.snapshot().canRedo).toBe(true);
+ expect(controller.snapshot().redoPaths).toEqual(["index.html"]);
+ });
+
+ it("keeps in-memory history when storage saves fail", async () => {
+ const storage: EditHistoryStorageAdapter = {
+ async get() {
+ return null;
+ },
+ async set() {
+ throw new Error("IndexedDB unavailable");
+ },
+ async delete() {},
+ };
+ const controller = await createPersistentEditHistoryController({
+ projectId: "project-1",
+ storage,
+ now: () => 100,
+ onChange: () => {},
+ });
+
+ await expect(
+ controller.recordEdit({
+ label: "Move layer",
+ kind: "manual",
+ files: { "index.html": { before: "a", after: "b" } },
+ }),
+ ).resolves.toBeUndefined();
+
+ expect(controller.snapshot().canUndo).toBe(true);
+ });
+
+ it("serializes concurrent record edits against the latest state", async () => {
+ const storage = createMemoryEditHistoryStorage();
+ let timestamp = 100;
+ const store = createPersistentEditHistoryStore({
+ projectId: "project-1",
+ storage,
+ initialState: createEmptyEditHistory(),
+ now: () => timestamp++,
+ onChange: () => {},
+ });
+
+ await Promise.all([
+ store.recordEdit({
+ label: "Move layer",
+ kind: "manual",
+ files: { "index.html": { before: "a", after: "b" } },
+ }),
+ store.recordEdit({
+ label: "Resize layer",
+ kind: "manual",
+ files: { "index.html": { before: "b", after: "c" } },
+ }),
+ ]);
+
+ expect(store.snapshot().state.undo.map((entry) => entry.label)).toEqual([
+ "Move layer",
+ "Resize layer",
+ ]);
+ });
+
+ it("still coalesces concurrent source edits that share a coalesce key", async () => {
+ const storage = createMemoryEditHistoryStorage();
+ let timestamp = 100;
+ const store = createPersistentEditHistoryStore({
+ projectId: "project-1",
+ storage,
+ initialState: createEmptyEditHistory(),
+ now: () => timestamp++,
+ onChange: () => {},
+ });
+
+ await Promise.all([
+ store.recordEdit({
+ label: "Edit source",
+ kind: "source",
+ coalesceKey: "source:index.html",
+ files: { "index.html": { before: "a", after: "b" } },
+ }),
+ store.recordEdit({
+ label: "Edit source",
+ kind: "source",
+ coalesceKey: "source:index.html",
+ files: { "index.html": { before: "b", after: "c" } },
+ }),
+ ]);
+
+ expect(store.snapshot().state.undo).toHaveLength(1);
+ expect(store.snapshot().state.undo[0].files["index.html"].before).toBe("a");
+ expect(store.snapshot().state.undo[0].files["index.html"].after).toBe("c");
+ });
+
+ it("reads undo hashes from the live top entry during queued undo calls", async () => {
+ const storage = createMemoryEditHistoryStorage();
+ let timestamp = 100;
+ const store = createPersistentEditHistoryStore({
+ projectId: "project-1",
+ storage,
+ initialState: createEmptyEditHistory(),
+ now: () => timestamp++,
+ onChange: () => {},
+ });
+ await store.recordEdit({
+ label: "Edit first file",
+ kind: "manual",
+ files: { "first.html": { before: "first-before", after: "first-after" } },
+ });
+ await store.recordEdit({
+ label: "Edit second file",
+ kind: "manual",
+ files: { "second.html": { before: "second-before", after: "second-after" } },
+ });
+
+ const files: Record<string, string> = {
+ "first.html": "first-after",
+ "second.html": "second-after",
+ };
+ const readPaths: string[] = [];
+
+ await Promise.all([
+ store.undo({
+ readFile: async (path) => {
+ readPaths.push(path);
+ return files[path];
+ },
+ writeFile: async (path, content) => {
+ files[path] = content;
+ },
+ }),
+ store.undo({
+ readFile: async (path) => {
+ readPaths.push(path);
+ return files[path];
+ },
+ writeFile: async (path, content) => {
+ files[path] = content;
+ },
+ }),
+ ]);
+
+ expect(readPaths).toEqual(["second.html", "first.html"]);
+ expect(files).toEqual({
+ "first.html": "first-before",
+ "second.html": "second-before",
+ });
+ expect(store.snapshot().canUndo).toBe(false);
+ expect(store.snapshot().canRedo).toBe(true);
+ });
+
+ it("rolls back files when an undo write fails partway through", async () => {
+ const storage = createMemoryEditHistoryStorage();
+ const store = createPersistentEditHistoryStore({
+ projectId: "project-1",
+ storage,
+ initialState: createEmptyEditHistory(),
+ now: () => 100,
+ onChange: () => {},
+ });
+ await store.recordEdit({
+ label: "Edit files",
+ kind: "manual",
+ files: {
+ "first.html": { before: "first-before", after: "first-after" },
+ "second.html": { before: "second-before", after: "second-after" },
+ },
+ });
+
+ const files: Record<string, string> = {
+ "first.html": "first-after",
+ "second.html": "second-after",
+ };
+ const result = store.undo({
+ readFile: async (path) => files[path],
+ writeFile: async (path, content) => {
+ if (path === "second.html" && content === "second-before") {
+ throw new Error("write failed");
+ }
+ files[path] = content;
+ },
+ });
+
+ await expect(result).rejects.toThrow("write failed");
+ expect(files).toEqual({
+ "first.html": "first-after",
+ "second.html": "second-after",
+ });
+ expect(store.snapshot().undoLabel).toBe("Edit files");
+ expect(store.snapshot().canRedo).toBe(false);
+ });
+});
diff --git a/packages/studio/src/hooks/usePersistentEditHistory.ts b/packages/studio/src/hooks/usePersistentEditHistory.ts
new file mode 100644
index 0000000000..de1af2867c
--- /dev/null
+++ b/packages/studio/src/hooks/usePersistentEditHistory.ts
@@ -0,0 +1,337 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import {
+ buildEditHistoryEntry,
+ createEmptyEditHistory,
+ hashEditHistoryContent,
+ pushEditHistoryEntry,
+ redoEditHistory,
+ undoEditHistory,
+ type BuildEditHistoryEntryInput,
+ type EditHistoryKind,
+ type EditHistoryState,
+} from "../utils/editHistory";
+import {
+ createIndexedDbEditHistoryStorage,
+ loadEditHistoryState,
+ saveEditHistoryState,
+ type EditHistoryStorageAdapter,
+} from "../utils/editHistoryStorage";
+
+interface RecordEditInput {
+ label: string;
+ kind: EditHistoryKind;
+ coalesceKey?: string;
+ files: BuildEditHistoryEntryInput["files"];
+}
+
+interface ApplyCallbacks {
+ readFile: (path: string) => Promise<string>;
+ writeFile: (path: string, content: string) => Promise<void>;
+}
+
+interface UsePersistentEditHistoryOptions {
+ projectId: string | null;
+ storage?: EditHistoryStorageAdapter;
+ now?: () => number;
+}
+
+interface ApplyResult {
+ ok: boolean;
+ reason?: "empty" | "content-mismatch";
+ label?: string;
+ paths?: string[];
+}
+
+interface PersistentEditHistoryStoreOptions {
+ projectId: string;
+ storage: EditHistoryStorageAdapter;
+ initialState: EditHistoryState;
+ now?: () => number;
+ onChange: (state: EditHistoryState) => void;
+}
+
+type EditHistoryMutation<T> = (state: EditHistoryState) => Promise<{
+ state: EditHistoryState;
+ result: T;
+}>;
+
+function createEntryId(now: number): string {
+ return `edit-${now.toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
+}
+
+function snapshotEditHistoryState(state: EditHistoryState) {
+ const undoEntry = state.undo[state.undo.length - 1] ?? null;
+ const redoEntry = state.redo[state.redo.length - 1] ?? null;
+ return {
+ canUndo: Boolean(undoEntry),
+ canRedo: Boolean(redoEntry),
+ undoLabel: undoEntry?.label ?? null,
+ redoLabel: redoEntry?.label ?? null,
+ undoPaths: undoEntry ? Object.keys(undoEntry.files) : [],
+ redoPaths: redoEntry ? Object.keys(redoEntry.files) : [],
+ state,
+ };
+}
+
+async function readCurrentFileHashes(
+ paths: string[],
+ readFile: (path: string) => Promise<string>,
+): Promise<{
+ currentFiles: Record<string, string>;
+ currentHashes: Record<string, string>;
+}> {
+ const currentFiles: Record<string, string> = {};
+ const currentHashes: Record<string, string> = {};
+ for (const path of paths) {
+ const content = await readFile(path);
+ currentFiles[path] = content;
+ currentHashes[path] = hashEditHistoryContent(content);
+ }
+ return { currentFiles, currentHashes };
+}
+
+async function writeFilesWithRollback({
+ files,
+ rollbackFiles,
+ writeFile,
+}: {
+ files: Record<string, string>;
+ rollbackFiles: Record<string, string>;
+ writeFile: (path: string, content: string) => Promise<void>;
+}): Promise<void> {
+ const writtenPaths: string[] = [];
+ try {
+ for (const [path, content] of Object.entries(files)) {
+ await writeFile(path, content);
+ writtenPaths.push(path);
+ }
+ } catch (error) {
+ try {
+ for (const path of writtenPaths.reverse()) {
+ await writeFile(path, rollbackFiles[path]);
+ }
+ } catch (rollbackError) {
+ throw new AggregateError(
+ [error, rollbackError],
+ "Failed to apply edit history and rollback did not complete",
+ );
+ }
+ throw error;
+ }
+}
+
+export function createPersistentEditHistoryStore({
+ projectId,
+ storage,
+ initialState,
+ now = Date.now,
+ onChange,
+}: PersistentEditHistoryStoreOptions) {
+ let state = initialState;
+ let queue = Promise.resolve();
+
+ const save = async (nextState: EditHistoryState) => {
+ state = nextState;
+ onChange(nextState);
+ try {
+ await saveEditHistoryState(storage, projectId, nextState);
+ } catch {
+ // Keep in-memory history usable when IndexedDB is unavailable.
+ }
+ };
+
+ const mutate = async <T>(mutation: EditHistoryMutation<T>): Promise<T> => {
+ const run = queue.then(async () => {
+ const { state: nextState, result } = await mutation(state);
+ if (nextState !== state) await save(nextState);
+ return result;
+ });
+ queue = run.then(
+ () => undefined,
+ () => undefined,
+ );
+ return run;
+ };
+
+ return {
+ snapshot: () => snapshotEditHistoryState(state),
+ async recordEdit(input: RecordEditInput) {
+ await mutate<void>(async (currentState) => {
+ const timestamp = now();
+ const entry = buildEditHistoryEntry({
+ ...input,
+ id: createEntryId(timestamp),
+ projectId,
+ now: timestamp,
+ });
+ return {
+ state: pushEditHistoryEntry(currentState, entry),
+ result: undefined,
+ };
+ });
+ },
+ async undo(callbacks: ApplyCallbacks): Promise<ApplyResult> {
+ return mutate<ApplyResult>(async (currentState) => {
+ const entry = currentState.undo[currentState.undo.length - 1];
+ if (!entry) {
+ return {
+ state: currentState,
+ result: { ok: false, reason: "empty" },
+ };
+ }
+ const { currentFiles, currentHashes } = await readCurrentFileHashes(
+ Object.keys(entry.files),
+ callbacks.readFile,
+ );
+ const result = undoEditHistory(currentState, currentHashes, now());
+ if (!result.ok) {
+ return {
+ state: currentState,
+ result: { ok: false, reason: result.reason },
+ };
+ }
+ await writeFilesWithRollback({
+ files: result.filesToWrite,
+ rollbackFiles: currentFiles,
+ writeFile: callbacks.writeFile,
+ });
+ return {
+ state: result.state,
+ result: { ok: true, label: result.entry.label, paths: Object.keys(result.entry.files) },
+ };
+ });
+ },
+ async redo(callbacks: ApplyCallbacks): Promise<ApplyResult> {
+ return mutate<ApplyResult>(async (currentState) => {
+ const entry = currentState.redo[currentState.redo.length - 1];
+ if (!entry) {
+ return {
+ state: currentState,
+ result: { ok: false, reason: "empty" },
+ };
+ }
+ const { currentFiles, currentHashes } = await readCurrentFileHashes(
+ Object.keys(entry.files),
+ callbacks.readFile,
+ );
+ const result = redoEditHistory(currentState, currentHashes, now());
+ if (!result.ok) {
+ return {
+ state: currentState,
+ result: { ok: false, reason: result.reason },
+ };
+ }
+ await writeFilesWithRollback({
+ files: result.filesToWrite,
+ rollbackFiles: currentFiles,
+ writeFile: callbacks.writeFile,
+ });
+ return {
+ state: result.state,
+ result: { ok: true, label: result.entry.label, paths: Object.keys(result.entry.files) },
+ };
+ });
+ },
+ };
+}
+
+export async function createPersistentEditHistoryController({
+ projectId,
+ storage,
+ now = Date.now,
+ onChange,
+}: {
+ projectId: string;
+ storage: EditHistoryStorageAdapter;
+ now?: () => number;
+ onChange: (state: EditHistoryState) => void;
+}) {
+ let state = await loadEditHistoryState(storage, projectId);
+ const store = createPersistentEditHistoryStore({
+ projectId,
+ storage,
+ initialState: state,
+ now,
+ onChange: (nextState) => {
+ state = nextState;
+ onChange(nextState);
+ },
+ });
+
+ return store;
+}
+
+export function usePersistentEditHistory(options: UsePersistentEditHistoryOptions) {
+ const storage = useMemo(
+ () => options.storage ?? createIndexedDbEditHistoryStorage(),
+ [options.storage],
+ );
+ const now = options.now ?? Date.now;
+ const [state, setState] = useState<EditHistoryState>(() => createEmptyEditHistory());
+ const [loaded, setLoaded] = useState(false);
+ const projectId = options.projectId;
+ const storeRef = useRef<ReturnType<typeof createPersistentEditHistoryStore> | null>(null);
+
+ useEffect(() => {
+ let cancelled = false;
+ const emptyState = createEmptyEditHistory();
+ storeRef.current = null;
+ setState(emptyState);
+ setLoaded(false);
+ if (!projectId) {
+ setLoaded(true);
+ return;
+ }
+
+ loadEditHistoryState(storage, projectId)
+ .then((loadedState) => {
+ if (cancelled) return;
+ storeRef.current = createPersistentEditHistoryStore({
+ projectId,
+ storage,
+ initialState: loadedState,
+ now,
+ onChange: setState,
+ });
+ setState(loadedState);
+ })
+ .catch(() => {
+ if (cancelled) return;
+ storeRef.current = createPersistentEditHistoryStore({
+ projectId,
+ storage,
+ initialState: emptyState,
+ now,
+ onChange: setState,
+ });
+ setState(emptyState);
+ })
+ .finally(() => {
+ if (!cancelled) setLoaded(true);
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [now, projectId, storage]);
+
+ const recordEdit = useCallback(async (input: RecordEditInput) => {
+ await storeRef.current?.recordEdit(input);
+ }, []);
+
+ const undo = useCallback(async (callbacks: ApplyCallbacks): Promise<ApplyResult> => {
+ return storeRef.current?.undo(callbacks) ?? { ok: false, reason: "empty" };
+ }, []);
+
+ const redo = useCallback(async (callbacks: ApplyCallbacks): Promise<ApplyResult> => {
+ return storeRef.current?.redo(callbacks) ?? { ok: false, reason: "empty" };
+ }, []);
+
+ return {
+ loaded,
+ ...snapshotEditHistoryState(state),
+ recordEdit,
+ undo,
+ redo,
+ };
+}
diff --git a/packages/studio/src/icons/SystemIcons.tsx b/packages/studio/src/icons/SystemIcons.tsx
index d63ad8cae0..00b4456d3c 100644
--- a/packages/studio/src/icons/SystemIcons.tsx
+++ b/packages/studio/src/icons/SystemIcons.tsx
@@ -54,6 +54,7 @@ import {
ClipboardText,
ArrowCounterClockwise,
Camera as PhCamera,
+ ArrowClockwise,
Gear,
} from "@phosphor-icons/react";
import type { Icon as PhosphorIcon, IconProps as PhosphorIconProps } from "@phosphor-icons/react";
@@ -129,4 +130,5 @@ export const ChevronRight = makeIcon(CaretRight);
export const ClipboardList = makeIcon(ClipboardText);
export const RotateCcw = makeIcon(ArrowCounterClockwise);
export const Camera = makeIcon(PhCamera);
+export const RotateCw = makeIcon(ArrowClockwise);
export const Settings = makeIcon(Gear);
diff --git a/packages/studio/src/player/components/CompositionThumbnail.test.ts b/packages/studio/src/player/components/CompositionThumbnail.test.ts
new file mode 100644
index 0000000000..65dc0a997f
--- /dev/null
+++ b/packages/studio/src/player/components/CompositionThumbnail.test.ts
@@ -0,0 +1,19 @@
+import { describe, expect, it } from "vitest";
+import { buildCompositionThumbnailUrl } from "./CompositionThumbnail";
+
+describe("buildCompositionThumbnailUrl", () => {
+ it("includes selector and occurrence index for precise element thumbnails", () => {
+ expect(
+ buildCompositionThumbnailUrl({
+ previewUrl: "/api/projects/demo/preview",
+ seekTime: 1,
+ duration: 2,
+ selector: ".card",
+ selectorIndex: 2,
+ origin: "http://localhost:3000",
+ }),
+ ).toBe(
+ "http://localhost:3000/api/projects/demo/thumbnail/index.html?t=2.00&v=v3&selector=.card&selectorIndex=2",
+ );
+ });
+});
diff --git a/packages/studio/src/player/components/CompositionThumbnail.tsx b/packages/studio/src/player/components/CompositionThumbnail.tsx
index 6fdcecc30b..bacc7daa2e 100644
--- a/packages/studio/src/player/components/CompositionThumbnail.tsx
+++ b/packages/studio/src/player/components/CompositionThumbnail.tsx
@@ -7,6 +7,7 @@ interface CompositionThumbnailProps {
labelColor: string;
accentColor?: string;
selector?: string;
+ selectorIndex?: number;
seekTime?: number;
duration?: number;
width?: number;
@@ -14,7 +15,38 @@ interface CompositionThumbnailProps {
}
const CLIP_HEIGHT = 66;
-const THUMBNAIL_URL_VERSION = "v2";
+const THUMBNAIL_URL_VERSION = "v3";
+
+export function buildCompositionThumbnailUrl({
+ previewUrl,
+ seekTime = 2,
+ duration = 5,
+ selector,
+ selectorIndex,
+ origin,
+}: {
+ previewUrl: string;
+ seekTime?: number;
+ duration?: number;
+ selector?: string;
+ selectorIndex?: number;
+ origin: string;
+}): string {
+ const thumbnailBase = previewUrl
+ .replace("/preview/comp/", "/thumbnail/")
+ .replace(/\/preview$/, "/thumbnail/index.html");
+ const midTime = seekTime + duration / 2;
+ const thumbnailUrl = new URL(thumbnailBase, origin);
+ thumbnailUrl.searchParams.set("t", midTime.toFixed(2));
+ thumbnailUrl.searchParams.set("v", THUMBNAIL_URL_VERSION);
+ if (selector) {
+ thumbnailUrl.searchParams.set("selector", selector);
+ if (selectorIndex != null && selectorIndex > 0) {
+ thumbnailUrl.searchParams.set("selectorIndex", String(selectorIndex));
+ }
+ }
+ return thumbnailUrl.toString();
+}
export const CompositionThumbnail = memo(function CompositionThumbnail({
previewUrl,
@@ -22,6 +54,7 @@ export const CompositionThumbnail = memo(function CompositionThumbnail({
labelColor,
accentColor = "#6B7280",
selector,
+ selectorIndex,
seekTime = 2,
duration = 5,
}: CompositionThumbnailProps) {
@@ -48,15 +81,14 @@ export const CompositionThumbnail = memo(function CompositionThumbnail({
roRef.current?.disconnect();
});
- const thumbnailBase = previewUrl
- .replace("/preview/comp/", "/thumbnail/")
- .replace(/\/preview$/, "/thumbnail/index.html");
- const midTime = seekTime + duration / 2;
- const thumbnailUrl = new URL(thumbnailBase, window.location.origin);
- thumbnailUrl.searchParams.set("t", midTime.toFixed(2));
- thumbnailUrl.searchParams.set("v", THUMBNAIL_URL_VERSION);
- if (selector) thumbnailUrl.searchParams.set("selector", selector);
- const url = thumbnailUrl.toString();
+ const url = buildCompositionThumbnailUrl({
+ previewUrl,
+ seekTime,
+ duration,
+ selector,
+ selectorIndex,
+ origin: window.location.origin,
+ });
const frameW = Math.max(48, Math.round(CLIP_HEIGHT * aspect));
const frameCount = containerWidth > 0 ? Math.max(1, Math.ceil(containerWidth / frameW)) : 1;
@@ -66,7 +98,7 @@ export const CompositionThumbnail = memo(function CompositionThumbnail({
src={url}
alt=""
draggable={false}
- loading="lazy"
+ loading="eager"
onLoad={(e) => {
const img = e.currentTarget;
if (img.naturalWidth > 0 && img.naturalHeight > 0) {
diff --git a/packages/studio/src/player/components/EditModal.tsx b/packages/studio/src/player/components/EditModal.tsx
index 067426c083..dae44f2d2c 100644
--- a/packages/studio/src/player/components/EditModal.tsx
+++ b/packages/studio/src/player/components/EditModal.tsx
@@ -3,6 +3,7 @@ import { useMountEffect } from "../../hooks/useMountEffect";
import { usePlayerStore } from "../store/playerStore";
import { formatTime } from "../lib/time";
import { buildPromptCopyText, buildTimelineAgentPrompt } from "./timelineEditing";
+import { copyTextToClipboard } from "../../utils/clipboard";
interface EditPopoverProps {
rangeStart: number;
@@ -62,16 +63,8 @@ export function EditPopover({ rangeStart, rangeEnd, anchorX, anchorY, onClose }:
}, [start, end, elementsInRange, prompt]);
const handleCopy = useCallback(async () => {
- try {
- await navigator.clipboard.writeText(buildClipboardText());
- } catch {
- const ta = document.createElement("textarea");
- ta.value = buildClipboardText();
- document.body.appendChild(ta);
- ta.select();
- document.execCommand("copy");
- document.body.removeChild(ta);
- }
+ const copied = await copyTextToClipboard(buildClipboardText());
+ if (!copied) return;
setCopiedAgentPrompt(true);
setTimeout(() => {
setCopiedAgentPrompt(false);
@@ -82,16 +75,8 @@ export function EditPopover({ rangeStart, rangeEnd, anchorX, anchorY, onClose }:
const handleCopyPrompt = useCallback(async () => {
const promptText = buildPromptCopyText(prompt);
if (!promptText) return;
- try {
- await navigator.clipboard.writeText(promptText);
- } catch {
- const ta = document.createElement("textarea");
- ta.value = promptText;
- document.body.appendChild(ta);
- ta.select();
- document.execCommand("copy");
- document.body.removeChild(ta);
- }
+ const copied = await copyTextToClipboard(promptText);
+ if (!copied) return;
setCopiedPromptOnly(true);
setTimeout(() => {
setCopiedPromptOnly(false);
diff --git a/packages/studio/src/player/components/Player.tsx b/packages/studio/src/player/components/Player.tsx
index 519536d318..6e8eaf6089 100644
--- a/packages/studio/src/player/components/Player.tsx
+++ b/packages/studio/src/player/components/Player.tsx
@@ -1,21 +1,30 @@
import { forwardRef, useRef, useState } from "react";
import { isLottieAnimationLoaded } from "@hyperframes/core/runtime/lottie-readiness";
import { useMountEffect } from "../../hooks/useMountEffect";
-// NOTE: importing "@hyperframes/player" registers a class extending HTMLElement
-// at module load, which throws under SSR. Defer the import to the mount effect
-// so it only runs in the browser.
interface PlayerProps {
projectId?: string;
directUrl?: string;
onLoad: () => void;
portrait?: boolean;
+ style?: React.CSSProperties;
}
interface HyperframesPlayerElement extends HTMLElement {
iframeElement: HTMLIFrameElement;
}
+function enableInteractiveIframe(player: HyperframesPlayerElement): void {
+ const root = player.shadowRoot;
+ if (!root) return;
+
+ const container = root.querySelector<HTMLElement>(".hfp-container");
+ const iframe = root.querySelector<HTMLIFrameElement>(".hfp-iframe");
+
+ container?.style.setProperty("pointer-events", "auto");
+ iframe?.style.setProperty("pointer-events", "auto");
+}
+
// Assets are considered ready when every `<video>`/`<audio>` has enough data
// to play through without buffering, and every registered Lottie animation has
// finished loading.
@@ -49,18 +58,9 @@ function hasUnloadedAssets(iframe: HTMLIFrameElement, lastResult: boolean): bool
}
}
-/**
- * Renders a composition preview using the <hyperframes-player> web component.
- *
- * The web component handles iframe scaling, dimension detection, and
- * ResizeObserver internally. This wrapper bridges its inner iframe to the
- * forwarded ref so useTimelinePlayer can access it for clip manifest parsing,
- * timeline probing, and DOM inspection.
- */
export const Player = forwardRef<HTMLIFrameElement, PlayerProps>(
- ({ projectId, directUrl, onLoad, portrait }, ref) => {
+ ({ projectId, directUrl, onLoad, portrait, style }, ref) => {
const containerRef = useRef<HTMLDivElement>(null);
- const loadCountRef = useRef(0);
const assetPollRef = useRef<ReturnType<typeof setInterval> | null>(null);
const [assetsLoading, setAssetsLoading] = useState(false);
@@ -71,11 +71,9 @@ export const Player = forwardRef<HTMLIFrameElement, PlayerProps>(
let canceled = false;
let cleanup: (() => void) | undefined;
- // Dynamic import registers the custom element in the browser only.
import("@hyperframes/player").then(() => {
if (canceled) return;
- // Create the web component imperatively to avoid JSX custom-element typing.
const player = document.createElement("hyperframes-player") as HyperframesPlayerElement;
const src = directUrl || `/api/projects/${projectId}/preview`;
player.setAttribute("src", src);
@@ -85,8 +83,8 @@ export const Player = forwardRef<HTMLIFrameElement, PlayerProps>(
player.style.height = "100%";
player.style.display = "block";
container.appendChild(player);
+ enableInteractiveIframe(player);
- // Bridge the inner iframe to the forwarded ref for useTimelinePlayer.
const iframe = player.iframeElement;
if (typeof ref === "function") {
ref(iframe);
@@ -94,35 +92,12 @@ export const Player = forwardRef<HTMLIFrameElement, PlayerProps>(
(ref as React.MutableRefObject<HTMLIFrameElement | null>).current = iframe;
}
- // Prevent the web component's built-in click-to-toggle behavior.
- // The studio manages playback exclusively via useTimelinePlayer.
const preventToggle = (e: Event) => e.stopImmediatePropagation();
player.addEventListener("click", preventToggle, { capture: true });
- // Forward the iframe's native load event to the studio's onIframeLoad.
const handleLoad = () => {
- loadCountRef.current++;
- // Reveal animation on reload (hot-reload, composition switch)
- if (loadCountRef.current > 1) {
- container.classList.remove("preview-revealing");
- void container.offsetWidth;
- container.classList.add("preview-revealing");
- const onEnd = () => container.classList.remove("preview-revealing");
- container.addEventListener("animationend", onEnd, { once: true });
- }
onLoad();
- // Show a loading overlay until every `<video>`/`<audio>` and Lottie
- // asset is ready. Without this users can click play before audio has
- // buffered — the runtime is resilient (queued play() resolves once
- // data arrives), but the overlay communicates why the first frame
- // or first audio beat may lag.
- //
- // Poll with a 10 s safety cap (100 ticks × 100 ms). If the cap
- // trips we hide the overlay so the UI doesn't appear stuck forever,
- // but we log a debug warning so the case is diagnosable — a long
- // cold video or a broken asset can legitimately exceed 10 s on a
- // slow network.
if (assetPollRef.current) clearInterval(assetPollRef.current);
let lastUnloaded = hasUnloadedAssets(iframe, false);
if (lastUnloaded) {
@@ -135,11 +110,6 @@ export const Player = forwardRef<HTMLIFrameElement, PlayerProps>(
if (assetPollRef.current) clearInterval(assetPollRef.current);
assetPollRef.current = null;
setAssetsLoading(false);
- if (lastUnloaded) {
- console.debug(
- "[Player] Asset-loading overlay timed out after 10s; hiding anyway. Check network or asset integrity.",
- );
- }
}
}, 100);
} else {
@@ -154,7 +124,6 @@ export const Player = forwardRef<HTMLIFrameElement, PlayerProps>(
if (assetPollRef.current) clearInterval(assetPollRef.current);
assetPollRef.current = null;
container.removeChild(player);
- // Clear the forwarded ref
if (typeof ref === "function") {
ref(null);
} else if (ref) {
@@ -170,7 +139,10 @@ export const Player = forwardRef<HTMLIFrameElement, PlayerProps>(
});
return (
- <div className="relative w-full h-full max-w-full max-h-full overflow-hidden bg-black flex items-center justify-center">
+ <div
+ className="relative w-full h-full max-w-full max-h-full overflow-hidden bg-black flex items-center justify-center"
+ style={style}
+ >
<div ref={containerRef} className="w-full h-full" />
{assetsLoading && (
<div className="absolute inset-0 bg-black/80 flex flex-col items-center justify-center z-20 pointer-events-none">
diff --git a/packages/studio/src/player/components/Timeline.test.ts b/packages/studio/src/player/components/Timeline.test.ts
index 19041d5e07..6b9390e63d 100644
--- a/packages/studio/src/player/components/Timeline.test.ts
+++ b/packages/studio/src/player/components/Timeline.test.ts
@@ -8,6 +8,7 @@ import {
getTimelinePlayheadLeft,
getTimelineScrollLeftForZoomAnchor,
getTimelineScrollLeftForZoomTransition,
+ shouldShowTimelineShortcutHint,
shouldHandleTimelineDeleteKey,
shouldAutoScrollTimeline,
} from "./Timeline";
@@ -237,6 +238,17 @@ describe("getTimelineCanvasHeight", () => {
});
});
+describe("shouldShowTimelineShortcutHint", () => {
+ it("shows the hint when the timeline does not vertically overflow", () => {
+ expect(shouldShowTimelineShortcutHint(220, 220)).toBe(true);
+ expect(shouldShowTimelineShortcutHint(220.5, 220)).toBe(true);
+ });
+
+ it("hides the hint when timeline tracks need vertical scrolling", () => {
+ expect(shouldShowTimelineShortcutHint(221.5, 220)).toBe(false);
+ });
+});
+
describe("shouldHandleTimelineDeleteKey", () => {
it("handles Delete and Backspace when focus is not in an editor", () => {
expect(shouldHandleTimelineDeleteKey({ key: "Delete" })).toBe(true);
diff --git a/packages/studio/src/player/components/Timeline.tsx b/packages/studio/src/player/components/Timeline.tsx
index 4ed4319ccf..8db945621e 100644
--- a/packages/studio/src/player/components/Timeline.tsx
+++ b/packages/studio/src/player/components/Timeline.tsx
@@ -35,7 +35,7 @@ const TRACK_H = 72;
const RULER_H = 24;
const CLIP_Y = 3; // vertical inset inside track
const CLIP_HANDLE_W = 18;
-const TIMELINE_SCROLL_BUFFER = 24;
+const TIMELINE_SCROLL_BUFFER = 20;
interface TrackVisualStyle extends TimelineTrackStyle {
icon: ReactNode;
@@ -216,6 +216,14 @@ export function getTimelineCanvasHeight(trackCount: number): number {
return RULER_H + Math.max(0, trackCount) * TRACK_H + TIMELINE_SCROLL_BUFFER;
}
+export function shouldShowTimelineShortcutHint(
+ scrollHeight: number,
+ clientHeight: number,
+): boolean {
+ if (!Number.isFinite(scrollHeight) || !Number.isFinite(clientHeight)) return true;
+ return scrollHeight - clientHeight <= 1;
+}
+
export function shouldHandleTimelineDeleteKey(input: {
key: string;
metaKey?: boolean;
@@ -279,7 +287,6 @@ export function resolveTimelineAssetDrop(
track: getDefaultDroppedTrack(input.trackOrder, rowIndex),
};
}
-
/* ── Component ──────────────────────────────────────────────────── */
interface TimelineProps {
/** Called when user seeks via ruler/track click or playhead drag */
@@ -427,30 +434,51 @@ export const Timeline = memo(function Timeline({
onDeleteElementRef.current = onDeleteElement;
const suppressClickRef = useRef(false);
const [showPopover, setShowPopover] = useState(false);
+ const [showShortcutHint, setShowShortcutHint] = useState(true);
const [viewportWidth, setViewportWidth] = useState(0);
const roRef = useRef<ResizeObserver | null>(null);
+ const shortcutHintRafRef = useRef(0);
+ const syncShortcutHintVisibility = useCallback(() => {
+ const scroll = scrollRef.current;
+ setShowShortcutHint(
+ scroll ? shouldShowTimelineShortcutHint(scroll.scrollHeight, scroll.clientHeight) : true,
+ );
+ }, []);
+ const scheduleShortcutHintVisibilitySync = useCallback(() => {
+ if (shortcutHintRafRef.current) cancelAnimationFrame(shortcutHintRafRef.current);
+ shortcutHintRafRef.current = requestAnimationFrame(() => {
+ shortcutHintRafRef.current = 0;
+ syncShortcutHintVisibility();
+ });
+ }, [syncShortcutHintVisibility]);
// Callback ref: sets up ResizeObserver when the DOM element actually mounts.
// useMountEffect can't work here because the component returns null on first
// render (timelineReady=false), so containerRef.current is null when the
// effect fires and the ResizeObserver is never created.
- const setContainerRef = useCallback((el: HTMLDivElement | null) => {
- if (roRef.current) {
- roRef.current.disconnect();
- roRef.current = null;
- }
- containerRef.current = el;
- if (!el) return;
- setViewportWidth(el.clientWidth);
- roRef.current = new ResizeObserver(([entry]) => {
- setViewportWidth(entry.contentRect.width);
- });
- roRef.current.observe(el);
- }, []);
+ const setContainerRef = useCallback(
+ (el: HTMLDivElement | null) => {
+ if (roRef.current) {
+ roRef.current.disconnect();
+ roRef.current = null;
+ }
+ containerRef.current = el;
+ if (!el) return;
+ setViewportWidth(el.clientWidth);
+ scheduleShortcutHintVisibilitySync();
+ roRef.current = new ResizeObserver(([entry]) => {
+ setViewportWidth(entry.contentRect.width);
+ scheduleShortcutHintVisibilitySync();
+ });
+ roRef.current.observe(el);
+ },
+ [scheduleShortcutHintVisibilitySync],
+ );
// Clean up ResizeObserver on unmount
useMountEffect(() => () => {
roRef.current?.disconnect();
+ if (shortcutHintRafRef.current) cancelAnimationFrame(shortcutHintRafRef.current);
});
// Effective duration: max of store duration and the furthest element end.
@@ -495,6 +523,7 @@ export const Timeline = memo(function Timeline({
}
return [...trackOrder, draggedClip.previewTrack].sort((a, b) => a - b);
}, [draggedClip, trackOrder]);
+ const totalH = getTimelineCanvasHeight(displayTrackOrder.length);
const selectedElement = useMemo(
() => elements.find((element) => (element.key ?? element.id) === selectedElementId) ?? null,
[elements, selectedElementId],
@@ -544,7 +573,6 @@ export const Timeline = memo(function Timeline({
);
previousZoomModeRef.current = zoomMode;
}, [zoomMode]);
-
useMountEffect(() => {
const unsub = liveTime.subscribe((t) => {
const dur = durationRef.current;
@@ -1012,6 +1040,10 @@ export const Timeline = memo(function Timeline({
);
const majorTickInterval =
major.length >= 2 ? Math.max(0.25, major[1] - major[0]) : effectiveDuration;
+ useEffect(() => {
+ syncShortcutHintVisibility();
+ }, [syncShortcutHintVisibility, timelineReady, elements.length, totalH]);
+
const getPreviewElement = useCallback(
(element: TimelineElement): TimelineElement => {
if (
@@ -1239,7 +1271,6 @@ export const Timeline = memo(function Timeline({
);
}
- const totalH = getTimelineCanvasHeight(displayTrackOrder.length);
const draggedElement = draggedClip?.element ?? null;
const activeDraggedElement =
draggedClip?.started === true && draggedElement
@@ -1313,7 +1344,7 @@ export const Timeline = memo(function Timeline({
<div
ref={setContainerRef}
aria-label="Timeline"
- className={`border-t select-none h-full overflow-hidden ${shiftHeld ? "cursor-crosshair" : "cursor-default"}`}
+ className={`relative border-t select-none h-full overflow-hidden ${shiftHeld ? "cursor-crosshair" : "cursor-default"}`}
style={{
touchAction: "pan-x pan-y",
background: theme.shellBackground,
@@ -1652,8 +1683,8 @@ export const Timeline = memo(function Timeline({
</div>
</div>
- {/* Keyboard shortcut hint — always visible */}
- {!showPopover && !rangeSelection && (
+ {/* Keyboard shortcut hint */}
+ {showShortcutHint && !showPopover && !rangeSelection && (
<div className="absolute bottom-2 right-3 pointer-events-none z-20">
<div
className="flex items-center gap-1.5 px-2 py-1 rounded-md border"
diff --git a/packages/studio/src/player/components/TimelineClip.tsx b/packages/studio/src/player/components/TimelineClip.tsx
index 0bd3b30860..59ac0fa536 100644
--- a/packages/studio/src/player/components/TimelineClip.tsx
+++ b/packages/studio/src/player/components/TimelineClip.tsx
@@ -63,6 +63,25 @@ export const TimelineClip = memo(function TimelineClip({
const capabilities = getTimelineEditCapabilities(el);
const displayLabel = el.label || el.id || el.tag;
const showHandles = handleOpacity > 0.01;
+ const baseBackgroundImage = isSelected ? theme.clipBackgroundActive : theme.clipBackground;
+ const glossBackgroundImage = isSelected
+ ? "linear-gradient(180deg, rgba(255,255,255,0.03), rgba(255,255,255,0))"
+ : "linear-gradient(180deg, rgba(255,255,255,0.02), rgba(255,255,255,0))";
+ const accentBackgroundImage = `linear-gradient(120deg, ${trackStyle.accent}${
+ isSelected ? "22" : "1e"
+ }, transparent 28%)`;
+ const compositionStripeBackgroundImage =
+ isComposition && !hasCustomContent
+ ? "repeating-linear-gradient(135deg, transparent, transparent 3px, rgba(255,255,255,0.05) 3px, rgba(255,255,255,0.05) 6px)"
+ : undefined;
+ const clipBackgroundImage = [
+ compositionStripeBackgroundImage,
+ glossBackgroundImage,
+ accentBackgroundImage,
+ baseBackgroundImage,
+ ]
+ .filter(Boolean)
+ .join(", ");
return (
<div
@@ -76,13 +95,7 @@ export const TimelineClip = memo(function TimelineClip({
top: clipY,
bottom: clipY,
borderRadius: theme.clipRadius,
- background: isSelected
- ? `linear-gradient(180deg, rgba(255,255,255,0.03), rgba(255,255,255,0)), linear-gradient(120deg, ${trackStyle.accent}22, transparent 28%), ${theme.clipBackgroundActive}`
- : `linear-gradient(180deg, rgba(255,255,255,0.02), rgba(255,255,255,0)), linear-gradient(120deg, ${trackStyle.accent}1e, transparent 28%), ${theme.clipBackground}`,
- backgroundImage:
- isComposition && !hasCustomContent
- ? `repeating-linear-gradient(135deg, transparent, transparent 3px, rgba(255,255,255,0.05) 3px, rgba(255,255,255,0.05) 6px)`
- : undefined,
+ backgroundImage: clipBackgroundImage,
border: `1px solid ${borderColor}`,
boxShadow,
transition:
diff --git a/packages/studio/src/player/components/timelineEditing.test.ts b/packages/studio/src/player/components/timelineEditing.test.ts
index 2ca13fe593..5282e621c4 100644
--- a/packages/studio/src/player/components/timelineEditing.test.ts
+++ b/packages/studio/src/player/components/timelineEditing.test.ts
@@ -248,7 +248,7 @@ describe("getTimelineEditCapabilities", () => {
});
});
- it("disables move and trims for generic motion clips even when patchable", () => {
+ it("allows moving generic motion clips while keeping trims blocked", () => {
expect(
getTimelineEditCapabilities({
tag: "section",
@@ -256,7 +256,7 @@ describe("getTimelineEditCapabilities", () => {
selector: ".feature-card",
}),
).toEqual({
- canMove: false,
+ canMove: true,
canTrimStart: false,
canTrimEnd: false,
});
@@ -428,7 +428,6 @@ describe("buildClipRangeSelection", () => {
});
});
});
-
describe("resolveTimelineAutoScroll", () => {
it("does not scroll when the pointer stays away from the edges", () => {
expect(
@@ -512,7 +511,6 @@ describe("buildTimelineElementAgentPrompt", () => {
).toContain("If this clip is animated with GSAP");
});
});
-
describe("resolveTimelineResize", () => {
it("shrinks clip duration from the right edge", () => {
expect(
diff --git a/packages/studio/src/player/components/timelineEditing.ts b/packages/studio/src/player/components/timelineEditing.ts
index 9f8ffc8aec..4016c0cd45 100644
--- a/packages/studio/src/player/components/timelineEditing.ts
+++ b/packages/studio/src/player/components/timelineEditing.ts
@@ -233,7 +233,7 @@ export function getTimelineEditCapabilities(input: {
const hasFiniteDuration = Number.isFinite(input.duration) && input.duration > 0;
const hasDeterministicWindow = isDeterministicTimelineWindow(input);
return {
- canMove: canPatch && hasDeterministicWindow,
+ canMove: canPatch && (hasDeterministicWindow || hasFiniteDuration),
canTrimEnd: canPatch && hasFiniteDuration && hasDeterministicWindow,
canTrimStart: canPatch && hasFiniteDuration && canOffsetTrimClipStart(input),
};
@@ -273,7 +273,6 @@ export function buildClipRangeSelection(
anchorY: anchor.anchorY,
};
}
-
export function buildTimelineAgentPrompt({
rangeStart,
rangeEnd,
@@ -347,7 +346,6 @@ export function buildTimelineElementAgentPrompt(element: {
return lines.join("\n");
}
-
export function formatTimelineAttributeNumber(value: number): string {
return Number(roundToCentiseconds(value).toFixed(2)).toString();
}
diff --git a/packages/studio/src/player/hooks/useTimelinePlayer.test.ts b/packages/studio/src/player/hooks/useTimelinePlayer.test.ts
index 2c89583f23..a8c7d590f5 100644
--- a/packages/studio/src/player/hooks/useTimelinePlayer.test.ts
+++ b/packages/studio/src/player/hooks/useTimelinePlayer.test.ts
@@ -13,28 +13,9 @@ import {
shouldIgnorePlaybackShortcutTarget,
} from "./useTimelinePlayer";
-function mockTargetMatching(selectorNeedle: string): EventTarget {
- return {
- closest: (selector: string) => (selector.includes(selectorNeedle) ? ({} as Element) : null),
- } as unknown as EventTarget;
-}
-
-function mockKeyboardEvent(
- code: string,
- overrides: Partial<Pick<KeyboardEvent, "altKey" | "ctrlKey" | "metaKey" | "target">> = {},
-): Pick<KeyboardEvent, "altKey" | "ctrlKey" | "metaKey" | "code" | "target"> {
- return {
- altKey: false,
- ctrlKey: false,
- metaKey: false,
- code,
- target: mockTargetMatching("[data-missing]"),
- ...overrides,
- };
-}
-
function createDocument(markup: string): Document {
const window = new Window();
+ Object.assign(window, { SyntaxError });
window.document.body.innerHTML = markup;
return window.document;
}
@@ -42,7 +23,7 @@ function createDocument(markup: string): Document {
function createClip(overrides: Partial<ClipManifestClip>): ClipManifestClip {
return {
id: null,
- label: "Element",
+ label: "",
start: 0,
duration: 4,
track: 0,
@@ -56,6 +37,26 @@ function createClip(overrides: Partial<ClipManifestClip>): ClipManifestClip {
};
}
+function mockTargetMatching(selectorNeedle: string): EventTarget {
+ return {
+ closest: (selector: string) => (selector.includes(selectorNeedle) ? ({} as Element) : null),
+ } as unknown as EventTarget;
+}
+
+function mockKeyboardEvent(
+ code: string,
+ overrides: Partial<Pick<KeyboardEvent, "altKey" | "ctrlKey" | "metaKey" | "target">> = {},
+): Pick<KeyboardEvent, "altKey" | "ctrlKey" | "metaKey" | "code" | "target"> {
+ return {
+ altKey: false,
+ ctrlKey: false,
+ metaKey: false,
+ code,
+ target: mockTargetMatching("[data-missing]"),
+ ...overrides,
+ };
+}
+
describe("buildStandaloneRootTimelineElement", () => {
it("includes selector and source metadata for standalone composition fallback clips", () => {
expect(
diff --git a/packages/studio/src/player/hooks/useTimelinePlayer.ts b/packages/studio/src/player/hooks/useTimelinePlayer.ts
index aa4f0ea25e..daf20194b7 100644
--- a/packages/studio/src/player/hooks/useTimelinePlayer.ts
+++ b/packages/studio/src/player/hooks/useTimelinePlayer.ts
@@ -22,7 +22,7 @@ interface TimelineLike {
isActive: () => boolean;
}
-interface ClipManifestClip {
+export interface ClipManifestClip {
id: string | null;
label: string;
start: number;
@@ -335,7 +335,6 @@ function buildTimelineElementKey(params: {
if (params.selector) return `${scope}:${params.selector}:${params.selectorIndex ?? 0}`;
return `${scope}:${params.id}:${params.fallbackIndex}`;
}
-
function buildTimelineElementIdentity(params: {
preferredId?: string | null;
label: string;
@@ -557,7 +556,6 @@ export function buildStandaloneRootTimelineElement(params: {
sourceFile: compositionSrc,
};
}
-
function normalizePreviewViewport(doc: Document, win: Window): void {
if (doc.documentElement) {
doc.documentElement.style.overflow = "hidden";
@@ -1351,6 +1349,9 @@ export function useTimelinePlayer() {
setIsPlaying(false);
}, [getAdapter, stopRAFLoop, setIsPlaying, stopReverseLoop]);
+ const togglePlayRef = useRef(togglePlay);
+ togglePlayRef.current = togglePlay;
+
const refreshPlayer = useCallback(() => {
const iframe = iframeRef.current;
if (!iframe) return;
@@ -1459,8 +1460,6 @@ export function useTimelinePlayer() {
stopRAFLoop();
stopReverseLoop();
if (probeIntervalRef.current) clearInterval(probeIntervalRef.current);
- // Don't reset() on cleanup — preserve timeline elements across iframe refreshes
- // to prevent blink. New data will replace old when the iframe reloads.
};
});
diff --git a/packages/studio/src/utils/clipboard.test.ts b/packages/studio/src/utils/clipboard.test.ts
new file mode 100644
index 0000000000..c648e18fb1
--- /dev/null
+++ b/packages/studio/src/utils/clipboard.test.ts
@@ -0,0 +1,89 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { Window } from "happy-dom";
+import { copyTextToClipboard } from "./clipboard";
+
+function installDocument(execCommand: (command: string) => boolean): void {
+ const window = new Window();
+ Object.assign(window, { SyntaxError });
+ Object.defineProperty(window.document, "execCommand", {
+ configurable: true,
+ value: execCommand,
+ });
+ vi.stubGlobal("document", window.document);
+}
+
+function installNavigator(
+ writeText: (text: string) => Promise<void>,
+ userAgent = "Mozilla/5.0 Chrome/120.0.0.0 Safari/537.36",
+): void {
+ vi.stubGlobal("navigator", {
+ clipboard: { writeText },
+ userAgent,
+ });
+}
+
+describe("copyTextToClipboard", () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it("uses the synchronous selection copy path first in Safari", async () => {
+ const execCommand = vi.fn((command: string) => command === "copy");
+ const writeText = vi.fn((_text: string) => Promise.resolve());
+
+ installDocument(execCommand);
+ installNavigator(
+ writeText,
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Safari/605.1.15",
+ );
+
+ await expect(copyTextToClipboard("copy me")).resolves.toBe(true);
+
+ expect(execCommand).toHaveBeenCalledWith("copy");
+ expect(writeText).not.toHaveBeenCalled();
+ expect(document.querySelector("textarea")).toBeNull();
+ });
+
+ it("uses navigator.clipboard first outside Safari", async () => {
+ const execCommand = vi.fn((command: string) => command === "copy");
+ const writeText = vi.fn((_text: string) => Promise.resolve());
+
+ installDocument(execCommand);
+ installNavigator(writeText);
+
+ await expect(copyTextToClipboard("copy me")).resolves.toBe(true);
+
+ expect(writeText).toHaveBeenCalledWith("copy me");
+ expect(execCommand).not.toHaveBeenCalled();
+ });
+
+ it("falls back to selection copy outside Safari when navigator.clipboard fails", async () => {
+ const execCommand = vi.fn((command: string) => command === "copy");
+ const writeText = vi.fn((_text: string) => Promise.reject(new Error("blocked")));
+
+ installDocument(execCommand);
+ installNavigator(writeText);
+
+ await expect(copyTextToClipboard("copy me")).resolves.toBe(true);
+
+ expect(writeText).toHaveBeenCalledWith("copy me");
+ expect(execCommand).toHaveBeenCalledWith("copy");
+ });
+
+ it("reports failure when both copy paths fail", async () => {
+ const execCommand = vi.fn(() => false);
+ const writeText = vi.fn((_text: string) => Promise.reject(new Error("blocked")));
+
+ installDocument(execCommand);
+ installNavigator(
+ writeText,
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Safari/605.1.15",
+ );
+
+ await expect(copyTextToClipboard("copy me")).resolves.toBe(false);
+
+ expect(execCommand).toHaveBeenCalledWith("copy");
+ expect(writeText).toHaveBeenCalledWith("copy me");
+ expect(document.querySelector("textarea")).toBeNull();
+ });
+});
diff --git a/packages/studio/src/utils/clipboard.ts b/packages/studio/src/utils/clipboard.ts
new file mode 100644
index 0000000000..449603fd01
--- /dev/null
+++ b/packages/studio/src/utils/clipboard.ts
@@ -0,0 +1,57 @@
+function copyWithSelection(text: string): boolean {
+ if (typeof document === "undefined" || !document.body || !document.execCommand) {
+ return false;
+ }
+
+ const textarea = document.createElement("textarea");
+ textarea.value = text;
+ textarea.setAttribute("readonly", "true");
+ textarea.style.position = "fixed";
+ textarea.style.top = "0";
+ textarea.style.left = "0";
+ textarea.style.width = "1px";
+ textarea.style.height = "1px";
+ textarea.style.padding = "0";
+ textarea.style.border = "0";
+ textarea.style.opacity = "0";
+ textarea.style.pointerEvents = "none";
+
+ document.body.appendChild(textarea);
+ textarea.focus({ preventScroll: true });
+ textarea.select();
+ textarea.setSelectionRange(0, text.length);
+
+ try {
+ return document.execCommand("copy");
+ } catch {
+ return false;
+ } finally {
+ document.body.removeChild(textarea);
+ }
+}
+
+function shouldCopyWithSelectionFirst(): boolean {
+ if (typeof navigator === "undefined") return false;
+
+ const userAgent = navigator.userAgent;
+ return /Safari/i.test(userAgent) && !/Chrome|Chromium|CriOS|FxiOS|Edg|OPR/i.test(userAgent);
+}
+
+export async function copyTextToClipboard(text: string): Promise<boolean> {
+ const useSelectionFirst = shouldCopyWithSelectionFirst();
+ if (useSelectionFirst && copyWithSelection(text)) {
+ return true;
+ }
+
+ const clipboard = typeof navigator !== "undefined" ? navigator.clipboard : undefined;
+ if (clipboard?.writeText) {
+ try {
+ await clipboard.writeText(text);
+ return true;
+ } catch {
+ // Fall back below when the browser still allows synchronous copy.
+ }
+ }
+
+ return !useSelectionFirst && copyWithSelection(text);
+}
diff --git a/packages/studio/src/utils/editHistory.test.ts b/packages/studio/src/utils/editHistory.test.ts
new file mode 100644
index 0000000000..e4f2abc3ea
--- /dev/null
+++ b/packages/studio/src/utils/editHistory.test.ts
@@ -0,0 +1,244 @@
+import { describe, expect, it } from "vitest";
+import {
+ buildEditHistoryEntry,
+ canApplyEditHistoryEntry,
+ createEmptyEditHistory,
+ hashEditHistoryContent,
+ pushEditHistoryEntry,
+ redoEditHistory,
+ undoEditHistory,
+} from "./editHistory";
+
+describe("edit history", () => {
+ it("pushes changed file snapshots onto undo and clears redo", () => {
+ const state = createEmptyEditHistory();
+ const entry = buildEditHistoryEntry({
+ projectId: "project-1",
+ label: "Move layer",
+ files: {
+ "index.html": {
+ before: '<div style="left: 0px"></div>',
+ after: '<div style="left: 20px"></div>',
+ },
+ },
+ now: 100,
+ id: "entry-1",
+ });
+
+ const withUndo = pushEditHistoryEntry(state, entry);
+ const redoEntry = buildEditHistoryEntry({
+ projectId: "project-1",
+ label: "Redoable edit",
+ files: {
+ "index.html": {
+ before: '<div style="left: 20px"></div>',
+ after: '<div style="left: 40px"></div>',
+ },
+ },
+ now: 200,
+ id: "redo-entry",
+ });
+
+ const next = pushEditHistoryEntry(
+ {
+ ...withUndo,
+ redo: [redoEntry],
+ },
+ {
+ ...entry,
+ id: "entry-2",
+ label: "Resize layer",
+ createdAt: 300,
+ },
+ );
+
+ expect(withUndo.undo).toHaveLength(1);
+ expect(withUndo.redo).toHaveLength(0);
+ expect(next.undo.map((item) => item.label)).toEqual(["Move layer", "Resize layer"]);
+ expect(next.redo).toHaveLength(0);
+ });
+
+ it("undo returns before contents and moves entry to redo", () => {
+ const entry = buildEditHistoryEntry({
+ projectId: "project-1",
+ label: "Move layer",
+ files: {
+ "index.html": { before: "before", after: "after" },
+ },
+ now: 100,
+ id: "entry-1",
+ });
+ const state = pushEditHistoryEntry(createEmptyEditHistory(), entry);
+
+ const result = undoEditHistory(state, { "index.html": hashEditHistoryContent("after") }, 200);
+
+ expect(result.ok).toBe(true);
+ expect(result.filesToWrite).toEqual({ "index.html": "before" });
+ expect(result.state.undo).toHaveLength(0);
+ expect(result.state.redo.map((item) => item.id)).toEqual(["entry-1"]);
+ });
+
+ it("redo returns after contents and moves entry to undo", () => {
+ const entry = buildEditHistoryEntry({
+ projectId: "project-1",
+ label: "Move layer",
+ files: {
+ "index.html": { before: "before", after: "after" },
+ },
+ now: 100,
+ id: "entry-1",
+ });
+ const undone = undoEditHistory(
+ pushEditHistoryEntry(createEmptyEditHistory(), entry),
+ { "index.html": hashEditHistoryContent("after") },
+ 200,
+ ).state;
+
+ const result = redoEditHistory(undone, { "index.html": hashEditHistoryContent("before") }, 300);
+
+ expect(result.ok).toBe(true);
+ expect(result.filesToWrite).toEqual({ "index.html": "after" });
+ expect(result.state.undo.map((item) => item.id)).toEqual(["entry-1"]);
+ expect(result.state.redo).toHaveLength(0);
+ });
+
+ it("blocks undo when current content hash does not match the recorded after hash", () => {
+ const entry = buildEditHistoryEntry({
+ projectId: "project-1",
+ label: "Move layer",
+ files: {
+ "index.html": { before: "before", after: "after" },
+ },
+ now: 100,
+ id: "entry-1",
+ });
+ const state = pushEditHistoryEntry(createEmptyEditHistory(), entry);
+
+ const result = undoEditHistory(
+ state,
+ { "index.html": hashEditHistoryContent("external") },
+ 200,
+ );
+
+ expect(result.ok).toBe(false);
+ expect(result.reason).toBe("content-mismatch");
+ expect(result.state).toBe(state);
+ expect(result.filesToWrite).toEqual({});
+ });
+
+ it("can validate all files in a multi-file entry before applying", () => {
+ const entry = buildEditHistoryEntry({
+ projectId: "project-1",
+ label: "Update files",
+ files: {
+ "index.html": { before: "a", after: "b" },
+ "compositions/title.html": { before: "c", after: "d" },
+ },
+ now: 100,
+ id: "entry-1",
+ });
+
+ expect(
+ canApplyEditHistoryEntry(entry, "undo", {
+ "index.html": hashEditHistoryContent("b"),
+ "compositions/title.html": hashEditHistoryContent("d"),
+ }),
+ ).toEqual({ ok: true });
+ expect(
+ canApplyEditHistoryEntry(entry, "undo", {
+ "index.html": hashEditHistoryContent("b"),
+ "compositions/title.html": hashEditHistoryContent("external"),
+ }),
+ ).toEqual({ ok: false, reason: "content-mismatch", path: "compositions/title.html" });
+ });
+
+ it("prunes oldest undo entries when the limit is exceeded", () => {
+ let state = createEmptyEditHistory({ maxEntries: 2 });
+ for (let index = 1; index <= 3; index += 1) {
+ state = pushEditHistoryEntry(
+ state,
+ buildEditHistoryEntry({
+ projectId: "project-1",
+ label: `Edit ${index}`,
+ files: {
+ "index.html": { before: `${index - 1}`, after: `${index}` },
+ },
+ now: index,
+ id: `entry-${index}`,
+ }),
+ { maxEntries: 2 },
+ );
+ }
+
+ expect(state.undo.map((entry) => entry.id)).toEqual(["entry-2", "entry-3"]);
+ });
+
+ it("coalesces source editor edits for the same file inside the coalesce window", () => {
+ const first = buildEditHistoryEntry({
+ projectId: "project-1",
+ label: "Edit source",
+ kind: "source",
+ coalesceKey: "source:index.html",
+ files: {
+ "index.html": { before: "a", after: "b" },
+ },
+ now: 100,
+ id: "entry-1",
+ });
+ const second = buildEditHistoryEntry({
+ projectId: "project-1",
+ label: "Edit source",
+ kind: "source",
+ coalesceKey: "source:index.html",
+ files: {
+ "index.html": { before: "b", after: "c" },
+ },
+ now: 300,
+ id: "entry-2",
+ });
+
+ const state = pushEditHistoryEntry(
+ pushEditHistoryEntry(createEmptyEditHistory(), first),
+ second,
+ { coalesceMs: 1000 },
+ );
+
+ expect(state.undo).toHaveLength(1);
+ expect(state.undo[0].id).toBe("entry-2");
+ expect(state.undo[0].files["index.html"].before).toBe("a");
+ expect(state.undo[0].files["index.html"].after).toBe("c");
+ });
+
+ it("does not coalesce source editor edits outside the coalesce window", () => {
+ const first = buildEditHistoryEntry({
+ projectId: "project-1",
+ label: "Edit source",
+ kind: "source",
+ coalesceKey: "source:index.html",
+ files: {
+ "index.html": { before: "a", after: "b" },
+ },
+ now: 100,
+ id: "entry-1",
+ });
+ const second = buildEditHistoryEntry({
+ projectId: "project-1",
+ label: "Edit source",
+ kind: "source",
+ coalesceKey: "source:index.html",
+ files: {
+ "index.html": { before: "b", after: "c" },
+ },
+ now: 5000,
+ id: "entry-2",
+ });
+
+ const state = pushEditHistoryEntry(
+ pushEditHistoryEntry(createEmptyEditHistory(), first),
+ second,
+ { coalesceMs: 1000 },
+ );
+
+ expect(state.undo.map((entry) => entry.id)).toEqual(["entry-1", "entry-2"]);
+ });
+});
diff --git a/packages/studio/src/utils/editHistory.ts b/packages/studio/src/utils/editHistory.ts
new file mode 100644
index 0000000000..b443bffb5d
--- /dev/null
+++ b/packages/studio/src/utils/editHistory.ts
@@ -0,0 +1,218 @@
+export type EditHistoryKind = "manual" | "timeline" | "source";
+
+export interface EditHistoryFileSnapshot {
+ before: string;
+ after: string;
+ beforeHash: string;
+ afterHash: string;
+}
+
+export interface EditHistoryEntry {
+ id: string;
+ projectId: string;
+ label: string;
+ kind: EditHistoryKind;
+ coalesceKey?: string;
+ createdAt: number;
+ files: Record<string, EditHistoryFileSnapshot>;
+}
+
+export interface EditHistoryState {
+ version: 1;
+ updatedAt: number;
+ undo: EditHistoryEntry[];
+ redo: EditHistoryEntry[];
+}
+
+export interface EditHistoryOptions {
+ maxEntries?: number;
+ coalesceMs?: number;
+}
+
+export interface BuildEditHistoryEntryInput {
+ id: string;
+ projectId: string;
+ label: string;
+ kind?: EditHistoryKind;
+ coalesceKey?: string;
+ now: number;
+ files: Record<string, { before: string; after: string }>;
+}
+
+export type EditHistoryDirection = "undo" | "redo";
+
+export type EditHistoryApplyCheck =
+ | { ok: true }
+ | { ok: false; reason: "content-mismatch"; path: string };
+
+export type EditHistoryTransitionResult =
+ | {
+ ok: true;
+ state: EditHistoryState;
+ entry: EditHistoryEntry;
+ filesToWrite: Record<string, string>;
+ }
+ | {
+ ok: false;
+ reason: "empty" | "content-mismatch";
+ state: EditHistoryState;
+ filesToWrite: Record<string, string>;
+ path?: string;
+ };
+
+const DEFAULT_MAX_ENTRIES = 100;
+const DEFAULT_COALESCE_MS = 1500;
+
+export function hashEditHistoryContent(content: string): string {
+ let hash = 2166136261;
+ for (let index = 0; index < content.length; index += 1) {
+ hash ^= content.charCodeAt(index);
+ hash = Math.imul(hash, 16777619);
+ }
+ return (hash >>> 0).toString(16).padStart(8, "0");
+}
+
+export function createEmptyEditHistory(_options?: EditHistoryOptions): EditHistoryState {
+ return {
+ version: 1,
+ updatedAt: 0,
+ undo: [],
+ redo: [],
+ };
+}
+
+export function buildEditHistoryEntry(input: BuildEditHistoryEntryInput): EditHistoryEntry {
+ const files: Record<string, EditHistoryFileSnapshot> = {};
+ for (const [path, snapshot] of Object.entries(input.files)) {
+ if (snapshot.before === snapshot.after) continue;
+ files[path] = {
+ before: snapshot.before,
+ after: snapshot.after,
+ beforeHash: hashEditHistoryContent(snapshot.before),
+ afterHash: hashEditHistoryContent(snapshot.after),
+ };
+ }
+
+ return {
+ id: input.id,
+ projectId: input.projectId,
+ label: input.label,
+ kind: input.kind ?? "manual",
+ coalesceKey: input.coalesceKey,
+ createdAt: input.now,
+ files,
+ };
+}
+
+export function pushEditHistoryEntry(
+ state: EditHistoryState,
+ entry: EditHistoryEntry,
+ options?: EditHistoryOptions,
+): EditHistoryState {
+ if (Object.keys(entry.files).length === 0) return state;
+
+ const coalesceMs = options?.coalesceMs ?? DEFAULT_COALESCE_MS;
+ const maxEntries = options?.maxEntries ?? DEFAULT_MAX_ENTRIES;
+ const previous = state.undo[state.undo.length - 1];
+ let undo = state.undo;
+
+ if (
+ previous &&
+ previous.coalesceKey &&
+ previous.coalesceKey === entry.coalesceKey &&
+ entry.createdAt - previous.createdAt <= coalesceMs
+ ) {
+ const files: Record<string, EditHistoryFileSnapshot> = {};
+ for (const [path, snapshot] of Object.entries(entry.files)) {
+ const previousSnapshot = previous.files[path];
+ files[path] = previousSnapshot
+ ? {
+ before: previousSnapshot.before,
+ after: snapshot.after,
+ beforeHash: previousSnapshot.beforeHash,
+ afterHash: snapshot.afterHash,
+ }
+ : snapshot;
+ }
+ undo = [...state.undo.slice(0, -1), { ...entry, files }];
+ } else {
+ undo = [...state.undo, entry];
+ }
+
+ return {
+ version: 1,
+ updatedAt: entry.createdAt,
+ undo: undo.slice(Math.max(0, undo.length - maxEntries)),
+ redo: [],
+ };
+}
+
+export function canApplyEditHistoryEntry(
+ entry: EditHistoryEntry,
+ direction: EditHistoryDirection,
+ currentHashes: Record<string, string>,
+): EditHistoryApplyCheck {
+ for (const [path, snapshot] of Object.entries(entry.files)) {
+ const expected = direction === "undo" ? snapshot.afterHash : snapshot.beforeHash;
+ if (currentHashes[path] !== expected) {
+ return { ok: false, reason: "content-mismatch", path };
+ }
+ }
+ return { ok: true };
+}
+
+export function undoEditHistory(
+ state: EditHistoryState,
+ currentHashes: Record<string, string>,
+ now: number,
+): EditHistoryTransitionResult {
+ const entry = state.undo[state.undo.length - 1];
+ if (!entry) return { ok: false, reason: "empty", state, filesToWrite: {} };
+
+ const check = canApplyEditHistoryEntry(entry, "undo", currentHashes);
+ if (!check.ok) {
+ return { ok: false, reason: check.reason, path: check.path, state, filesToWrite: {} };
+ }
+
+ return {
+ ok: true,
+ entry,
+ filesToWrite: Object.fromEntries(
+ Object.entries(entry.files).map(([path, snapshot]) => [path, snapshot.before]),
+ ),
+ state: {
+ version: 1,
+ updatedAt: now,
+ undo: state.undo.slice(0, -1),
+ redo: [...state.redo, entry],
+ },
+ };
+}
+
+export function redoEditHistory(
+ state: EditHistoryState,
+ currentHashes: Record<string, string>,
+ now: number,
+): EditHistoryTransitionResult {
+ const entry = state.redo[state.redo.length - 1];
+ if (!entry) return { ok: false, reason: "empty", state, filesToWrite: {} };
+
+ const check = canApplyEditHistoryEntry(entry, "redo", currentHashes);
+ if (!check.ok) {
+ return { ok: false, reason: check.reason, path: check.path, state, filesToWrite: {} };
+ }
+
+ return {
+ ok: true,
+ entry,
+ filesToWrite: Object.fromEntries(
+ Object.entries(entry.files).map(([path, snapshot]) => [path, snapshot.after]),
+ ),
+ state: {
+ version: 1,
+ updatedAt: now,
+ undo: [...state.undo, entry],
+ redo: state.redo.slice(0, -1),
+ },
+ };
+}
diff --git a/packages/studio/src/utils/editHistoryStorage.test.ts b/packages/studio/src/utils/editHistoryStorage.test.ts
new file mode 100644
index 0000000000..be5e3a6f98
--- /dev/null
+++ b/packages/studio/src/utils/editHistoryStorage.test.ts
@@ -0,0 +1,37 @@
+import { beforeEach, describe, expect, it } from "vitest";
+import { buildEditHistoryEntry, createEmptyEditHistory, pushEditHistoryEntry } from "./editHistory";
+import {
+ createMemoryEditHistoryStorage,
+ loadEditHistoryState,
+ saveEditHistoryState,
+} from "./editHistoryStorage";
+
+describe("edit history storage", () => {
+ let storage: ReturnType<typeof createMemoryEditHistoryStorage>;
+
+ beforeEach(() => {
+ storage = createMemoryEditHistoryStorage();
+ });
+
+ it("returns empty history for projects without persisted state", async () => {
+ const state = await loadEditHistoryState(storage, "project-1");
+
+ expect(state).toEqual(createEmptyEditHistory());
+ });
+
+ it("saves and loads history per project", async () => {
+ const entry = buildEditHistoryEntry({
+ id: "entry-1",
+ projectId: "project-1",
+ label: "Move layer",
+ files: { "index.html": { before: "a", after: "b" } },
+ now: 100,
+ });
+ const state = pushEditHistoryEntry(createEmptyEditHistory(), entry);
+
+ await saveEditHistoryState(storage, "project-1", state);
+
+ expect(await loadEditHistoryState(storage, "project-1")).toEqual(state);
+ expect(await loadEditHistoryState(storage, "project-2")).toEqual(createEmptyEditHistory());
+ });
+});
diff --git a/packages/studio/src/utils/editHistoryStorage.ts b/packages/studio/src/utils/editHistoryStorage.ts
new file mode 100644
index 0000000000..1266c9a8dd
--- /dev/null
+++ b/packages/studio/src/utils/editHistoryStorage.ts
@@ -0,0 +1,99 @@
+import { createEmptyEditHistory, type EditHistoryState } from "./editHistory";
+
+export interface EditHistoryStorageAdapter {
+ get(projectId: string): Promise<EditHistoryState | null>;
+ set(projectId: string, state: EditHistoryState): Promise<void>;
+ delete(projectId: string): Promise<void>;
+}
+
+const DB_NAME = "hyperframes-studio-edit-history";
+const DB_VERSION = 1;
+const STORE_NAME = "project-history";
+
+export function createMemoryEditHistoryStorage(): EditHistoryStorageAdapter {
+ const states = new Map<string, EditHistoryState>();
+ return {
+ async get(projectId) {
+ return states.get(projectId) ?? null;
+ },
+ async set(projectId, state) {
+ states.set(projectId, structuredClone(state));
+ },
+ async delete(projectId) {
+ states.delete(projectId);
+ },
+ };
+}
+
+function openEditHistoryDb(): Promise<IDBDatabase> {
+ return new Promise((resolve, reject) => {
+ if (!globalThis.indexedDB) {
+ reject(new Error("IndexedDB is not available"));
+ return;
+ }
+
+ const request = globalThis.indexedDB.open(DB_NAME, DB_VERSION);
+ request.onupgradeneeded = () => {
+ const db = request.result;
+ if (!db.objectStoreNames.contains(STORE_NAME)) {
+ db.createObjectStore(STORE_NAME);
+ }
+ };
+ request.onerror = () => reject(request.error ?? new Error("Failed to open edit history db"));
+ request.onsuccess = () => resolve(request.result);
+ });
+}
+
+function withStore<T>(
+ mode: IDBTransactionMode,
+ callback: (store: IDBObjectStore) => IDBRequest<T>,
+): Promise<T> {
+ return openEditHistoryDb().then(
+ (db) =>
+ new Promise<T>((resolve, reject) => {
+ const tx = db.transaction(STORE_NAME, mode);
+ const request = callback(tx.objectStore(STORE_NAME));
+ request.onerror = () => reject(request.error ?? new Error("IndexedDB request failed"));
+ request.onsuccess = () => resolve(request.result);
+ tx.oncomplete = () => db.close();
+ tx.onerror = () => {
+ db.close();
+ reject(tx.error ?? new Error("IndexedDB transaction failed"));
+ };
+ }),
+ );
+}
+
+export function createIndexedDbEditHistoryStorage(): EditHistoryStorageAdapter {
+ return {
+ async get(projectId) {
+ return (
+ (await withStore<EditHistoryState | undefined>("readonly", (store) =>
+ store.get(projectId),
+ )) ?? null
+ );
+ },
+ async set(projectId, state) {
+ await withStore<IDBValidKey>("readwrite", (store) => store.put(state, projectId));
+ },
+ async delete(projectId) {
+ await withStore<undefined>("readwrite", (store) => store.delete(projectId));
+ },
+ };
+}
+
+export async function loadEditHistoryState(
+ storage: EditHistoryStorageAdapter,
+ projectId: string,
+): Promise<EditHistoryState> {
+ const state = await storage.get(projectId);
+ return state ?? createEmptyEditHistory();
+}
+
+export async function saveEditHistoryState(
+ storage: EditHistoryStorageAdapter,
+ projectId: string,
+ state: EditHistoryState,
+): Promise<void> {
+ await storage.set(projectId, state);
+}
diff --git a/packages/studio/src/utils/mediaTypes.ts b/packages/studio/src/utils/mediaTypes.ts
index ebc41540da..844fe88ed6 100644
--- a/packages/studio/src/utils/mediaTypes.ts
+++ b/packages/studio/src/utils/mediaTypes.ts
@@ -1,7 +1,7 @@
export const IMAGE_EXT = /\.(jpg|jpeg|png|gif|webp|svg|ico)$/i;
export const VIDEO_EXT = /\.(mp4|webm|mov)$/i;
export const AUDIO_EXT = /\.(mp3|wav|ogg|m4a|aac)$/i;
-export const FONT_EXT = /\.(woff|woff2|ttf|otf|eot)$/i;
+export const FONT_EXT = /\.(woff|woff2|ttf|ttc|otf|eot)$/i;
export const MEDIA_EXT = /\.(mp4|webm|mov|mp3|wav|ogg|m4a|aac|jpg|jpeg|png|gif|webp|svg|ico)$/i;
export function isMediaFile(path: string): boolean {
diff --git a/packages/studio/src/utils/sourcePatcher.test.ts b/packages/studio/src/utils/sourcePatcher.test.ts
index 9f5c25f571..0ae73e097f 100644
--- a/packages/studio/src/utils/sourcePatcher.test.ts
+++ b/packages/studio/src/utils/sourcePatcher.test.ts
@@ -1,5 +1,11 @@
import { describe, expect, it } from "vitest";
-import { applyPatchByTarget, readAttributeByTarget, type PatchOperation } from "./sourcePatcher";
+import {
+ applyPatch,
+ applyPatchByTarget,
+ readAttributeByTarget,
+ readTagSnippetByTarget,
+ type PatchOperation,
+} from "./sourcePatcher";
describe("applyPatchByTarget", () => {
it("updates a composition host by data-composition-id selector", () => {
@@ -29,6 +35,64 @@ describe("applyPatchByTarget", () => {
);
});
+ it("patches inline move styles by target", () => {
+ const html = `<div id="card" style="position: absolute; left: 108px; top: 112px"></div>`;
+
+ const withLeft = applyPatchByTarget(
+ html,
+ { id: "card" },
+ { type: "inline-style", property: "left", value: "160px" },
+ );
+ const withTop = applyPatchByTarget(
+ withLeft,
+ { id: "card" },
+ { type: "inline-style", property: "top", value: "140px" },
+ );
+
+ expect(withTop).toContain('style="position: absolute; left: 160px; top: 140px"');
+ });
+
+ it("patches inline resize styles by target", () => {
+ const html = `<div id="card" style="position: absolute; width: 380px; height: 196px"></div>`;
+
+ const withWidth = applyPatchByTarget(
+ html,
+ { id: "card" },
+ { type: "inline-style", property: "width", value: "420px" },
+ );
+ const withHeight = applyPatchByTarget(
+ withWidth,
+ { id: "card" },
+ { type: "inline-style", property: "height", value: "220px" },
+ );
+
+ expect(withHeight).toContain('style="position: absolute; width: 420px; height: 220px"');
+ });
+
+ it("escapes quoted CSS urls inside double-quoted style attributes", () => {
+ const html = `<div id="card" style="position: absolute; opacity: 1"></div>`;
+
+ const withBackground = applyPatchByTarget(
+ html,
+ { id: "card" },
+ {
+ type: "inline-style",
+ property: "background-image",
+ value: `url("../ChatGPT Image Apr 22, 2026.png")`,
+ },
+ );
+ const withRadius = applyPatchByTarget(
+ withBackground,
+ { id: "card" },
+ { type: "inline-style", property: "border-radius", value: "12px" },
+ );
+
+ expect(withRadius).toContain(
+ "background-image: url(&quot;../ChatGPT Image Apr 22, 2026.png&quot;)",
+ );
+ expect(withRadius).toContain("border-radius: 12px");
+ });
+
it("updates media timing attributes by selector", () => {
const html = `<video class="hero clip" data-start="0.2" data-duration="1.4" data-media-start="0.4"></video>`;
@@ -62,6 +126,69 @@ describe("applyPatchByTarget", () => {
expect(readAttributeByTarget(html, { selector: ".hero" }, "duration")).toBe("1.4");
});
+ it("reads the matched tag snippet by target", () => {
+ const html = `<section id="hero" class="card clip" style="left: 120px; top: 180px"></section>`;
+
+ expect(readTagSnippetByTarget(html, { id: "hero" })).toBe(
+ `<section id="hero" class="card clip" style="left: 120px; top: 180px"`,
+ );
+ });
+
+ it("patches and reads single-quoted attributes and styles", () => {
+ const html =
+ "<section id='hero' class='card clip' data-start='0.2' style='left: 120px; top: 180px'></section>";
+
+ const moved = applyPatchByTarget(
+ html,
+ { id: "hero" },
+ { type: "inline-style", property: "left", value: "160px" },
+ );
+ const updated = applyPatchByTarget(
+ moved,
+ { id: "hero" },
+ { type: "attribute", property: "start", value: "0.4" },
+ );
+
+ expect(updated).toContain(`style='left: 160px; top: 180px'`);
+ expect(updated).toContain(`data-start="0.4"`);
+ expect(readAttributeByTarget(updated, { id: "hero" }, "start")).toBe("0.4");
+ });
+
+ it("replaces the full text body of a nested element by id", () => {
+ const html =
+ '<div id="panel"><strong>Headline</strong><span>Supporting copy</span></div><p>Outside</p>';
+
+ const patched = applyPatch(html, "panel", {
+ type: "text-content",
+ property: "text",
+ value: "<strong>New headline</strong><span>New supporting copy</span>",
+ });
+
+ expect(patched).toContain(
+ '<div id="panel"><strong>New headline</strong><span>New supporting copy</span></div>',
+ );
+ expect(patched).toContain("<p>Outside</p>");
+ });
+
+ it("does not stop at the first child closing tag when patching nested text", () => {
+ const html =
+ '<section id="card"><div><strong>Headline</strong></div><div>Copy</div></section><p>Outside</p>';
+
+ const patched = applyPatchByTarget(
+ html,
+ { id: "card" },
+ {
+ type: "text-content",
+ property: "text",
+ value: "<strong>New headline</strong>",
+ },
+ );
+
+ expect(patched).toBe(
+ '<section id="card"><strong>New headline</strong></section><p>Outside</p>',
+ );
+ });
+
it("patches the correct duplicate selector occurrence", () => {
const html = [
`<div class="headline clip" data-start="0"></div>`,
diff --git a/packages/studio/src/utils/sourcePatcher.ts b/packages/studio/src/utils/sourcePatcher.ts
index 921cb5b644..3d8e728258 100644
--- a/packages/studio/src/utils/sourcePatcher.ts
+++ b/packages/studio/src/utils/sourcePatcher.ts
@@ -7,6 +7,67 @@ function escapeRegex(s: string): string {
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
+function escapeStyleAttributeValue(value: string, quote: string): string {
+ return quote === '"' ? value.replace(/"/g, "&quot;") : value.replace(/'/g, "&#39;");
+}
+
+function splitInlineStyleDeclarations(style: string): string[] {
+ const declarations: string[] = [];
+ let current = "";
+ let quote: string | null = null;
+ let entity = false;
+ let parenDepth = 0;
+
+ for (const char of style) {
+ if (entity) {
+ current += char;
+ if (char === ";") entity = false;
+ continue;
+ }
+
+ if (char === "&") {
+ entity = true;
+ current += char;
+ continue;
+ }
+
+ if (quote) {
+ current += char;
+ if (char === quote) quote = null;
+ continue;
+ }
+
+ if (char === '"' || char === "'") {
+ quote = char;
+ current += char;
+ continue;
+ }
+
+ if (char === "(") {
+ parenDepth += 1;
+ current += char;
+ continue;
+ }
+
+ if (char === ")") {
+ parenDepth = Math.max(0, parenDepth - 1);
+ current += char;
+ continue;
+ }
+
+ if (char === ";" && parenDepth === 0) {
+ declarations.push(current);
+ current = "";
+ continue;
+ }
+
+ current += char;
+ }
+
+ if (current) declarations.push(current);
+ return declarations;
+}
+
export interface PatchOperation {
type: "inline-style" | "attribute" | "text-content";
property: string;
@@ -74,7 +135,7 @@ export function resolveSourceFile(
*/
function patchInlineStyle(html: string, elementId: string, prop: string, value: string): string {
// Find the element tag with this id
- const idPattern = new RegExp(`(<[^>]*\\bid="${escapeRegex(elementId)}"[^>]*)>`, "i");
+ const idPattern = new RegExp(`(<[^>]*\\bid=(["'])${escapeRegex(elementId)}\\2[^>]*)>`, "i");
const match = idPattern.exec(html);
if (!match) return html;
@@ -86,12 +147,13 @@ function patchInlineStyleInTag(html: string, tag: string, prop: string, value: s
if (!tag) return html;
// Check if there's an existing style attribute
- const styleMatch = /\bstyle="([^"]*)"/.exec(tag);
+ const styleMatch = /\bstyle=(["'])([\s\S]*?)\1/.exec(tag);
if (styleMatch) {
- const existingStyle = styleMatch[1];
+ const existingStyle = styleMatch[2];
+ const quote = styleMatch[1];
// Parse existing properties
const props = new Map<string, string>();
- for (const part of existingStyle.split(";")) {
+ for (const part of splitInlineStyleDeclarations(existingStyle)) {
const colon = part.indexOf(":");
if (colon < 0) continue;
const key = part.slice(0, colon).trim();
@@ -102,13 +164,14 @@ function patchInlineStyleInTag(html: string, tag: string, prop: string, value: s
props.set(prop, value);
// Rebuild style string
const newStyle = Array.from(props.entries())
- .map(([k, v]) => `${k}: ${v}`)
+ .map(([k, v]) => `${k}: ${escapeStyleAttributeValue(v, quote)}`)
.join("; ");
- const newTag = tag.replace(/\bstyle="[^"]*"/, `style="${newStyle}"`);
+ const newTag = tag.replace(styleMatch[0], `style=${quote}${newStyle}${quote}`);
return html.replace(tag, newTag);
} else {
// No existing style — add one
- const newTag = tag.replace(/>$/, "") + ` style="${prop}: ${value}"`;
+ const newTag =
+ tag.replace(/>$/, "") + ` style="${prop}: ${escapeStyleAttributeValue(value, '"')}"`;
return html.replace(tag, newTag);
}
}
@@ -137,7 +200,7 @@ function replaceTagAtMatch(html: string, match: TagMatch, newTag: string): strin
function findTagByTarget(html: string, target: PatchTarget): TagMatch | null {
if (target.id) {
- const idPattern = new RegExp(`(<[^>]*\\bid="${escapeRegex(target.id)}"[^>]*)>`, "i");
+ const idPattern = new RegExp(`(<[^>]*\\bid=(["'])${escapeRegex(target.id)}\\2[^>]*)>`, "i");
const match = idPattern.exec(html);
if (match?.index != null) {
return {
@@ -154,7 +217,7 @@ function findTagByTarget(html: string, target: PatchTarget): TagMatch | null {
if (compositionIdMatch) {
const compId = compositionIdMatch[1];
const pattern = new RegExp(
- `(<[^>]*\\bdata-composition-id="${escapeRegex(compId)}"[^>]*)>`,
+ `(<[^>]*\\bdata-composition-id=(["'])${escapeRegex(compId)}\\2[^>]*)>`,
"i",
);
const match = pattern.exec(html);
@@ -201,8 +264,13 @@ export function readAttributeByTarget(
if (!match) return undefined;
const fullAttr = attr.startsWith("data-") ? attr : `data-${attr}`;
- const valueMatch = new RegExp(`\\b${fullAttr}="([^"]*)"`).exec(match.tag);
- return valueMatch?.[1];
+ const valueMatch = new RegExp(`\\b${fullAttr}=(["'])([^"']*)\\1`).exec(match.tag);
+ return valueMatch?.[2];
+}
+
+export function readTagSnippetByTarget(html: string, target: PatchTarget): string | undefined {
+ const match = findTagByTarget(html, target);
+ return match?.tag;
}
function patchAttributeByTarget(
@@ -215,7 +283,7 @@ function patchAttributeByTarget(
if (!match) return html;
const fullAttr = attr.startsWith("data-") ? attr : `data-${attr}`;
- const attrPattern = new RegExp(`\\b${fullAttr}="[^"]*"`);
+ const attrPattern = new RegExp(`\\b${fullAttr}=(["'])([^"']*)\\1`);
const tag = match.tag;
if (attrPattern.test(tag)) {
@@ -231,13 +299,13 @@ function patchAttributeByTarget(
* Apply an attribute change to an element in the HTML source.
*/
function patchAttribute(html: string, elementId: string, attr: string, value: string): string {
- const idPattern = new RegExp(`(<[^>]*\\bid="${escapeRegex(elementId)}"[^>]*)>`, "i");
+ const idPattern = new RegExp(`(<[^>]*\\bid=(["'])${escapeRegex(elementId)}\\2[^>]*)>`, "i");
const match = idPattern.exec(html);
if (!match) return html;
const tag = match[1];
const fullAttr = attr.startsWith("data-") ? attr : `data-${attr}`;
- const attrPattern = new RegExp(`\\b${fullAttr}="[^"]*"`);
+ const attrPattern = new RegExp(`\\b${fullAttr}=(["'])([^"']*)\\1`);
if (attrPattern.test(tag)) {
// Update existing attribute
@@ -254,11 +322,53 @@ function patchAttribute(html: string, elementId: string, attr: string, value: st
* Apply a text content change to an element.
*/
function patchTextContent(html: string, elementId: string, value: string): string {
- // Match the element and its content: <tagname id="elementId"...>content</tagname>
- const pattern = new RegExp(`(<[^>]*\\bid="${elementId}"[^>]*>)([\\s\\S]*?)(<\\/[a-z]+>)`, "i");
- const match = pattern.exec(html);
+ const openTagPattern = new RegExp(
+ `(<([a-z0-9-]+)[^>]*\\bid=(["'])${escapeRegex(elementId)}\\3[^>]*>)`,
+ "i",
+ );
+ const match = openTagPattern.exec(html);
+ if (!match || match.index == null) return html;
+
+ const openingTag = match[1];
+ const tagName = match[2];
+ const contentStart = match.index + openingTag.length;
+ const closingIndex = findMatchingClosingTagIndex(html, tagName, contentStart);
+ if (closingIndex < 0) return html;
+
+ return `${html.slice(0, contentStart)}${value}${html.slice(closingIndex)}`;
+}
+
+function findMatchingClosingTagIndex(html: string, tagName: string, contentStart: number): number {
+ const tagPattern = new RegExp(`</?${escapeRegex(tagName)}\\b[^>]*>`, "gi");
+ tagPattern.lastIndex = contentStart;
+ let depth = 1;
+ let match: RegExpExecArray | null;
+
+ while ((match = tagPattern.exec(html)) !== null) {
+ const tag = match[0];
+ if (tag.startsWith("</")) {
+ depth -= 1;
+ if (depth === 0) return match.index;
+ continue;
+ }
+ if (!tag.endsWith("/>")) depth += 1;
+ }
+
+ return -1;
+}
+
+function patchTextContentByTarget(html: string, target: PatchTarget, value: string): string {
+ const match = findTagByTarget(html, target);
if (!match) return html;
- return html.replace(pattern, `${match[1]}${value}${match[3]}`);
+
+ const tagNameMatch = /^<([a-z0-9-]+)/i.exec(match.tag);
+ const tagName = tagNameMatch?.[1];
+ if (!tagName) return html;
+
+ const closingIndex = findMatchingClosingTagIndex(html, tagName, match.end + 1);
+ if (closingIndex < 0) return html;
+
+ return `${html.slice(0, match.end + 1)}${value}${html.slice(closingIndex)}`;
}
/**
@@ -290,6 +400,8 @@ export function applyPatchByTarget(html: string, target: PatchTarget, op: PatchO
return patchInlineStyleByTarget(html, target, op.property, op.value);
case "attribute":
return patchAttributeByTarget(html, target, op.property, op.value);
+ case "text-content":
+ return patchTextContentByTarget(html, target, op.value);
default:
return html;
}
diff --git a/packages/studio/src/utils/studioFileHistory.test.ts b/packages/studio/src/utils/studioFileHistory.test.ts
new file mode 100644
index 0000000000..375843e800
--- /dev/null
+++ b/packages/studio/src/utils/studioFileHistory.test.ts
@@ -0,0 +1,156 @@
+import { describe, expect, it, vi } from "vitest";
+import { saveProjectFilesWithHistory } from "./studioFileHistory";
+
+describe("saveProjectFilesWithHistory", () => {
+ it("reads before content, writes after content, and records a history entry", async () => {
+ const reads: Record<string, string> = { "index.html": "before" };
+ const writes: Record<string, string> = {};
+ const recordEdit = vi.fn();
+
+ await saveProjectFilesWithHistory({
+ projectId: "project-1",
+ label: "Move layer",
+ kind: "manual",
+ files: { "index.html": "after" },
+ readFile: async (path) => reads[path],
+ writeFile: async (path, content) => {
+ writes[path] = content;
+ },
+ recordEdit,
+ });
+
+ expect(writes).toEqual({ "index.html": "after" });
+ expect(recordEdit).toHaveBeenCalledWith({
+ label: "Move layer",
+ kind: "manual",
+ coalesceKey: undefined,
+ files: { "index.html": { before: "before", after: "after" } },
+ });
+ });
+
+ it("skips writes and history for unchanged content", async () => {
+ const writeFile = vi.fn();
+ const recordEdit = vi.fn();
+
+ const changedPaths = await saveProjectFilesWithHistory({
+ projectId: "project-1",
+ label: "Edit layer",
+ kind: "manual",
+ files: { "index.html": "same" },
+ readFile: async () => "same",
+ writeFile,
+ recordEdit,
+ });
+
+ expect(changedPaths).toEqual([]);
+ expect(writeFile).not.toHaveBeenCalled();
+ expect(recordEdit).not.toHaveBeenCalled();
+ });
+
+ it("rolls back files already written when a later file write fails", async () => {
+ const reads: Record<string, string> = {
+ "index.html": "index-before",
+ "scene.html": "scene-before",
+ };
+ const writes: Array<[string, string]> = [];
+ const recordEdit = vi.fn();
+
+ await expect(
+ saveProjectFilesWithHistory({
+ projectId: "project-1",
+ label: "Move layer",
+ kind: "manual",
+ files: {
+ "index.html": "index-after",
+ "scene.html": "scene-after",
+ },
+ readFile: async (path) => reads[path],
+ writeFile: async (path, content) => {
+ writes.push([path, content]);
+ if (path === "scene.html") {
+ throw new Error("disk full");
+ }
+ },
+ recordEdit,
+ }),
+ ).rejects.toThrow("disk full");
+
+ expect(writes).toEqual([
+ ["index.html", "index-after"],
+ ["scene.html", "scene-after"],
+ ["index.html", "index-before"],
+ ]);
+ expect(recordEdit).not.toHaveBeenCalled();
+ });
+
+ it("rolls back written files when the injected history recorder throws", async () => {
+ const reads: Record<string, string> = {
+ "index.html": "index-before",
+ "scene.html": "scene-before",
+ };
+ const writes: Array<[string, string]> = [];
+
+ await expect(
+ saveProjectFilesWithHistory({
+ projectId: "project-1",
+ label: "Move layer",
+ kind: "manual",
+ files: {
+ "index.html": "index-after",
+ "scene.html": "scene-after",
+ },
+ readFile: async (path) => reads[path],
+ writeFile: async (path, content) => {
+ writes.push([path, content]);
+ },
+ recordEdit: async () => {
+ throw new Error("history unavailable");
+ },
+ }),
+ ).rejects.toThrow("history unavailable");
+
+ expect(writes).toEqual([
+ ["index.html", "index-after"],
+ ["scene.html", "scene-after"],
+ ["scene.html", "scene-before"],
+ ["index.html", "index-before"],
+ ]);
+ });
+
+ it("reports rollback failure with the original write failure", async () => {
+ const reads: Record<string, string> = {
+ "index.html": "index-before",
+ "scene.html": "scene-before",
+ };
+ const writes: Array<[string, string]> = [];
+
+ await expect(
+ saveProjectFilesWithHistory({
+ projectId: "project-1",
+ label: "Move layer",
+ kind: "manual",
+ files: {
+ "index.html": "index-after",
+ "scene.html": "scene-after",
+ },
+ readFile: async (path) => reads[path],
+ writeFile: async (path, content) => {
+ writes.push([path, content]);
+ if (path === "scene.html" && content === "scene-after") {
+ throw new Error("write denied");
+ }
+ if (path === "index.html" && content === "index-before") {
+ throw new Error("rollback denied");
+ }
+ },
+ recordEdit: vi.fn(),
+ }),
+ ).rejects.toThrow("rollback did not complete");
+
+ expect(writes).toEqual([
+ ["index.html", "index-after"],
+ ["scene.html", "scene-after"],
+ ["index.html", "index-before"],
+ ]);
+ });
+});
diff --git a/packages/studio/src/utils/studioFileHistory.ts b/packages/studio/src/utils/studioFileHistory.ts
new file mode 100644
index 0000000000..95e0a2a395
--- /dev/null
+++ b/packages/studio/src/utils/studioFileHistory.ts
@@ -0,0 +1,61 @@
+import type { EditHistoryKind } from "./editHistory";
+
+interface SaveProjectFilesWithHistoryInput {
+ projectId: string;
+ label: string;
+ kind: EditHistoryKind;
+ coalesceKey?: string;
+ files: Record<string, string>;
+ readFile: (path: string) => Promise<string>;
+ writeFile: (path: string, content: string) => Promise<void>;
+ recordEdit: (entry: {
+ label: string;
+ kind: EditHistoryKind;
+ coalesceKey?: string;
+ files: Record<string, { before: string; after: string }>;
+ }) => Promise<void>;
+}
+
+export async function saveProjectFilesWithHistory({
+ label,
+ kind,
+ coalesceKey,
+ files,
+ readFile,
+ writeFile,
+ recordEdit,
+}: SaveProjectFilesWithHistoryInput): Promise<string[]> {
+ const snapshots: Record<string, { before: string; after: string }> = {};
+ for (const [path, after] of Object.entries(files)) {
+ const before = await readFile(path);
+ if (before !== after) {
+ snapshots[path] = { before, after };
+ }
+ }
+
+ const changedPaths = Object.keys(snapshots);
+ if (changedPaths.length === 0) return [];
+
+ const writtenPaths: string[] = [];
+ try {
+ for (const path of changedPaths) {
+ await writeFile(path, snapshots[path].after);
+ writtenPaths.push(path);
+ }
+
+ await recordEdit({ label, kind, coalesceKey, files: snapshots });
+ } catch (error) {
+ try {
+ for (const path of writtenPaths.reverse()) {
+ await writeFile(path, snapshots[path].before);
+ }
+ } catch (rollbackError) {
+ throw new AggregateError(
+ [error, rollbackError],
+ "Failed to save project files and rollback did not complete",
+ );
+ }
+ throw error;
+ }
+ return changedPaths;
+}
diff --git a/packages/studio/src/utils/timelineAssetDrop.test.ts b/packages/studio/src/utils/timelineAssetDrop.test.ts
index 2284091b40..80ff8dcf35 100644
--- a/packages/studio/src/utils/timelineAssetDrop.test.ts
+++ b/packages/studio/src/utils/timelineAssetDrop.test.ts
@@ -4,6 +4,7 @@ import {
buildTimelineAssetInsertHtml,
getTimelineAssetKind,
insertTimelineAssetIntoSource,
+ resolveTimelineAssetInitialGeometry,
resolveTimelineAssetSrc,
} from "./timelineAssetDrop";
@@ -19,17 +20,21 @@ describe("getTimelineAssetKind", () => {
describe("buildTimelineAssetInsertHtml", () => {
it("builds an image clip with explicit timing and track", () => {
- expect(
- buildTimelineAssetInsertHtml({
- id: "photo_asset",
- assetPath: "assets/photo.png",
- kind: "image",
- start: 1.25,
- duration: 3,
- track: 2,
- zIndex: 4,
- }),
- ).toContain('img id="photo_asset"');
+ const html = buildTimelineAssetInsertHtml({
+ id: "photo_asset",
+ assetPath: "assets/photo.png",
+ kind: "image",
+ start: 1.25,
+ duration: 3,
+ track: 2,
+ zIndex: 4,
+ geometry: { left: 0, top: 0, width: 1280, height: 720 },
+ });
+
+ expect(html).toContain('img id="photo_asset"');
+ expect(html).toContain("left: 0px");
+ expect(html).toContain("width: 1280px");
+ expect(html).not.toContain("inset:");
});
it("builds an audio clip without visual layout styles", () => {
@@ -47,6 +52,21 @@ describe("buildTimelineAssetInsertHtml", () => {
});
});
+describe("resolveTimelineAssetInitialGeometry", () => {
+ it("uses the target composition dimensions for visual media", () => {
+ expect(
+ resolveTimelineAssetInitialGeometry(
+ `<div data-composition-id="main" data-width="330" data-height="228"></div>`,
+ ),
+ ).toEqual({
+ left: 0,
+ top: 0,
+ width: 330,
+ height: 228,
+ });
+ });
+});
+
describe("resolveTimelineAssetSrc", () => {
it("keeps project-root asset paths for index.html", () => {
expect(resolveTimelineAssetSrc("index.html", "assets/photo.png")).toBe("assets/photo.png");
diff --git a/packages/studio/src/utils/timelineAssetDrop.ts b/packages/studio/src/utils/timelineAssetDrop.ts
index c8ee11a559..9a431b4c5e 100644
--- a/packages/studio/src/utils/timelineAssetDrop.ts
+++ b/packages/studio/src/utils/timelineAssetDrop.ts
@@ -76,6 +76,23 @@ export function buildTimelineFileDropPlacements(
});
}
+export function resolveTimelineAssetInitialGeometry(source: string): {
+ left: number;
+ top: number;
+ width: number;
+ height: number;
+} {
+ const width = Number.parseFloat(source.match(/\bdata-width=(["'])([^"']+)\1/i)?.[2] ?? "");
+ const height = Number.parseFloat(source.match(/\bdata-height=(["'])([^"']+)\1/i)?.[2] ?? "");
+
+ return {
+ left: 0,
+ top: 0,
+ width: Number.isFinite(width) && width > 0 ? Math.round(width) : 640,
+ height: Number.isFinite(height) && height > 0 ? Math.round(height) : 360,
+ };
+}
+
export function buildTimelineAssetInsertHtml(input: {
id: string;
assetPath: string;
@@ -84,15 +101,18 @@ export function buildTimelineAssetInsertHtml(input: {
duration: number;
track: number;
zIndex: number;
+ geometry?: { left: number; top: number; width: number; height: number };
}): string {
const sharedAttrs = `id="${input.id}" class="clip" src="${input.assetPath}" data-start="${input.start}" data-duration="${input.duration}" data-track-index="${input.track}"`;
+ const geometry = input.geometry ?? { left: 0, top: 0, width: 640, height: 360 };
+ const visualStyles = `position: absolute; left: ${geometry.left}px; top: ${geometry.top}px; width: ${geometry.width}px; height: ${geometry.height}px; object-fit: contain; z-index: ${input.zIndex}`;
if (input.kind === "image") {
- return `<img ${sharedAttrs} style="position: absolute; inset: 0; width: 100%; height: 100%; object-fit: contain; z-index: ${input.zIndex}" />`;
+ return `<img ${sharedAttrs} style="${visualStyles}" />`;
}
if (input.kind === "video") {
- return `<video ${sharedAttrs} muted playsinline style="position: absolute; inset: 0; width: 100%; height: 100%; object-fit: contain; z-index: ${input.zIndex}"></video>`;
+ return `<video ${sharedAttrs} muted playsinline style="${visualStyles}"></video>`;
}
return `<audio ${sharedAttrs} style="z-index: ${input.zIndex}"></audio>`;
diff --git a/packages/studio/vite.config.ts b/packages/studio/vite.config.ts
index 9e7c014f62..c6f39e5052 100644
--- a/packages/studio/vite.config.ts
+++ b/packages/studio/vite.config.ts
@@ -9,11 +9,13 @@ import {
realpathSync,
} from "node:fs";
import { join, resolve } from "node:path";
-import type {
- StudioApiAdapter,
- ResolvedProject,
- RenderJobState,
+import { createHash } from "node:crypto";
+import {
+ type ResolvedProject,
+ type RenderJobState,
+ type StudioApiAdapter,
} from "@hyperframes/core/studio-api";
+import { createStudioManualEditsRenderBodyScript } from "@hyperframes/core/studio-api/manual-edits-render-script";
import { createRetryingModuleLoader, ensureProducerDist } from "./vite.producer";
import { readNodeRequestBody } from "./vite.request-body.js";
import { seekThumbnailPreview } from "./vite.thumbnail";
@@ -48,6 +50,7 @@ async function getSharedBrowser(): Promise<import("puppeteer-core").Browser | nu
// In-flight thumbnail dedup
const _thumbnailInflight = new Map<string, Promise<Buffer>>();
const THUMBNAIL_CACHE_VERSION = "v3";
+const STUDIO_MANUAL_EDITS_PATH = ".hyperframes/studio-manual-edits.json";
interface ScreenshotClip {
x: number;
@@ -56,24 +59,59 @@ interface ScreenshotClip {
height: number;
}
+function readStudioManualEditManifestContent(projectDir: string): string {
+ const manifestPath = join(projectDir, STUDIO_MANUAL_EDITS_PATH);
+ if (!existsSync(manifestPath)) return "";
+ try {
+ return readFileSync(manifestPath, "utf-8");
+ } catch {
+ return "";
+ }
+}
+
+async function applyStudioManualEditsToThumbnailPage(
+ page: import("puppeteer-core").Page,
+ manifestContent: string,
+ activeCompositionPath: string,
+): Promise<void> {
+ const script = createStudioManualEditsRenderBodyScript(manifestContent, {
+ activeCompositionPath,
+ });
+ if (!script) return;
+ await page.addScriptTag({ content: script });
+}
+
+async function reapplyStudioManualEditsToThumbnailPage(
+ page: import("puppeteer-core").Page,
+): Promise<void> {
+ await page.evaluate(() => {
+ const apply = (window as Window & { __hfStudioManualEditsApply?: () => number })
+ .__hfStudioManualEditsApply;
+ if (typeof apply === "function") apply();
+ });
+}
+
// ── Vite adapter for the shared studio API ───────────────────────────────────
function createViteAdapter(dataDir: string, server: ViteDevServer): StudioApiAdapter {
// Lazy-load the bundler via Vite's SSR module loader
let _bundler: ((dir: string) => Promise<string>) | null = null;
- let _producerModulePromise: Promise<{
- createRenderJob: (config: {
- fps: 24 | 30 | 60;
- quality: "draft" | "standard" | "high";
- format: string;
- }) => unknown;
- executeRenderJob: (
- job: unknown,
- projectDir: string,
- outputPath: string,
- onProgress?: (job: { progress: number; currentStage?: string }) => void,
- ) => Promise<void>;
- }> | null = null;
+ let _producerModuleLoader:
+ | (() => Promise<{
+ createRenderJob: (config: {
+ fps: 24 | 30 | 60;
+ quality: "draft" | "standard" | "high";
+ format: string;
+ renderBodyScripts?: string[];
+ }) => unknown;
+ executeRenderJob: (
+ job: unknown,
+ projectDir: string,
+ outputPath: string,
+ onProgress?: (job: { progress: number; currentStage?: string }) => void,
+ ) => Promise<void>;
+ }>)
+ | null = null;
const getBundler = async () => {
if (!_bundler) {
try {
@@ -88,8 +126,8 @@ function createViteAdapter(dataDir: string, server: ViteDevServer): StudioApiAda
};
const getProducerModule = async () => {
- if (!_producerModulePromise) {
- _producerModulePromise = createRetryingModuleLoader(async () => {
+ if (!_producerModuleLoader) {
+ _producerModuleLoader = createRetryingModuleLoader(async () => {
const { built } = ensureProducerDist({
studioDir: __dirname,
env: process.env,
@@ -101,9 +139,9 @@ function createViteAdapter(dataDir: string, server: ViteDevServer): StudioApiAda
}
const producerPkg = "@hyperframes/producer";
return await import(/* @vite-ignore */ producerPkg);
- })();
+ });
}
- return _producerModulePromise();
+ return _producerModuleLoader();
};
return {
@@ -211,10 +249,13 @@ function createViteAdapter(dataDir: string, server: ViteDevServer): StudioApiAda
if (systemChrome) process.env.PRODUCER_HEADLESS_SHELL_PATH = systemChrome;
}
const { createRenderJob, executeRenderJob } = await getProducerModule();
+ const manifestContent = readStudioManualEditManifestContent(opts.project.dir);
+ const manualEditsRenderScript = createStudioManualEditsRenderBodyScript(manifestContent);
const job = createRenderJob({
fps: opts.fps as 24 | 30 | 60,
quality: opts.quality as "draft" | "standard" | "high",
format: opts.format,
+ ...(manualEditsRenderScript ? { renderBodyScripts: [manualEditsRenderScript] } : {}),
});
const onProgress = (j: { progress: number; currentStage?: string }) => {
state.progress = j.progress;
@@ -245,9 +286,13 @@ function createViteAdapter(dataDir: string, server: ViteDevServer): StudioApiAda
async generateThumbnail(opts) {
const selectorKey = opts.selector
- ? `_${opts.selector.replace(/[^a-zA-Z0-9_-]+/g, "_").slice(0, 80)}`
+ ? `_${opts.selector.replace(/[^a-zA-Z0-9_-]+/g, "_").slice(0, 80)}_${opts.selectorIndex ?? 0}`
+ : "";
+ const manifestContent = readStudioManualEditManifestContent(opts.project.dir);
+ const manifestKey = manifestContent.trim()
+ ? `_${createHash("sha1").update(manifestContent).digest("hex").slice(0, 16)}`
: "";
- const cacheKey = `${THUMBNAIL_CACHE_VERSION}_${opts.compPath.replace(/\//g, "_")}_${opts.seekTime.toFixed(2)}${selectorKey}.jpg`;
+ const cacheKey = `${THUMBNAIL_CACHE_VERSION}${manifestKey}_${opts.compPath.replace(/\//g, "_")}_${opts.seekTime.toFixed(2)}${selectorKey}.${opts.format === "png" ? "png" : "jpg"}`;
let bufferPromise = _thumbnailInflight.get(cacheKey);
if (!bufferPromise) {
@@ -274,27 +319,40 @@ function createViteAdapter(dataDir: string, server: ViteDevServer): StudioApiAda
)
.catch(() => {});
await seekThumbnailPreview(page, opts.seekTime);
+ await applyStudioManualEditsToThumbnailPage(page, manifestContent, opts.compPath);
await page.evaluate("document.fonts?.ready");
await new Promise((r) => setTimeout(r, 200));
+ await reapplyStudioManualEditsToThumbnailPage(page);
let clip: ScreenshotClip | undefined;
if (opts.selector) {
- clip = await page.evaluate((selector: string) => {
- const el = document.querySelector(selector);
- if (!(el instanceof HTMLElement)) return undefined;
- const rect = el.getBoundingClientRect();
- if (rect.width < 4 || rect.height < 4) return undefined;
- const pad = 8;
- const x = Math.max(0, rect.left - pad);
- const y = Math.max(0, rect.top - pad);
- const maxWidth = window.innerWidth - x;
- const maxHeight = window.innerHeight - y;
- return {
- x,
- y,
- width: Math.max(1, Math.min(rect.width + pad * 2, maxWidth)),
- height: Math.max(1, Math.min(rect.height + pad * 2, maxHeight)),
- };
- }, opts.selector);
+ clip = await page.evaluate(
+ (selector: string, selectorIndex: number | undefined) => {
+ const matches = Array.from(document.querySelectorAll(selector)).filter(
+ (el): el is HTMLElement => el instanceof HTMLElement,
+ );
+ const safeIndex = Math.max(
+ 0,
+ Math.min(matches.length - 1, Math.floor(selectorIndex ?? 0)),
+ );
+ const el = matches[safeIndex] ?? null;
+ if (!(el instanceof HTMLElement)) return undefined;
+ const rect = el.getBoundingClientRect();
+ if (rect.width < 4 || rect.height < 4) return undefined;
+ const pad = 8;
+ const x = Math.max(0, rect.left - pad);
+ const y = Math.max(0, rect.top - pad);
+ const maxWidth = window.innerWidth - x;
+ const maxHeight = window.innerHeight - y;
+ return {
+ x,
+ y,
+ width: Math.max(1, Math.min(rect.width + pad * 2, maxWidth)),
+ height: Math.max(1, Math.min(rect.height + pad * 2, maxHeight)),
+ };
+ },
+ opts.selector,
+ opts.selectorIndex,
+ );
}
const buf = await page.screenshot(
opts.format === "png"
@@ -492,10 +550,13 @@ function devProjectApi(): Plugin {
const isProjectFile = realProjectPaths.some((p) => filePath.startsWith(p));
if (
isProjectFile &&
- (filePath.endsWith(".html") || filePath.endsWith(".css") || filePath.endsWith(".js"))
+ (filePath.endsWith(".html") ||
+ filePath.endsWith(".css") ||
+ filePath.endsWith(".js") ||
+ filePath.endsWith(".json"))
) {
console.log(`[Studio] File changed: ${filePath}`);
- server.ws.send({ type: "custom", event: "hf:file-change", data: {} });
+ server.ws.send({ type: "custom", event: "hf:file-change", data: { path: filePath } });
}
});
},