Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 88 additions & 0 deletions packages/studio/src/hooks/elementPickerWrites.browser.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import { readFileSync } from "node:fs";
import { createRequire } from "node:module";
import type { Browser } from "puppeteer-core";
import { afterAll, beforeAll, expect, it, vi } from "vitest";
import { closeTestChrome, launchTestChrome } from "../../tests/chromeTestUtils";
import { buildStudioBundle, openPreview } from "../../tests/sealedPreviewHarness";

vi.setConfig({ testTimeout: 60_000, hookTimeout: 60_000 });
const require = createRequire(import.meta.url);
const MODES = process.env.HF_PARITY_MODE ? [process.env.HF_PARITY_MODE] : ["unsealed", "sealed"];
let browser: Browser;
let studioBundle: string;

beforeAll(async () => {
browser = await launchTestChrome();
studioBundle = await buildStudioBundle([
`export { writePicked } from "./hooks/elementPickerWrites";`,
]);
});

afterAll(() => closeTestChrome(browser));

function previewHtml(): string {
const runtime = readFileSync(require.resolve("@hyperframes/core/runtime"), "utf8");
return `<!doctype html><html><head><meta charset="UTF-8" />
<meta name="hyperframes-studio-preview" content="1" />
</head><body>
<div id="root" data-composition-id="main" data-start="0" data-duration="4" data-width="1920" data-height="1080">
<h1 class="title" data-hf-id="t1" data-start="0" data-duration="4" data-track-index="1">Hello</h1>
</div>
<script>${runtime}</script></body></html>`;
}

async function pickerWrites(mode: string) {
const preview = await openPreview(browser, studioBundle, previewHtml(), mode);
try {
const sources = await preview.page.evaluate(async () => {
type Studio = {
writePicked(iframe: HTMLIFrameElement, selector: string, write: unknown): unknown;
};
const studio = (window as unknown as { hfStudio: Studio }).hfStudio;
const iframe = document.querySelector("iframe")!;
return [
await studio.writePicked(iframe, ".title", {
live: (el: HTMLElement) => el.style.setProperty("color", "rgb(0, 128, 0)"),
sealed: { styles: [["color", "rgb(0, 128, 0)"]] },
}),
await studio.writePicked(iframe, ".title", {
live: (el: HTMLElement) => el.setAttribute("data-mood", "calm"),
sealed: { attributes: [["data-mood", "calm"]] },
}),
await studio.writePicked(iframe, ".title", {
live: (el: HTMLElement) => {
el.textContent = "Hi <there> & you";
},
sealed: { html: "Hi &lt;there&gt; &amp; you" },
}),
await studio.writePicked(iframe, ".missing", {
live: () => {},
sealed: { styles: [["color", "red"]] },
}),
];
});
const drawn = await preview.frame.evaluate(() => {
const title = document.querySelector<HTMLElement>(".title")!;
return {
color: getComputedStyle(title).color,
mood: title.getAttribute("data-mood"),
text: title.textContent,
};
});
return { sources, drawn };
} finally {
await preview.page.close();
}
}

it.each(MODES)(
"the element picker's style, data and text edits draw in a %s preview",
async (mode) => {
const writes = await pickerWrites(mode);
const source = { hfId: "t1", ownFile: "index.html" };
expect(writes).toEqual({
sources: [source, source, source, null],
drawn: { color: "rgb(0, 128, 0)", mood: "calm", text: "Hi <there> & you" },
});
},
);
52 changes: 52 additions & 0 deletions packages/studio/src/hooks/elementPickerWrites.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { compositionPathOfPreviewUrl } from "../player/components/CompositionThumbnail";
import { previewFrameOpaque } from "../player/lib/previewChannel";
import {
describePreviewElements,
editPreviewElement,
previewElementSourceFile,
queryPreviewElements,
} from "../player/lib/previewElements";
import { getSourceFileForElement } from "../components/editor/domEditingDom";

