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
4 changes: 2 additions & 2 deletions packages/core/src/runtime/editing/color-grading.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { installEditingAgent } from "../editingAgent";
import { installMarkedEditingAgent } from "../editingAgent.test-helpers";

const CONNECT = { source: "hf-parent", type: "editing-connect", v: 1 };
const target = { id: "clip", hfId: null, selector: "#clip", selectorIndex: 0 };
Expand All @@ -16,7 +16,7 @@ function connect(): MessagePort {
const parent = document.body.appendChild(document.createElement("iframe")).contentWindow!;
const handoff = vi.fn();
parent.postMessage = handoff as unknown as Window["postMessage"];
agent = installEditingAgent(parent);
agent = installMarkedEditingAgent(parent);
window.dispatchEvent(new MessageEvent("message", { source: parent, data: CONNECT }));
return (handoff.mock.calls[0]![2] as MessagePort[])[0]!;
}
Expand Down
26 changes: 26 additions & 0 deletions packages/core/src/runtime/editing/restoreAttributes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,32 @@ describe("restore-attributes", () => {
expect(rebind).not.toHaveBeenCalled();
});

it("changes no handler, URL or sandbox-style attribute, and leaves an unchanged one alone", () => {
const refused = (html: string, attributes: [string, string][]) => {
document.body.innerHTML = html;
player();
const before = document.body.innerHTML;
expect(restoreAttributes(restore("hf:box", attributes))).toEqual({ applied: false });
expect(document.body.innerHTML).toBe(before);
};
const box = '<div data-hf-id="box"></div>';
const id: [string, string] = ["data-hf-id", "box"];
for (const name of ["onclick", "ONCLICK", "href", "src", "srcdoc", "xlink:href", "sandbox"])
refused(box, [id, [name, "alert(1)"]]);
refused(box, [id, ["data-composition-src", "https://example.com/a.html"]]);
refused('<iframe data-hf-id="box" sandbox=""></iframe>', [id]);

document.body.innerHTML =
'<img data-hf-id="box" src="a.png" style="left: 9px" loading="lazy" data-hf-preview-lazy>';
player();
const img = document.querySelector("img")!;
const setAttribute = vi.spyOn(img, "setAttribute");
const params = restore("hf:box", [id, ["src", "a.png"], ["style", "left: 0px"]]);
expect(restoreAttributes(params)).toEqual({ applied: true });
expect(setAttribute.mock.calls).toEqual([["style", "left: 0px"]]);
expect(img.hasAttribute("loading")).toBe(false);
});

