fix(studio): paste and duplicate check the file they write, after every edit to it (#8519)

* test(studio): a paste writes only the markup it checked, comments included

* fix(studio): paste and duplicate check the file they write, after every edit to it

* test(studio): the paste check reads the saved copy's values and the file's parsed ids

* fix(studio): the paste check allows the copy as saved in the file, matched by its values

* fix(studio): a copied look rule is skipped only when it holds a tag opener

* test(studio): a paste is checked as a tree, as the preview server serves the file

* fix(studio): the paste check compares whole copies in the file as the preview serves it

* test(studio): a batch paste compares each copy only with its own candidates

* perf(studio): the paste check finds each copy by its signature, not by scanning the file
This commit is contained in:
Miguel Ángel
2026-11-22 17:03:38 +00:00
committed by GitHub
parent 886f609c43
commit bd7a8402db
9 changed files with 542 additions and 176 deletions
@@ -8,6 +8,7 @@ import { usePlayerStore, type TimelineElement } from "../player";
import type { DomEditSelection } from "../components/editor/domEditing";
import { sealedPreviewFrame } from "../player/lib/sealedPreviewFrame.test-helpers";
import { setCompositionSourceMap } from "../components/editor/domEditingDom";
import { parseHTMLContent } from "@hyperframes/core/compiler/html-document";
(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -178,6 +179,75 @@ it("pastes a sealed preview's own element only when its markup runs no code", as
}
});
// The sealed path to the writes useClipboard.written.test.ts fails main on; jsdom keeps CSS escapes, so this one holds.
it("writes no running code when a sealed preview's own element hides markup in a comment", async () => {
const hidden = [
'<div id="made" class="clip">Made<!-- x -- data-hf-id="1"><img src=x onerror=f()></div>',
'<div id="made" class="clip"><b id="title">Made</b>' +
'<!-- <style>#title{content:"\\2d\\2d\\3e"}</style><img src=x onerror=f()> --></div>',
];
for (const markup of hidden) {
const selection = {
id: "made",
selector: "#made",
sourceFile: "index.html",
} as DomEditSelection;
const { clipboard, writes } = sealedClipboard(
selection,
markup,
SAVED.replace("<body>", "<head><style>#title{color:red}</style></head><body>"),
);
expect(clipboard().handleCopy()).toBe(true);
await clipboard().handlePaste();
for (const written of writes) {
const parsed = new DOMParser().parseFromString(written, "text/html");
const handlers = Array.from(parsed.querySelectorAll("*")).flatMap((el) =>
el.getAttributeNames().filter((name) => name.startsWith("on")),
);
expect(handlers).toEqual([]);
}
act(() => root?.unmount());
root = null;
}
});
/** Handlers in a written file, read as saved and as the preview server serves it. */
function handlersServed(written: string): string[] {
return [written, parseHTMLContent(written).toString()].flatMap((html) =>
Array.from(new DOMParser().parseFromString(html, "text/html").querySelectorAll("*")).flatMap(
(el) => el.getAttributeNames().filter((name) => name.startsWith("on")),
),
);
}
// fails without the fix: a comment in an svg <title> passed the check, and the server's parser serves it as markup.
it("writes nothing the server serves as running code, from the live copy or a saved one", async () => {
const svg = "<svg><title><!-- </title><img src=x onerror=f()> --></title></svg>";
const live = sealedClipboard(
{ id: "made", selector: "#made", sourceFile: "index.html" } as DomEditSelection,
`<div id="made" class="clip">${svg}</div>`,
);
expect(live.clipboard().handleCopy()).toBe(true);
await live.clipboard().handlePaste();
for (const file of live.writes) expect(handlersServed(file)).toEqual([]);
act(() => root?.unmount());
root = null;
setCompositionSourceMap(new Map([["recv", "compositions/recv.html"]]));
const received = `<!doctype html><html><body><div data-composition-id="recv" data-start="0" data-duration="5">
<div id="go" class="clip" data-start="1" data-duration="1" data-track-index="2">${svg}</div>
</div></body></html>`;
const saved = sealedClipboard(
{ id: "go", selector: "#go", sourceFile: "compositions/recv.html" } as DomEditSelection,
`<div data-composition-file="compositions/recv.html"><div id="go" class="clip">${svg}</div></div>`,
SAVED,
{ "compositions/recv.html": received },
);
expect(saved.clipboard().handleCopy()).toBe(true);
await saved.clipboard().handlePaste();
for (const file of saved.writes) expect(handlersServed(file)).toEqual([]);
});
// fails without the fix: markup the copy found in another file was taken as saved and pasted unchecked.
it("checks a saved element read from another file before pasting it into this one", async () => {
const received = `<!doctype html><html><body><div data-composition-id="recv" data-start="0" data-duration="5">
@@ -215,20 +215,17 @@ describe("pasteTimelineClips", () => {
expect(hfIdsIn(content)).toHaveLength(1);
});
it("still strips data-hf-id from bare text with no element root", () => {
it("refuses bare text with no element root", () => {
const noRoot: TimelineClipboardClip = {
html: 'text mentioning data-hf-id="hf-leak" with no tag at all',
start: 0,
duration: 1,
track: 0,
};
const { content } = pasteTimelineClips(ROOT, [noRoot], 0, []);
expect(content).not.toContain("data-hf-id");
expect(() => pasteTimelineClips(ROOT, [noRoot], 0, [])).toThrow(/^Couldn't paste/);
});
it("still strips data-hf-id from a tag the HTML parser hoists out of body (e.g. title)", () => {
// A <title> never reaches DOMParser's body, so remintHfIds's DOM walk sees
// no root element here -- this exercises the regex fallback, not the walk.
it("gives a tag a document would hoist out of body (e.g. title) a fresh data-hf-id, never the copied one", () => {
// Only an in-file copy gets that far: from anywhere else a <title> is refused.
const hoisted: TimelineClipboardClip = {
html: '<title data-hf-id="hf-leak">x</title>',
@@ -238,7 +235,7 @@ describe("pasteTimelineClips", () => {
track: 0,
};
const { content } = pasteTimelineClips(ROOT, [hoisted], 0, [], true, "index.html");
expect(content).not.toContain("data-hf-id");
expect(content).not.toContain("hf-leak");
expect(() => pasteTimelineClips(ROOT, [{ ...hoisted, readFrom: null }], 0, [])).toThrow(
/^Couldn't paste/,
);
+42 -89
View File
@@ -1,5 +1,4 @@
import { useCallback, useRef } from "react";
import { EXCLUDED_TAGS, mintHfId, walkCompositionDescendants } from "@hyperframes/parsers/hf-ids";
import type { TimelineElement } from "../player";
import { usePlayerStore } from "../player";
import { toAuthoredStart } from "../player/store/timelineElement";
@@ -7,13 +6,10 @@ import type { DomEditSelection } from "../components/editor/domEditing";
import {
type ClipboardPayload,
type TimelineClipboardClip,
ID_ATTR_RE,
deduplicateIds,
insertAsSibling,
} from "../utils/clipboardPayload";
import { carryLook, renamedIds } from "../utils/clipboardLook";
import { collectHtmlIds } from "../utils/studioHelpers";
import { insertTimelineAssetIntoSource, writtenTrackIndex } from "../utils/timelineAssetDrop";
import { carryLook } from "../utils/clipboardLook";
import { placeUnderCompositionRoot, writtenTrackIndex } from "../utils/timelineAssetDrop";
import { extendRootDurationInSource } from "../utils/rootDuration";
import { saveProjectFilesWithHistory } from "../utils/studioFileHistory";
import { formatTimelineAttributeNumber } from "../player/components/timelineEditing";
@@ -29,7 +25,7 @@ import {
savedMarkupElseLive,
} from "../utils/authoredSource";
import { serializeStudioFileMutations } from "../utils/studioFileMutationCoordinator";
import { copiedFile, refuseUnlistedMarkup } from "../utils/clipboardMarkup";
import { copiedFile, idsInFile, prepareCopy, refuseAddedMarkup } from "../utils/clipboardMarkup";
import { knownCompositionFile } from "../components/editor/domEditingDom";
type InPlace = { inPlace?: boolean };
@@ -159,61 +155,28 @@ export function resolveFreeTrack(preferred: PlacedClip, taken: readonly PlacedCl
return maxTrack + 1;
}
/** Gives a clone's root and every descendant a fresh data-hf-id, clear of `taken`. Minted here,
* inside the edit, or the server stamps them on the next preview load, behind undo's back.
* DOMParser, not a regex, so a `>` inside an attribute value can't defeat it. */
function remintHfIds(
html: string,
parser: DOMParser,
taken: Set<string>,
check: (doc: Document) => void,
): string {
const doc = parser.parseFromString(html, "text/html");
check(doc);
const root = doc.body.firstElementChild;
if (!root) {
// A tag the HTML parser hoists out of <body> (title/meta/style/base/link)
// never reaches the walk above — fall back to a direct strip so
// data-hf-id still can't survive, even though no real clip root is one
// of these tags today.
return html.replace(/\sdata-hf-id=("[^"]*"|'[^']*')/g, "");
}
const elements = [root];
walkCompositionDescendants(root, (el) => elements.push(el));
for (const el of elements) {
if (EXCLUDED_TAGS.has(el.tagName.toLowerCase())) el.removeAttribute("data-hf-id");
else el.setAttribute("data-hf-id", mintHfId(el, taken));
}
return root.outerHTML;
}
const HF_ID_ATTR_RE = /\bdata-hf-id\s*=\s*["']?([^"'\s>]+)/gi;
const hfIdsInFile = (content: string) =>
new Set(Array.from(content.matchAll(HF_ID_ATTR_RE), (match) => match[1]));
export function pasteElementHtml(
content: string,
payload: { html: string; readFrom?: string | null },
fromThisFile = false,
writeTo: string | null = null,
): string {
const parser = new DOMParser();
const check = (doc: Document) => refuseUnlistedMarkup(doc, payload.readFrom, writeTo);
const reminted = remintHfIds(payload.html, parser, hfIdsInFile(content), check);
const deduped = deduplicateIds(reminted, collectHtmlIds(content));
const anchorFromThisFile =
fromThisFile && !!payload.readFrom && payload.readFrom === writeTo
? parser
.parseFromString(payload.html, "text/html")
.body.firstElementChild?.getAttribute("data-hf-id")
: null;
const result = insertAsSibling(content, deduped, anchorFromThisFile ?? undefined);
return fromThisFile ? carryLook(result, renamedIds(reminted, deduped), 0) : result;
const taken = idsInFile(content);
const copy = prepareCopy(payload.html, taken.hfIds, taken.ids);
const fromItsFile = fromThisFile && !!payload.readFrom && payload.readFrom === writeTo;
const inserted = insertAsSibling(
content,
copy.html,
(fromItsFile && copy.originalHfId) || undefined,
);
const result = fromThisFile ? carryLook(inserted, copy.renames, 0) : inserted;
refuseAddedMarkup(content, result, [{ html: copy.html, readFrom: payload.readFrom }], writeTo);
return result;
}
/** Shared insertion path for paste and duplicate, anchored at the playhead or the selection's end. Returns the
* final ids so the caller can select what it placed, and the furthest end any clip lands at so it can grow the
* root duration to cover it. `fromThisFile`: the clips came from `content`, so a renamed copy takes its
* final ids so the caller can select what it placed; the root's data-duration grows to the furthest end, since a
* clip past it never plays or exports. `fromThisFile`: the clips came from `content`, so a renamed copy takes its
* original's look. */
export function pasteTimelineClips(
content: string,
@@ -224,22 +187,14 @@ export function pasteTimelineClips(
writeTo: string | null = null,
): { content: string; ids: string[]; requiredEnd: number } {
const groupMinStart = Math.min(...clips.map((c) => c.start));
let existingIds = collectHtmlIds(content);
const taken: PlacedClip[] = liveElements.map((el) => ({
track: writtenTrackIndex(el.authoredTrack ?? el.track),
start: el.start,
duration: el.duration,
}));
const ids: string[] = [];
let result = content;
const { hfIds: takenHfIds, ids: takenIds } = idsInFile(content);
let requiredEnd = 0;
const domParser = new DOMParser();
const takenHfIds = hfIdsInFile(content);
for (const clip of clips) {
const check = (doc: Document) => refuseUnlistedMarkup(doc, clip.readFrom, writeTo);
const reminted = remintHfIds(clip.html, domParser, takenHfIds, check);
const deduped = deduplicateIds(reminted, existingIds);
existingIds = existingIds.concat(collectHtmlIds(deduped));
const placed = clips.map((clip) => {
const newStart = anchorTime + (clip.start - groupMinStart);
const newTrack = resolveFreeTrack(
{ track: writtenTrackIndex(clip.track), start: newStart, duration: clip.duration },
@@ -247,27 +202,28 @@ export function pasteTimelineClips(
);
taken.push({ track: newTrack, start: newStart, duration: clip.duration });
requiredEnd = Math.max(requiredEnd, newStart + clip.duration);
// Only rewrite the outermost opening tag. The non-global regex matches
// the first occurrence, which is always in the root tag since outerHTML
// starts with it. Nested clips keep their own timing and track.
const rootTagEnd = deduped.indexOf(">");
const rootTag = rootTagEnd >= 0 ? deduped.slice(0, rootTagEnd + 1) : deduped;
const patchedRootTag = rootTag
.replace(/data-start="[^"]*"/, `data-start="${formatTimelineAttributeNumber(newStart)}"`)
.replace(/data-track-index="[^"]*"/, `data-track-index="${newTrack}"`);
const withPatched = patchedRootTag + deduped.slice(rootTagEnd + 1);
check(domParser.parseFromString(withPatched, "text/html"));
result = insertTimelineAssetIntoSource(result, withPatched);
if (fromThisFile) {
const authored = Number(rootTag.match(/data-start="([^"]*)"/)?.[1]);
const authoredStart = Number.isFinite(authored) ? authored : clip.start;
result = carryLook(result, renamedIds(reminted, deduped), newStart - authoredStart);
}
const id = patchedRootTag.match(ID_ATTR_RE)?.[1];
if (id) ids.push(id);
}
let authoredStart = clip.start;
// Only the root moves: nested clips keep their own timing and track.
const copy = prepareCopy(clip.html, takenHfIds, takenIds, (root) => {
const authored = Number(root.getAttribute("data-start"));
if (root.hasAttribute("data-start") && Number.isFinite(authored)) authoredStart = authored;
if (root.hasAttribute("data-start"))
root.setAttribute("data-start", formatTimelineAttributeNumber(newStart));
if (root.hasAttribute("data-track-index"))
root.setAttribute("data-track-index", String(newTrack));
});
return { copy, readFrom: clip.readFrom, delta: newStart - authoredStart };
});
const base = extendRootDurationInSource(content, requiredEnd);
let result = base;
const written = placed.map(({ copy, readFrom, delta }) => {
const { insertAt, written: html } = placeUnderCompositionRoot(result, copy.html);
result = result.slice(0, insertAt) + html + result.slice(insertAt);
if (fromThisFile) result = carryLook(result, copy.renames, delta);
return { html, readFrom };
});
refuseAddedMarkup(base, result, written, writeTo);
const ids = placed.flatMap(({ copy }) => copy.root.getAttribute("id") ?? []);
return { content: result, ids, requiredEnd };
}
@@ -443,10 +399,7 @@ export function useClipboard({
writeTo,
);
pastedIds = pasted.ids;
// A clip pasted past the current composition end would exist in the
// file but never appear on the timeline or in playback/export (the
// root's data-duration is what actually bounds the render).
return extendRootDurationInSource(pasted.content, pasted.requiredEnd);
return pasted.content;
};
const { label, toast } = pasteWords(payload);
@@ -519,7 +472,7 @@ export function useClipboard({
targetPath,
);
ids = pasted.ids;
return extendRootDurationInSource(pasted.content, pasted.requiredEnd);
return pasted.content;
};
await saveProjectFilesWithHistory({
@@ -0,0 +1,238 @@
// @vitest-environment jsdom
import { describe, expect, it, vi } from "vitest";
import { pasteElementHtml, pasteTimelineClips } from "./useClipboard";
import { parseHTMLContent } from "@hyperframes/core/compiler/html-document";
import { prepareCopy, refuseAddedMarkup } from "../utils/clipboardMarkup";
const FILE = `<!doctype html><html><head><style>
#card { color: red; }
</style></head><body><div id="root" data-composition-id="root" data-start="0" data-duration="10">
<div id="card" class="clip" data-start="0" data-duration="2" data-track-index="0">Card</div>
</div></body></html>`;
/** Every handler in `html` as saved and as the preview server serves it: what no paste may add. */
function runningCode(html: string): string[] {
return [html, parseHTMLContent(html).toString()].flatMap(handlersIn);
}
function handlersIn(html: string): string[] {
const doc = new DOMParser().parseFromString(html, "text/html");
return Array.from(doc.querySelectorAll("*")).flatMap((el) =>
el
.getAttributeNames()
.filter((name) => name.toLowerCase().startsWith("on"))
.map((name) => `${el.localName}[${name}]`),
);
}
/** The paste's own file, or nothing when it was refused. */
function written(paste: () => string): string {
try {
return paste();
} catch (error) {
expect(String(error)).toMatch(/Couldn't paste/);
return FILE;
}
}
// fails without the fix: a comment that loses its data-hf-id text after the check closes early, and what followed it
// in the comment is written as markup.
describe("markup a paste writes is the markup it checked", () => {
const SPLIT_COMMENTS = ['"', "'"].flatMap((q) => [
`<!-- x -- data-hf-id=${q}1${q}><img src=x onerror=f()>`,
`<body><!-- x -- data-hf-id=${q}1${q}><img src=x onerror=f()></body>`,
`<html><body><!-- x -- data-hf-id=${q}1${q}><img src=x onerror=f()></body></html>`,
`<html><head><!-- x -- data-hf-id=${q}1${q}><img src=x onerror=f()></head></html>`,
]);
it.each(SPLIT_COMMENTS)("writes no running code for %s", (html) => {
const file = written(() =>
pasteElementHtml(FILE, { html, readFrom: null }, false, "index.html"),
);
expect(runningCode(file)).toEqual([]);
});
it.each(SPLIT_COMMENTS)("writes no running code for a clip of %s", (html) => {
const file = written(
() =>
pasteTimelineClips(
FILE,
[{ html, readFrom: null, start: 0, duration: 1, track: 1 }],
0,
[],
false,
"index.html",
).content,
);
expect(runningCode(file)).toEqual([]);
});
});
// fails without the fix: the look copy found <style> text inside a comment and wrote a rule that closed the comment.
describe("the look a copy carries adds no markup", () => {
const COMMENTED_STYLE =
'<div id="card" class="clip" data-start="0" data-duration="2" data-track-index="1">Copy' +
'<!-- <style>#card{content:"\\2d\\2d\\3e"}</style><img src=x onerror=f()> --></div>';
it("writes no running code when an element is pasted into its own file", () => {
const file = written(() =>
pasteElementHtml(FILE, { html: COMMENTED_STYLE, readFrom: null }, true, "index.html"),
);
expect(runningCode(file)).toEqual([]);
});
it("writes no running code when a clip is duplicated in its own file", () => {
const clip = { html: COMMENTED_STYLE, readFrom: null, start: 0, duration: 2, track: 1 };
const file = written(() => pasteTimelineClips(FILE, [clip], 2, [], true, "index.html").content);
expect(runningCode(file)).toEqual([]);
});
it("still gives a pasted copy its original's look", () => {
const html =
'<div id="card" class="clip" data-start="0" data-duration="2" data-track-index="1">Copy</div>';
const file = pasteElementHtml(FILE, { html, readFrom: "index.html" }, true, "index.html");
expect(file).toMatch(/#card-2\s*\{\s*color: red;?\s*\}/);
});
});
describe("prepareCopy", () => {
it("renames each taken id on the copy's elements and leaves every other attribute as it was", () => {
const html =
'<div id="hero" data-composition-id="hero"><p id="hero-2" data-id="hero">x</p><p id="free">y</p></div>';
const copy = prepareCopy(html, new Set(), new Set(["hero", "hero-2"]));
expect(copy.root.getAttribute("id")).toBe("hero-3");
expect(copy.root.getAttribute("data-composition-id")).toBe("hero");
expect(copy.html).toContain('id="hero-2-2" data-id="hero"');
expect(copy.html).toContain('id="free"');
expect([...copy.renames]).toEqual([
["hero", "hero-3"],
["hero-2", "hero-2-2"],
]);
});
});
// fails without the fix: the check compared attribute names only and ran the allowlist on the copy, not on the file.
describe("the final check reads what the saved file holds", () => {
const copy = '<a id="go" href="next.html" data-hf-id="hf-go">Go</a>';
const before = FILE;
const inserted = (html: string) => before.replace('<div id="card"', `${html}\n<div id="card"`);
it("refuses a saved copy whose link differs from the copy that was checked", () => {
const after = inserted('<a id="go" href="javascript:alert(1)" data-hf-id="hf-go">Go</a>');
expect(() =>
refuseAddedMarkup(before, after, [{ html: copy, readFrom: null }], "index.html"),
).toThrow(/Couldn't paste/);
});
it("refuses a changed link even for a copy Studio read from this very file", () => {
const after = inserted('<a id="go" href="other.html" data-hf-id="hf-go">Go</a>');
expect(() =>
refuseAddedMarkup(before, after, [{ html: copy, readFrom: "index.html" }], "index.html"),
).toThrow(/Couldn't paste/);
});
it("refuses a saved copy whose elements moved to other parents in the same order", () => {
const nested = '<div id="w"><section id="s"><p id="cap">Caption</p></section></div>';
const after = inserted('<div id="w"><section id="s"></section><p id="cap">Caption</p></div>');
expect(() =>
refuseAddedMarkup(before, after, [{ html: nested, readFrom: "index.html" }], "index.html"),
).toThrow(/Couldn't paste/);
});
it("accepts the saved copy when it is the copy that was checked", () => {
expect(() =>
refuseAddedMarkup(before, inserted(copy), [{ html: copy, readFrom: null }], "index.html"),
).not.toThrow();
});
});
// fails without the fix: the file's ids were read as raw text, so an entity-escaped id never matched the copy's.
it("renames a pasted id the file already holds written with entities", () => {
const file = FILE.replace('<div id="card"', '<span id="left&amp;right">L</span>\n<div id="card"');
const pasted = pasteElementHtml(
file,
{ html: '<span id="left&amp;right">R</span>', readFrom: null },
false,
"index.html",
);
const ids = Array.from(
new DOMParser().parseFromString(pasted, "text/html").querySelectorAll("span"),
(el) => el.id,
);
expect(ids.sort()).toEqual(["left&right", "left&right-2"]);
});
// fails without the fix: an svg element named template has no template content, and reading the file's ids threw.
it("pastes into a file holding an svg element named template", () => {
const file = FILE.replace(
'<div id="card"',
'<svg><template id="t"></template></svg>\n<div id="card"',
);
const pasted = pasteElementHtml(
file,
{ html: '<span id="new">N</span>', readFrom: null },
false,
"index.html",
);
expect(pasted).toContain('<span id="new"');
});
it("pastes a clip whose markup spans lines, indented under the root as written", () => {
const html =
'<div id="multi" class="clip" data-start="0" data-duration="1" data-track-index="1">\n <p title="a\nb">x</p>\n</div>';
const { content } = pasteTimelineClips(
FILE,
[{ html, readFrom: null, start: 0, duration: 1, track: 1 }],
0,
[],
false,
"index.html",
);
expect(content).toContain('id="multi"');
});
// fails without the fix: the check read a comment in an svg <title> as a comment, and the preview server's parser
// ends the title inside it, serving what follows as markup.
describe("a paste is checked as the preview server serves the file", () => {
const svgClip =
'<div id="icon" class="clip" data-start="0" data-duration="1" data-track-index="1">' +
"<svg><title><!-- </title><img src=x onerror=f()> --></title></svg></div>";
it.each([null, "compositions/recv.html", "index.html"])(
"as an element read from %s",
(readFrom) => {
const file = written(() =>
pasteElementHtml(FILE, { html: svgClip, readFrom }, false, "index.html"),
);
expect(runningCode(file)).toEqual([]);
},
);
it.each([null, "compositions/recv.html", "index.html"])("as a clip read from %s", (readFrom) => {
const clip = { html: svgClip, readFrom, start: 0, duration: 1, track: 1 };
const file = written(() => pasteTimelineClips(FILE, [clip], 0, [], true, "index.html").content);
expect(runningCode(file)).toEqual([]);
});
it("still pastes an svg whose title is plain text", () => {
const icon =
'<svg viewBox="0 0 4 4"><title>Icon &lt;/title&gt;</title><circle r="2"></circle></svg>';
const file = pasteElementHtml(FILE, { html: icon, readFrom: null }, false, "index.html");
expect(file).toMatch(/<title [^>]*>Icon &lt;\/title&gt;<\/title><circle /);
});
});
// fails without the fix: each copy was compared with every element of the file, so a batch paste took seconds.
it("compares each pasted copy with only the elements that could be it", () => {
const clips = Array.from({ length: 60 }, (_, i) => ({
html: `<div id="c${i}" class="clip" data-start="0" data-duration="1" data-track-index="1"><span>${i}</span></div>`,
readFrom: null,
start: i,
duration: 1,
track: 1,
}));
const compared = vi.spyOn(Node.prototype, "isEqualNode");
pasteTimelineClips(FILE, clips, 0, [], false, "index.html");
expect(compared.mock.calls.length).toBeLessThanOrEqual(clips.length * 2);
compared.mockRestore();
});
+31 -28
View File
@@ -1,26 +1,10 @@
import { copyAnimationsInScript } from "@hyperframes/parsers/gsap-writer-acorn";
import { ID_ATTR_RE } from "./clipboardPayload";
import { tagsOutsideCommentsAndRawText } from "@hyperframes/core/compiler/html-document";
import { escapeRegex } from "./sourcePatcher";
const ID_ATTRS = new RegExp(ID_ATTR_RE.source, "g");
// One pass over both, so a `<style>` written inside a script's text is left as script.
const BLOCKS =
/(<script\b(?![^>]*\bsrc=)[^>]*>)([\s\S]*?)(<\/script>)|(<style\b[^>]*>)([\s\S]*?)(<\/style>)/gi;
/** Each id a paste renamed (`goodbye` to `goodbye-2`), from the same markup before and after the rename. */
export function renamedIds(before: string, after: string): Map<string, string> {
const ids = (html: string) => Array.from(html.matchAll(ID_ATTRS), (match) => match[1] as string);
const renamed = ids(after);
const renames = new Map<string, string>();
ids(before).forEach((from, index) => {
const to = renamed[index];
if (to && to !== from) renames.set(from, to);
});
return renames;
}
/** Gives each renamed copy the look and motion its original has in `html`: a copy of every CSS rule keyed to
* the original's id, and of every tween on it, moved by `delta` seconds. */
* the original's id, and of every tween on it, moved by `delta` seconds. Only real <style> and inline <script>
* elements are read, found with the tag scanner, so text in a comment or another element is never touched. */
export function carryLook(
html: string,
renames: ReadonlyMap<string, string>,
@@ -28,19 +12,36 @@ export function carryLook(
): string {
let result = html;
for (const [from, to] of renames) {
result = result.replace(
BLOCKS,
(block, scriptOpen, script, scriptClose, styleOpen, css, styleClose) =>
scriptOpen !== undefined
? scriptOpen + copyAnimationsInScript(script, `#${from}`, `#${to}`, delta) + scriptClose
: styleOpen !== undefined
? styleOpen + withCopiedRules(css, from, to) + styleClose
: block,
result = editBlocks(result, (kind, text) =>
kind === "script"
? copyAnimationsInScript(text, `#${from}`, `#${to}`, delta)
: withCopiedRules(text, from, to),
);
}
return result;
}
function editBlocks(
html: string,
edit: (kind: "script" | "style", text: string) => string,
): string {
const tags = [...tagsOutsideCommentsAndRawText(html)];
let out = "";
let at = 0;
tags.forEach((tag, index) => {
const kind = tag.lowercaseName;
if (tag.closing || (kind !== "script" && kind !== "style")) return;
if (kind === "script" && /\ssrc\s*=/i.test(html.slice(tag.start, tag.endAfterBracket))) return;
const close = tags.slice(index + 1).find((t) => t.closing && t.lowercaseName === kind);
if (!close) return;
out +=
html.slice(at, tag.endAfterBracket) +
edit(kind, html.slice(tag.endAfterBracket, close.start));
at = close.start;
});
return out + html.slice(at);
}
// Top-level rules only: a rule inside @media or @supports is not copied.
function withCopiedRules(css: string, from: string, to: string): string {
const sheet = new CSSStyleSheet();
@@ -56,7 +57,9 @@ function withCopiedRules(css: string, from: string, to: string): string {
);
if (selectors.length === 0) return [];
const copied = selectors.map((selector) => selector.replace(id, `#${to}`)).join(", ");
return [`\n${indent}${copied}${rule.cssText.slice(rule.selectorText.length)}`];
const text = `${copied}${rule.cssText.slice(rule.selectorText.length)}`;
// Raw <style> text ends at "</style": a rule holding "<" is not copied.
return text.includes("<") ? [] : [`\n${indent}${text}`];
});
if (copies.length === 0) return css;
const body = css.trimEnd();
+148 -9
View File
@@ -1,6 +1,10 @@
import { parseHTMLContent } from "@hyperframes/core/compiler/html-document";
import { markupOutsideAllowlist } from "@hyperframes/core/html-attr-safety";
import { EXCLUDED_TAGS, mintHfId, walkCompositionDescendants } from "@hyperframes/parsers/hf-ids";
import { knownCompositionFile } from "../components/editor/domEditingDom";
const REFUSED = "Couldn't paste: the copied element holds markup that can't be pasted here.";
export function copiedFile(
claimed: string | undefined,
activeCompositionPath: string | null,
@@ -10,14 +14,149 @@ export function copiedFile(
throw new Error("Couldn't use this element: its file isn't one of this project's compositions.");
}
/** Every clipboard write: only markup Studio itself read from the file it writes to skips the allowlist. */
export function refuseUnlistedMarkup(
doc: Document,
readFrom: string | null | undefined,
writeTo: string | null,
): void {
if (readFrom && readFrom === writeTo) return;
if (markupOutsideAllowlist(doc.documentElement).length > 0) {
throw new Error("Couldn't paste: the copied element holds markup that can't be pasted here.");
export interface PreparedCopy {
html: string;
root: Element;
originalHfId: string | null;
renames: Map<string, string>;
}
function fragment(html: string): HTMLTemplateElement {
const template = document.createElement("template");
template.innerHTML = html;
return template;
}
/** Fresh data-hf-ids minted in the edit (else the server stamps them behind undo's back); taken ids renamed. */
export function prepareCopy(
html: string,
takenHfIds: Set<string>,
takenIds: Set<string>,
place?: (root: Element) => void,
): PreparedCopy {
const root = fragment(html).content.firstElementChild;
if (!root) throw new Error(REFUSED);
const originalHfId = root.getAttribute("data-hf-id");
const elements = [root];
walkCompositionDescendants(root, (el) => elements.push(el));
for (const el of elements) {
if (EXCLUDED_TAGS.has(el.localName)) el.removeAttribute("data-hf-id");
else el.setAttribute("data-hf-id", mintHfId(el, takenHfIds));
}
const renames = new Map<string, string>();
for (const el of [root, ...Array.from(root.querySelectorAll("[id]"))]) {
const id = el.getAttribute("id");
if (!id) continue;
if (takenIds.has(id)) {
let counter = 2;
while (takenIds.has(`${id}-${counter}`)) counter++;
el.setAttribute("id", `${id}-${counter}`);
renames.set(id, `${id}-${counter}`);
}
takenIds.add(el.getAttribute("id")!);
}
place?.(root);
return { html: root.outerHTML, root, originalHfId, renames };
}
const parsed = (html: string) => new DOMParser().parseFromString(html, "text/html");
// The page as served: the preview server and render compiler re-read a file with linkedom before a browser does.
const served = (html: string) => parsed(parseHTMLContent(html).toString());
const htmlTemplate = (node: Node): node is HTMLTemplateElement =>
node instanceof Element && node.localName === "template" && node.namespaceURI === HTML_NS;
const HTML_NS = "http://www.w3.org/1999/xhtml";
function eachElement(nodes: ParentNode, visit: (el: Element) => void): void {
for (const el of Array.from(nodes.querySelectorAll("*"))) {
visit(el);
if (htmlTemplate(el)) eachElement(el.content, visit);
}
}
const signature = (el: Element) =>
JSON.stringify([
el.namespaceURI,
el.localName,
Array.from(el.attributes, (a) => JSON.stringify([a.namespaceURI, a.name, a.value])).sort(),
]);
function subtree(root: Element): Element[] {
const elements = [root];
eachElement(root, (el) => elements.push(el));
return elements;
}
// Raw <style>/<script> text is the look copy's to extend; the allowlist reads it on the saved node.
function withoutRawText(node: Node): Node {
const clone = node.cloneNode(true) as ParentNode & Node;
const scope: Element[] = clone instanceof Element ? [clone] : [];
eachElement(clone, (el) => scope.push(el));
for (const el of scope) {
if (el.namespaceURI === HTML_NS && (el.localName === "style" || el.localName === "script"))
el.textContent = "";
}
return clone;
}
/** Equal by the DOM's own isEqualNode, template contents included, which it does not compare. */
function sameTree(a: Node, b: Node): boolean {
if (!withoutRawText(a).isEqualNode(withoutRawText(b))) return false;
const templates = (node: Node) =>
[node, ...Array.from((node as ParentNode).querySelectorAll("*"))].filter(htmlTemplate);
const left = templates(a);
const right = templates(b);
return (
left.length === right.length && left.every((t, i) => sameTree(t.content, right[i].content))
);
}
/** The file's ids and data-hf-ids as parsed values, so an id written with entities matches its copy's. */
export function idsInFile(content: string): { ids: Set<string>; hfIds: Set<string> } {
const ids = new Set<string>();
const hfIds = new Set<string>();
eachElement(parsed(content), (el) => {
const id = el.getAttribute("id");
const hfId = el.getAttribute("data-hf-id");
if (id) ids.add(id);
if (hfId) hfIds.add(hfId);
});
return { ids, hfIds };
}
/** Last step of every clipboard write: the saved file gains exactly the copies, each allowed or read here. */
export function refuseAddedMarkup(
before: string,
after: string,
copies: ReadonlyArray<{ html: string; readFrom?: string | null }>,
writeTo: string | null,
): void {
const saved = served(after);
const counts = new Map<string, number>();
const tally = (shape: string, sign: number) => counts.set(shape, (counts.get(shape) ?? 0) + sign);
const candidatesBySignatureOfMintedRoot = new Map<string, Element[]>();
eachElement(saved, (el) => {
const shape = signature(el);
tally(shape, 1);
const bucket = candidatesBySignatureOfMintedRoot.get(shape);
if (bucket) bucket.push(el);
else candidatesBySignatureOfMintedRoot.set(shape, [el]);
});
eachElement(served(before), (el) => tally(signature(el), -1));
const claimed = new Set<Element>();
for (const copy of copies) {
const expected = fragment(copy.html).content.firstElementChild;
if (!expected) throw new Error(REFUSED);
const found = (candidatesBySignatureOfMintedRoot.get(signature(expected)) ?? []).find(
(el) => subtree(el).every((e) => !claimed.has(e)) && sameTree(el, expected),
);
if (!found) throw new Error(REFUSED);
const exempt = !!copy.readFrom && copy.readFrom === writeTo;
if (!exempt && markupOutsideAllowlist(found).length > 0) throw new Error(REFUSED);
for (const el of subtree(found)) {
claimed.add(el);
tally(signature(el), -1);
}
}
if (Array.from(counts.values()).some((count) => count !== 0)) throw new Error(REFUSED);
}
@@ -1,38 +1,12 @@
// @vitest-environment node
import { describe, expect, it } from "vitest";
import {
deduplicateIds,
serializeClipboardPayload,
deserializeClipboardPayload,
insertAsSibling,
type ClipboardPayload,
} from "./clipboardPayload";
describe("deduplicateIds", () => {
it("renames ids that collide with existing ids", () => {
const html = '<div id="hero"><img id="photo" src="a.png" /></div>';
const existingIds = ["hero", "other"];
const result = deduplicateIds(html, existingIds);
expect(result).not.toContain('id="hero"');
expect(result).toContain('id="photo"');
expect(result).toMatch(/id="hero-\d+"/);
});
it("returns html unchanged when no collisions", () => {
const html = '<div id="unique"><p>hello</p></div>';
const result = deduplicateIds(html, ["other"]);
expect(result).toBe(html);
});
it("does not rewrite data-composition-id or other data-*-id attributes", () => {
const html = '<div data-composition-id="hero" data-clip-id="hero" id="hero">content</div>';
const result = deduplicateIds(html, ["hero"]);
expect(result).toContain('data-composition-id="hero"');
expect(result).toContain('data-clip-id="hero"');
expect(result).toMatch(/\sid="hero-\d+"/);
});
});
describe("serializeClipboardPayload / deserializeClipboardPayload", () => {
it("round-trips a single-clip timeline payload", () => {
const payload: ClipboardPayload = {
@@ -148,19 +148,3 @@ export function insertAsSibling(source: string, newHtml: string, anchorHfId?: st
? source.slice(0, root.endAfterBracket) + newHtml + source.slice(root.endAfterBracket)
: source + newHtml;
}
/** An `id="..."` attribute, not `data-id="..."` or similar — only matches
* when preceded by whitespace, the way every generated attribute is. */
export const ID_ATTR_RE = /(?<=\s)id="([^"]+)"/;
export function deduplicateIds(html: string, existingIds: string[]): string {
const existingSet = new Set(existingIds);
return html.replace(new RegExp(ID_ATTR_RE.source, "g"), (full, id: string) => {
if (!existingSet.has(id)) return full;
let counter = 2;
while (existingSet.has(`${id}-${counter}`)) counter++;
const newId = `${id}-${counter}`;
existingSet.add(newId);
return `id="${newId}"`;
});
}
@@ -164,6 +164,14 @@ export function setCompositionDurationToContent(
}
export function insertTimelineAssetIntoSource(source: string, assetHtml: string): string {
const { insertAt, written } = placeUnderCompositionRoot(source, assetHtml);
return `${source.slice(0, insertAt)}${written}${source.slice(insertAt)}`;
}
export function placeUnderCompositionRoot(
source: string,
assetHtml: string,
): { insertAt: number; written: string } {
const match = COMPOSITION_ROOT_OPEN_TAG_RE.exec(source);
if (!match || match.index == null) {
throw new Error("No composition root found in target source");
@@ -176,5 +184,5 @@ export function insertTimelineAssetIntoSource(source: string, assetHtml: string)
.split("\n")
.map((line, i) => (i === 0 ? line : childIndent + line))
.join("\n");
return `${source.slice(0, insertAt)}\n${childIndent}${indented}${source.slice(insertAt)}`;
return { insertAt, written: `\n${childIndent}${indented}` };
}