const previewedPath = (iframe: HTMLIFrameElement) =>
compositionPathOfPreviewUrl(iframe.getAttribute("src") ?? "");

export interface PickedSource {
hfId: string | null;
ownFile: string;
}

export interface PickedWrite {
live: (el: HTMLElement) => void;
sealed: Parameters<typeof editPreviewElement>[2];
}

/** Draws `write` on the frame's first `selector` match; the element's source, or null when nothing was drawn. */
export function writePicked(
iframe: HTMLIFrameElement,
selector: string,
write: PickedWrite,
): PickedSource | null | Promise<PickedSource | null> {
if (previewFrameOpaque(iframe)) return writeSealedPicked(iframe, selector, write.sealed);
try {
const el = iframe.contentDocument?.querySelector<HTMLElement>(selector);
if (!el) return null;
write.live(el);
const ownFile = getSourceFileForElement(el, previewedPath(iframe)).sourceFile;
return { hfId: el.getAttribute("data-hf-id"), ownFile };
} catch {
return null;
}
}

async function writeSealedPicked(
iframe: HTMLIFrameElement,
selector: string,
edit: PickedWrite["sealed"],
): Promise<PickedSource | null> {
const handle = (await queryPreviewElements(iframe, selector))?.matches[0]?.handle;
const [element] = (handle && (await describePreviewElements(iframe, [handle]))) || [];
if (!element || !(await editPreviewElement(iframe, element.handle, edit).drawn)) return null;
const hfId = element.attributes.find(([name]) => name === "data-hf-id")?.[1] ?? null;
return { hfId, ownFile: previewElementSourceFile(element, previewedPath(iframe)) };
}
132 changes: 49 additions & 83 deletions packages/studio/src/hooks/useElementPicker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@ import {
acceptStudioRuntimeMessage,
postRuntimeControlMessage,
} from "../player/lib/runtimeProtocol";
import { compositionPathOfPreviewUrl } from "../player/components/CompositionThumbnail";
import { frameOrigins } from "../player/lib/bridgePlayback";
import { previewComputedStyles, previewFrameOpaque } from "../player/lib/previewChannel";
import { escapeHtmlText } from "../components/editor/domEditingLayers";
import { writePicked, type PickedSource, type PickedWrite } from "./elementPickerWrites";
import { PICKED_STYLE_PROPERTIES, readComputedStyles } from "./elementPickerStyles";
import { getSourceFileForElement } from "../components/editor/domEditingDom";
import {
createElementPickerHoverLabel,
type ElementPickerHoverInfo,
Expand Down Expand Up @@ -298,17 +298,16 @@ export function useElementPicker(
settlePendingWrites(pendingWritesRef.current, options?.workspaceFiles);

const syncToSource = useCallback(
(picked: PickedElement, live: HTMLElement, iframe: HTMLIFrameElement, op: PatchOperation) => {
(picked: PickedElement, source: PickedSource, op: PatchOperation) => {
const opts = optionsRef.current;
if (!opts?.workspaceFiles || !opts.onSyncFiles) return;
// No id: the preview's hf-id names the element, in the file it was served from.
const hfId = live.getAttribute("data-hf-id");
const pending = pendingWritesRef.current;
const files = withPendingWrites(opts.workspaceFiles, pending);
const patch = picked.id
? patchById(files, picked.id, picked.selector, op)
: hfId
? patchByHfId(files, hfId, ownSourceFile(live, iframe), op)
: source.hfId
? patchByHfId(files, source.hfId, source.ownFile, op)
: null;
if (!patch || patch.after === patch.before) return;
recordPendingWrite(pending, patch.path, opts.workspaceFiles[patch.path], patch.after);
Expand All @@ -317,87 +316,59 @@ export function useElementPicker(
[],
);

const setStyle = useCallback(
(prop: string, value: string) => {
const writePickedElement = useCallback(
(write: PickedWrite, shown: (prev: PickedElement) => PickedElement, op: PatchOperation) => {
const activeIframe = getActiveIframe();
if (!pickedElement?.selector || !activeIframe) return;
try {
const doc = activeIframe.contentDocument;
const el = doc?.querySelector(pickedElement.selector) as HTMLElement | null;
if (el) {
el.style.setProperty(prop, value);
setPickedElement((prev) =>
prev
? {
...prev,
computedStyles: { ...prev.computedStyles, [prop]: value },
}
: null,
);
syncToSource(pickedElement, el, activeIframe, {
type: "inline-style",
property: prop,
value,
});
}
} catch {
/* cross-origin */
}
const picked = pickedElement;
if (!picked?.selector || !activeIframe) return;
const saved = (source: PickedSource | null) => {
if (!source) return;
setPickedElement((prev) => (prev ? shown(prev) : null));
syncToSource(picked, source, op);
};
const source = writePicked(activeIframe, picked.selector, write);
if (source instanceof Promise) void source.then(saved);
else saved(source);
},
[pickedElement, getActiveIframe, setPickedElement, syncToSource],
);

const setStyle = useCallback(
(prop: string, value: string) =>
writePickedElement(
{ live: (el) => el.style.setProperty(prop, value), sealed: { styles: [[prop, value]] } },
(prev) => ({ ...prev, computedStyles: { ...prev.computedStyles, [prop]: value } }),
{ type: "inline-style", property: prop, value },
),
[writePickedElement],
);

const setDataAttr = useCallback(
(attr: string, value: string) => {
const activeIframe = getActiveIframe();
if (!pickedElement?.selector || !activeIframe) return;
try {
const doc = activeIframe.contentDocument;
const el = doc?.querySelector(pickedElement.selector);
if (el) {
el.setAttribute(`data-${attr}`, value);
setPickedElement((prev) =>
prev
? {
...prev,
dataAttributes: { ...prev.dataAttributes, [attr]: value },
}
: null,
);
syncToSource(pickedElement, el as HTMLElement, activeIframe, {
type: "attribute",
property: attr,
value,
});
}
} catch {
/* cross-origin */
}
},
[pickedElement, getActiveIframe, setPickedElement, syncToSource],
(attr: string, value: string) =>
writePickedElement(
{
live: (el) => el.setAttribute(`data-${attr}`, value),
sealed: { attributes: [[`data-${attr}`, value]] },
},
(prev) => ({ ...prev, dataAttributes: { ...prev.dataAttributes, [attr]: value } }),
{ type: "attribute", property: attr, value },
),
[writePickedElement],
);

const setTextContent = useCallback(
(text: string) => {
const activeIframe = getActiveIframe();
if (!pickedElement?.selector || !activeIframe) return;
try {
const doc = activeIframe.contentDocument;
const el = doc?.querySelector(pickedElement.selector);
if (el) {
el.textContent = text;
setPickedElement((prev) => (prev ? { ...prev, textContent: text } : null));
syncToSource(pickedElement, el as HTMLElement, activeIframe, {
type: "text-content",
property: "textContent",
value: text,
});
}
} catch {
/* cross-origin */
}
},
[pickedElement, getActiveIframe, setPickedElement, syncToSource],
(text: string) =>
writePickedElement(
{
live: (el) => {
el.textContent = text;
},
sealed: { html: escapeHtmlText(text) },
},
(prev) => ({ ...prev, textContent: text }),
{ type: "text-content", property: "textContent", value: text },
),
[writePickedElement],
);

return {
Expand Down Expand Up @@ -543,11 +514,6 @@ function patchById(
return path && before ? { path, before, after: applyPatch(before, id, op) } : null;
}

function ownSourceFile(live: HTMLElement, iframe: HTMLIFrameElement): string {
const previewed = compositionPathOfPreviewUrl(iframe.getAttribute("src") ?? "");
return getSourceFileForElement(live, previewed).sourceFile;
}

function patchByHfId(
files: Record<string, string>,
hfId: string,
Expand Down
Loading