it("accepts only bounded, well-formed params", () => {
const ok = restore("hf:box", [["style", "left: 0"]]);
expect(parseRestoreAttributes(ok)).toEqual(ok);
Expand Down
42 changes: 34 additions & 8 deletions packages/core/src/runtime/editing/restoreAttributes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,29 @@ const MAX_KEY_LENGTH = 512;
const MAX_VALUE_LENGTH = 200_000;
const ATTRIBUTE_NAME = /^[^\s"'>/=]{1,256}$/;
const IDENTITY_SELECTOR = "[id], [data-hf-id]";
const SAFE_TO_SET = new Set([
"class",
"style",
"data-start",
"data-end",
"data-duration",
"data-track-index",
"data-media-start",
"data-playback-start",
"data-playback-rate",
"data-volume",
"data-audio-muted",
"data-hidden",
"data-label",
"data-timeline-label",
"data-width",
"data-height",
"data-x",
"data-y",
"data-hf-group",
]);
const safeToDrop = (name: string) =>
SAFE_TO_SET.has(name) || name === "loading" || name.startsWith("data-");

const isRecord = (value: unknown): value is Record<string, unknown> =>
Object.prototype.toString.call(value) === "[object Object]";
Expand Down Expand Up @@ -96,9 +119,9 @@ function scopeRoots(file: string | null): ParentNode[] {
);
}

type RestorePlan = [Element, RestoreAttribute[]][];
type RestorePlan = [Element, drop: string[], set: RestoreAttribute[]][];

/** Adds `root`'s live elements to `plan`; false when any is missing or not the file's own. */
/** Adds `root`'s live elements to `plan`; false when any is missing, not the file's own, or unsafe to change. */
function planRoot(
root: ParentNode,
elements: RestoreScope["elements"],
Expand All @@ -110,12 +133,16 @@ function planRoot(
const el = live.get(key);
// The preview rewrites a sub-composition's own root, so its attributes are not the file's.
if (!el || el.hasAttribute("data-hf-inner-root")) return false;
plan.push([el, attributes]);
const keep = new Set(attributes.map(([name]) => name));
const drop = el.getAttributeNames().filter((name) => !keep.has(name));
const set = attributes.filter(([name, value]) => el.getAttribute(name) !== value);
if (!drop.every(safeToDrop) || !set.every(([name]) => SAFE_TO_SET.has(name))) return false;
plan.push([el, drop, set]);
}
return true;
}

/** Each live element with the attributes it takes, or null when any is missing or not the file's own. */
/** Each live element with the attributes it drops and sets, or null when the restore cannot apply in place. */
function planRestore(scopes: RestoreScope[]): RestorePlan | null {
const plan: RestorePlan = [];
for (const { file, elements } of scopes) {
Expand Down Expand Up @@ -153,10 +180,9 @@ export function restoreAttributes({ scopes, scripted, time }: RestoreAttributesP
const plan = planRestore(scopes);
if (!plan || typeof win.__player?.seek !== "function") return { applied: false };
if (scripted && plan.some(([el]) => "_gsap" in el)) return { applied: false };
for (const [el, attributes] of plan) {
const keep = new Set(attributes.map(([name]) => name));
for (const name of el.getAttributeNames()) if (!keep.has(name)) el.removeAttribute(name);
for (const [name, value] of attributes) el.setAttribute(name, value);
for (const [el, drop, set] of plan) {
for (const name of drop) el.removeAttribute(name);
for (const [name, value] of set) el.setAttribute(name, value);
}
rebindAt(win, time);
return { applied: true };
Expand Down
16 changes: 16 additions & 0 deletions packages/core/src/runtime/editingAgent.test-helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { STUDIO_PREVIEW_MARK_META } from "../studioPreviewMark";
import { installEditingAgent } from "./editingAgent";

/** The agent in a page Studio's preview server marked, the only page it hands a port to. */
export function installMarkedEditingAgent(parent: Window): { dispose: () => void } {
const mark = document.createElement("meta");
mark.name = STUDIO_PREVIEW_MARK_META;
document.head.append(mark);
const agent = installEditingAgent(parent);
return {
dispose() {
agent.dispose();
mark.remove();
},
};
}
17 changes: 16 additions & 1 deletion packages/core/src/runtime/editingAgent.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { installEditingAgent } from "./editingAgent";
import { PREVIEW_FOR_ANOTHER_SITE_META } from "../studioPreviewMark";
import { PREVIEW_FOR_ANOTHER_SITE_META, STUDIO_PREVIEW_MARK_META } from "../studioPreviewMark";

const CONNECT = { source: "hf-parent", type: "editing-connect", v: 1 };
const H = "0123456789abcdef:1";
const studioMark = document.createElement("meta");
studioMark.name = STUDIO_PREVIEW_MARK_META;
document.head.append(studioMark);

function frameWindow(): Window {
const iframe = document.createElement("iframe");
Expand Down Expand Up @@ -126,6 +129,18 @@ describe("installEditingAgent", () => {
expect(handoff).toHaveBeenCalledOnce();
});

it("never hands off in a document Studio's preview server did not mark", () => {
studioMark.remove();
try {
post(parent, CONNECT);
expect(handoff).not.toHaveBeenCalled();
} finally {
document.head.append(studioMark);
}
post(parent, CONNECT);
expect(handoff).toHaveBeenCalledOnce();
});

it("stops listening for a connect once disposed", () => {
agent.dispose();
post(parent, CONNECT);
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/runtime/editingAgent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ import { restoreAttributes } from "./editing/restoreAttributes";
import { gestureStart } from "./editingGestureStart";
import {
getLogicalOpacity,
markedForStudio,
previewConsoleErrorText,
servedToAnotherSite,
STUDIO_PREVIEW_ERRORS,
} from "../studioPreviewMark";
import { MAX_QUERY_MATCHES } from "./editingElement";
Expand Down Expand Up @@ -251,7 +251,7 @@ export function installEditingAgent(parent: Window = window.parent): { dispose:
const data = event.data;
if (!isPlainRecord(data) || data.source !== "hf-parent" || data.type !== EDITING_CONNECT)
return;
if (data.v !== EDITING_PROTOCOL_VERSION || servedToAnotherSite(document)) return;
if (data.v !== EDITING_PROTOCOL_VERSION || !markedForStudio(document)) return;
const channel = new MessageChannel();
const port = channel.port1;
ports.add(port);
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/runtime/editingGeometry.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { installEditingAgent } from "./editingAgent";
import { installMarkedEditingAgent } from "./editingAgent.test-helpers";
import {
MAX_ELEMENT_VALUE,
MAX_GEOMETRY_CHILDREN,
Expand Down Expand Up @@ -86,7 +86,7 @@ describe("overlay geometry over the editing port", () => {
const parent = iframe.contentWindow!;
const handoff = vi.fn();
parent.postMessage = handoff as unknown as Window["postMessage"];
agent = installEditingAgent(parent);
agent = installMarkedEditingAgent(parent);
window.dispatchEvent(new MessageEvent("message", { source: parent, data: CONNECT }));
port = (handoff.mock.calls[0]![2] as MessagePort[])[0]!;
});
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/runtime/editingHandles.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { installEditingAgent } from "./editingAgent";
import { installMarkedEditingAgent } from "./editingAgent.test-helpers";
import { trackedHandleCount } from "./editingHandles";
import {
EDITING_ELEMENT_HANDLE,
Expand Down Expand Up @@ -46,7 +46,7 @@ describe("element handles over the editing port", () => {
const parent = iframe.contentWindow!;
const handoff = vi.fn();
parent.postMessage = handoff as unknown as Window["postMessage"];
agent = installEditingAgent(parent);
agent = installMarkedEditingAgent(parent);
window.dispatchEvent(new MessageEvent("message", { source: parent, data: CONNECT }));
port = (handoff.mock.calls[0]![2] as MessagePort[])[0]!;
});
Expand Down
8 changes: 4 additions & 4 deletions packages/core/src/runtime/editingPort.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { installEditingAgent } from "./editingAgent";
import { installMarkedEditingAgent } from "./editingAgent.test-helpers";
import { createEditingPortClient, EditingPortError, type EditingPortClient } from "./editingPort";

type Listener = (event: Partial<MessageEvent>) => void;
Expand Down Expand Up @@ -53,7 +53,7 @@ describe("createEditingPortClient", () => {
window.dispatchEvent(
new MessageEvent("message", { source: parent, data }),
)) as Window["postMessage"];
const agent = installEditingAgent(parent);
const agent = installMarkedEditingAgent(parent);
try {
const client = createEditingPortClient({ iframe, host });
clients.push(client);
Expand Down Expand Up @@ -142,7 +142,7 @@ describe("createEditingPortClient", () => {
window.dispatchEvent(
new MessageEvent("message", { source: parent, data }),
)) as Window["postMessage"];
const agent = installEditingAgent(parent);
const agent = installMarkedEditingAgent(parent);
try {
const first = createEditingPortClient({ iframe, host });
await first.ready;
Expand Down Expand Up @@ -173,7 +173,7 @@ describe("createEditingPortClient", () => {
toHost.push({ source: frame, data, ports: transfer });
}) as Window["postMessage"];
frame.postMessage = ((data: unknown) => toAgent.push(data)) as Window["postMessage"];
const agent = installEditingAgent(parent);
const agent = installMarkedEditingAgent(parent);
try {
const client = createEditingPortClient({ iframe, host, timeoutMs: 300 });
clients.push(client);
Expand Down
7 changes: 7 additions & 0 deletions packages/core/src/studioPreviewMark.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,13 @@ export function servedToAnotherSite(doc: Document): boolean {
return doc.querySelector(`meta[name="${PREVIEW_FOR_ANOTHER_SITE_META}"]`) !== null;
}

export function markedForStudio(doc: Document): boolean {
return (
doc.querySelector(`meta[name="${STUDIO_PREVIEW_MARK_META}"]`) !== null &&
!servedToAnotherSite(doc)
);
}

export function getLogicalOpacity(el: Element, computed: CSSStyleDeclaration): string {
const overlay = el.previousElementSibling;
if (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { act, createElement, Fragment, useRef } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, expect, it, vi } from "vitest";
// The frame's real runtime agent, serving the opaque frame from this document.
import { installEditingAgent } from "../../../../core/src/runtime/editingAgent";
import { installMarkedEditingAgent } from "../../../../core/src/runtime/editingAgent.test-helpers";
import { installReactActEnvironment } from "../../hooks/domSelectionTestHarness";
import { detachedFakeIframe } from "../../player/hooks/timelinePlayerTestHarness";
import { previewRequest } from "../../player/lib/previewChannel";
Expand Down Expand Up @@ -77,7 +77,7 @@ function opaqueFrame() {
}),
),
} as unknown as Window;
const agent = installEditingAgent(parent);
const agent = installMarkedEditingAgent(parent);
frame.postMessage = (data: unknown) =>
window.dispatchEvent(new MessageEvent("message", { source: parent, data }));
closers.push(() => agent.dispose());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { act, createElement } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, expect, it, vi } from "vitest";
// The frame's real runtime agent, serving the opaque frame from this document.
import { installEditingAgent } from "../../../../core/src/runtime/editingAgent";
import { installMarkedEditingAgent } from "../../../../core/src/runtime/editingAgent.test-helpers";
import { installReactActEnvironment } from "../../hooks/domSelectionTestHarness";
import { detachedFakeIframe } from "../../player/hooks/timelinePlayerTestHarness";
import { usePreviewIframeStore } from "../../player/store/previewIframeStore";
Expand Down Expand Up @@ -91,7 +91,7 @@ function opaqueFrame() {
new MessageEvent("message", { source: frame as unknown as Window, data, ports }),
),
} as unknown as Window;
const agent = installEditingAgent(parent);
const agent = installMarkedEditingAgent(parent);
frame.postMessage = (data: unknown) =>
window.dispatchEvent(new MessageEvent("message", { source: parent, data }));
closers.push(() => agent.dispose());
Expand Down
4 changes: 2 additions & 2 deletions packages/studio/src/components/editor/previewDrafts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
// The frame's real runtime agent, serving the opaque frame from this document.
import { installEditingAgent } from "../../../../core/src/runtime/editingAgent";
import { installMarkedEditingAgent } from "../../../../core/src/runtime/editingAgent.test-helpers";
import { detachedFakeIframe } from "../../player/hooks/timelinePlayerTestHarness";
import { describePreviewElements, queryPreviewElements } from "../../player/lib/previewElements";
import { resolvePreviewSelection, standInFor } from "./previewSelection";
Expand Down Expand Up @@ -61,7 +61,7 @@ function opaqueFrame(): HTMLIFrameElement {
new MessageEvent("message", { source: frame as unknown as Window, data, ports }),
),
} as unknown as Window;
const agent = installEditingAgent(parent);
const agent = installMarkedEditingAgent(parent);
target.postMessage = (data: unknown) =>
window.dispatchEvent(new MessageEvent("message", { source: parent, data }));
closers.push(() => agent.dispose());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
// The frame's real runtime agent, serving the opaque frame from this document.
import { installEditingAgent } from "../../../../core/src/runtime/editingAgent";
import { installMarkedEditingAgent } from "../../../../core/src/runtime/editingAgent.test-helpers";
import { makeSelection } from "../../hooks/domSelectionTestHarness";
import { computeDraggedGsapPosition } from "../../hooks/draggedGsapPosition";
import { watchPreviewFrame } from "../../player/lib/bridgePlayback";
Expand Down Expand Up @@ -100,7 +100,7 @@ function opaqueFrame() {
new MessageEvent("message", { source: frame as unknown as Window, data, ports }),
),
} as unknown as Window;
const agent = installEditingAgent(parent);
const agent = installMarkedEditingAgent(parent);
frame.postMessage = (data: unknown) =>
window.dispatchEvent(new MessageEvent("message", { source: parent, data }));
closers.push(() => agent.dispose());
Expand Down
4 changes: 2 additions & 2 deletions packages/studio/src/components/editor/previewLayers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { MAX_QUERY_MATCHES } from "@hyperframes/core/runtime/editing-port";
import { createRoot } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
// The frame's real runtime agent, serving the opaque frame from this document.
import { installEditingAgent } from "../../../../core/src/runtime/editingAgent";
import { installMarkedEditingAgent } from "../../../../core/src/runtime/editingAgent.test-helpers";
import { installReactActEnvironment } from "../../hooks/domSelectionTestHarness";
import { watchPreviewFrame } from "../../player/lib/bridgePlayback";
import { getElementZIndex } from "../../player/lib/layerOrdering";
Expand Down Expand Up @@ -97,7 +97,7 @@ function opaqueFrame() {
new MessageEvent("message", { source: frame as unknown as Window, data, ports }),
),
} as unknown as Window;
const agent = installEditingAgent(parent);
const agent = installMarkedEditingAgent(parent);
frame.postMessage = (data: unknown) =>
window.dispatchEvent(new MessageEvent("message", { source: parent, data }));
closers.push(() => agent.dispose());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import React, { act } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
// The frame's real runtime agent, serving the opaque frame from this document.
import { installEditingAgent } from "../../../../core/src/runtime/editingAgent";
import { installMarkedEditingAgent } from "../../../../core/src/runtime/editingAgent.test-helpers";
import { makeSelection, installReactActEnvironment } from "../../hooks/domSelectionTestHarness";
import { watchPreviewFrame } from "../../player/lib/bridgePlayback";
import { queryPreviewElements } from "../../player/lib/previewElements";
Expand Down Expand Up @@ -131,7 +131,7 @@ function opaqueFrame() {
new MessageEvent("message", { source: frame as unknown as Window, data, ports }),
),
} as unknown as Window;
const agent = installEditingAgent(parent);
const agent = installMarkedEditingAgent(parent);
frame.postMessage = (data: unknown) =>
window.dispatchEvent(new MessageEvent("message", { source: parent, data }));
closers.push(() => agent.dispose());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import React, { act } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
// The frame's real runtime agent, serving the opaque frame from this document.
import { installEditingAgent } from "../../../../core/src/runtime/editingAgent";
import { installMarkedEditingAgent } from "../../../../core/src/runtime/editingAgent.test-helpers";
import {
getAllPreviewTargetsFromPointer,
getPreviewTargetFromPointer,
Expand Down Expand Up @@ -106,7 +106,7 @@ function opaqueFrame(): HTMLIFrameElement {
new MessageEvent("message", { source: frame as unknown as Window, data, ports }),
),
} as unknown as Window;
const agent = installEditingAgent(parent);
const agent = installMarkedEditingAgent(parent);
frame.postMessage = (data: unknown) =>
window.dispatchEvent(new MessageEvent("message", { source: parent, data }));
closers.push(() => agent.dispose());
Expand Down
Loading
Loading