mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-25 16:37:32 +00:00
fix(studio): a pasted element lands after its own original, never inside a script (#8489)
* fix(studio): a pasted element lands after its own original, never inside a script * fix(studio): a paste compares the anchor id instead of building a pattern from it
This commit is contained in:
@@ -12,6 +12,7 @@ import {
|
||||
hasCompositionOutsideTemplates,
|
||||
isFullHtmlDocument,
|
||||
mapStartTagsAndStyles,
|
||||
tagsOutsideCommentsAndRawText,
|
||||
parseHTMLContent,
|
||||
stripEmbeddedRuntimeScripts,
|
||||
} from "./htmlDocument.js";
|
||||
@@ -524,3 +525,22 @@ describe("insertRuntimeTag", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("tagsOutsideCommentsAndRawText", () => {
|
||||
it("lists the real tags only, never tag text inside a script, style, title or comment", () => {
|
||||
const html = `<P id="a">x</P><script>'<b data-hf-id="w">'</script><!-- <i> --><style>/* <u> */</style><br/>`;
|
||||
const tags = [...tagsOutsideCommentsAndRawText(html)].map(
|
||||
({ lowercaseName, closing, start, endAfterBracket }) =>
|
||||
`${closing ? "/" : ""}${lowercaseName}:${html.slice(start, endAfterBracket)}`,
|
||||
);
|
||||
expect(tags).toEqual([
|
||||
'p:<P id="a">',
|
||||
"/p:</P>",
|
||||
"script:<script>",
|
||||
"/script:</script>",
|
||||
"style:<style>",
|
||||
"/style:</style>",
|
||||
"br:<br/>",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -308,6 +308,27 @@ export function mapStartTagsAndStyles(
|
||||
return out + html.slice(cursor);
|
||||
}
|
||||
|
||||
export interface SourceTag {
|
||||
start: number;
|
||||
endAfterBracket: number;
|
||||
lowercaseName: string;
|
||||
closing: boolean;
|
||||
}
|
||||
|
||||
export function* tagsOutsideCommentsAndRawText(html: string): Generator<SourceTag> {
|
||||
for (const open of markupStarts(html)) {
|
||||
const closing = html.charAt(open + 1) === "/";
|
||||
const nameStart = open + (closing ? 2 : 1);
|
||||
if (!/[a-z]/i.test(html.charAt(nameStart))) continue;
|
||||
const end = findTagEnd(html, nameStart);
|
||||
if (end === -1) return;
|
||||
let nameEnd = nameStart;
|
||||
while (nameEnd < end && !isTagBoundary(html.charAt(nameEnd))) nameEnd++;
|
||||
const lowercaseName = lowerAscii(html.slice(nameStart, nameEnd));
|
||||
yield { start: open, endAfterBracket: end + 1, lowercaseName, closing };
|
||||
}
|
||||
}
|
||||
|
||||
export function findStartTags(html: string, name: string): number[] {
|
||||
const token = `<${lowerAscii(name)}`;
|
||||
const starts: number[] = [];
|
||||
|
||||
@@ -304,7 +304,8 @@ describe("pasteElementHtml", () => {
|
||||
ROOT.replace("</div>", '<p id="title" class="t">Hello <b>there</b></p></div>'),
|
||||
);
|
||||
const copied = stamped.match(/<p[^>]*id="title"[^>]*>.*?<\/p>/)![0];
|
||||
const content = pasteElementHtml(stamped, { html: copied, originSelector: "#title" });
|
||||
const content = pasteElementHtml(stamped, { html: copied, saved: true }, true);
|
||||
expect(content.indexOf("</p>") + 4).toBe(content.indexOf("\n<p"));
|
||||
const ids = hfIdsIn(content);
|
||||
expect(ids).toHaveLength(hfIdsIn(stamped).length + 2);
|
||||
expect(new Set(ids).size).toBe(ids.length);
|
||||
|
||||
@@ -195,17 +195,19 @@ const hfIdsInFile = (content: string) =>
|
||||
|
||||
export function pasteElementHtml(
|
||||
content: string,
|
||||
payload: { html: string; saved?: boolean; originSelector?: string; originSelectorIndex?: number },
|
||||
payload: { html: string; saved?: boolean },
|
||||
fromThisFile = false,
|
||||
): string {
|
||||
const reminted = remintHfIds(payload.html, new DOMParser(), hfIdsInFile(content), payload.saved);
|
||||
const parser = new DOMParser();
|
||||
const reminted = remintHfIds(payload.html, parser, hfIdsInFile(content), payload.saved);
|
||||
const deduped = deduplicateIds(reminted, collectHtmlIds(content));
|
||||
const result = insertAsSibling(
|
||||
content,
|
||||
deduped,
|
||||
payload.originSelector,
|
||||
payload.originSelectorIndex,
|
||||
);
|
||||
const anchorFromThisFile =
|
||||
fromThisFile && payload.saved
|
||||
? 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;
|
||||
}
|
||||
|
||||
@@ -376,8 +378,6 @@ export function useClipboard({
|
||||
...savedMarkupElseLive(parseSavedSource(content), live, sourceFile),
|
||||
sourceFile,
|
||||
projectId: pid ?? undefined,
|
||||
originSelector: domSelection.selector,
|
||||
originSelectorIndex: domSelection.selectorIndex,
|
||||
};
|
||||
});
|
||||
return copyFound(found, copy, showToast);
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
deduplicateIds,
|
||||
serializeClipboardPayload,
|
||||
deserializeClipboardPayload,
|
||||
insertAsSibling,
|
||||
type ClipboardPayload,
|
||||
} from "./clipboardPayload";
|
||||
|
||||
@@ -128,3 +129,34 @@ describe("serializeClipboardPayload / deserializeClipboardPayload", () => {
|
||||
expect(deserializeClipboardPayload(json)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("insertAsSibling", () => {
|
||||
const ROOT = '<div data-composition-id="main" data-hf-id="r0">';
|
||||
const PASTED = '<b data-hf-id="n1">new</b>';
|
||||
|
||||
it("places the paste right after the element the file names by that id", () => {
|
||||
const source = `${ROOT}<p data-hf-id="a1">one <i>two</i></p><p data-hf-id="a2">three</p></div>`;
|
||||
expect(insertAsSibling(source, PASTED, "a1")).toBe(
|
||||
`${ROOT}<p data-hf-id="a1">one <i>two</i></p>\n${PASTED}<p data-hf-id="a2">three</p></div>`,
|
||||
);
|
||||
});
|
||||
|
||||
it("never anchors on tag text inside a script, style or comment", () => {
|
||||
const script = `<script>const word = '<span data-hf-id="w1">' + w + "</span>";</script>`;
|
||||
const style =
|
||||
'<style>/* <div data-composition-id="x"> */</style><!-- <span data-hf-id="w1"> -->';
|
||||
const source = `${script}${style}${ROOT}<p data-hf-id="a1">one</p></div>`;
|
||||
expect(insertAsSibling(source, PASTED, "w1")).toBe(
|
||||
`${script}${style}${ROOT}${PASTED}<p data-hf-id="a1">one</p></div>`,
|
||||
);
|
||||
});
|
||||
|
||||
it("takes an anchor no element has, a pattern-like one too, as no anchor, at once", () => {
|
||||
const source = `${ROOT}${"a".repeat(5000)}!</div>`;
|
||||
const started = performance.now();
|
||||
expect(insertAsSibling(source, PASTED, "(a+)+$")).toBe(
|
||||
`${ROOT}${PASTED}${"a".repeat(5000)}!</div>`,
|
||||
);
|
||||
expect(performance.now() - started).toBeLessThan(500);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { COMPOSITION_ROOT_OPEN_TAG_RE } from "./compositionPatterns";
|
||||
import {
|
||||
tagsOutsideCommentsAndRawText,
|
||||
type SourceTag,
|
||||
} from "@hyperframes/core/compiler/html-document";
|
||||
|
||||
const CLIPBOARD_MARKER = "hyperframes-clipboard:v1";
|
||||
|
||||
@@ -26,8 +29,6 @@ export type ClipboardPayload =
|
||||
saved?: boolean;
|
||||
sourceFile: string;
|
||||
projectId?: string;
|
||||
originSelector?: string;
|
||||
originSelectorIndex?: number;
|
||||
};
|
||||
|
||||
type SerializedPayload = { _marker: string } & ClipboardPayload;
|
||||
@@ -85,119 +86,69 @@ export function deserializeClipboardPayload(json: string): ClipboardPayload | nu
|
||||
html: obj.html,
|
||||
sourceFile: obj.sourceFile,
|
||||
projectId: typeof obj.projectId === "string" ? obj.projectId : undefined,
|
||||
originSelector: typeof obj.originSelector === "string" ? obj.originSelector : undefined,
|
||||
originSelectorIndex:
|
||||
typeof obj.originSelectorIndex === "number" ? obj.originSelectorIndex : undefined,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert `newHtml` as a sibling immediately after the element matched by
|
||||
* `selector` (at `selectorIndex`) in `source`. Falls back to inserting after
|
||||
* the composition root if the selector doesn't match — so paste never silently
|
||||
* drops the content.
|
||||
*/
|
||||
// fallow-ignore-next-line complexity
|
||||
export function insertAsSibling(
|
||||
source: string,
|
||||
newHtml: string,
|
||||
selector: string | undefined,
|
||||
selectorIndex: number | undefined,
|
||||
): string {
|
||||
if (selector) {
|
||||
const idx = selectorIndex ?? 0;
|
||||
let matchCount = 0;
|
||||
const VOID_TAGS = new Set([
|
||||
"area",
|
||||
"base",
|
||||
"br",
|
||||
"col",
|
||||
"embed",
|
||||
"hr",
|
||||
"img",
|
||||
"input",
|
||||
"link",
|
||||
"meta",
|
||||
"source",
|
||||
"track",
|
||||
"wbr",
|
||||
]);
|
||||
const HF_ID_ATTRIBUTE = /\sdata-hf-id\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+))/i;
|
||||
|
||||
// Find the element by searching for its opening tag pattern.
|
||||
// For id selectors like #foo, search for id="foo".
|
||||
// For class selectors like .name-text, search for class="...name-text...".
|
||||
// For attribute selectors like [data-composition-id="x"], search literally.
|
||||
const tagText = (source: string, tag: SourceTag) => source.slice(tag.start, tag.endAfterBracket);
|
||||
const selfClosing = (source: string, tag: SourceTag) =>
|
||||
source.charAt(tag.endAfterBracket - 2) === "/";
|
||||
|
||||
let searchPattern: RegExp | null = null;
|
||||
if (selector.startsWith("#")) {
|
||||
const id = selector.slice(1);
|
||||
searchPattern = new RegExp(`<[a-z][^>]*\\bid="${id}"[^>]*>`, "gi");
|
||||
} else if (selector.startsWith(".")) {
|
||||
const cls = selector.slice(1);
|
||||
searchPattern = new RegExp(`<[a-z][^>]*\\bclass="[^"]*\\b${cls}\\b[^"]*"[^>]*>`, "gi");
|
||||
} else if (selector.startsWith("[")) {
|
||||
const inner = selector.slice(1, -1);
|
||||
searchPattern = new RegExp(`<[a-z][^>]*\\b${inner}[^>]*>`, "gi");
|
||||
}
|
||||
|
||||
if (searchPattern) {
|
||||
let match: RegExpExecArray | null;
|
||||
while ((match = searchPattern.exec(source)) !== null) {
|
||||
if (matchCount === idx) {
|
||||
const insertPos = findClosingTagPosition(source, match.index);
|
||||
if (insertPos > 0) {
|
||||
return source.slice(0, insertPos) + "\n" + newHtml + source.slice(insertPos);
|
||||
}
|
||||
}
|
||||
matchCount++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: insert after composition root opening tag (same as timeline clips)
|
||||
const rootMatch = COMPOSITION_ROOT_OPEN_TAG_RE.exec(source);
|
||||
if (rootMatch && rootMatch.index != null) {
|
||||
const insertAt = rootMatch.index + rootMatch[0].length;
|
||||
return source.slice(0, insertAt) + newHtml + source.slice(insertAt);
|
||||
}
|
||||
|
||||
return source + newHtml;
|
||||
}
|
||||
|
||||
// fallow-ignore-next-line complexity
|
||||
function findClosingTagPosition(html: string, openTagStart: number): number {
|
||||
// Find the end of the opening tag
|
||||
const openTagEnd = html.indexOf(">", openTagStart);
|
||||
if (openTagEnd < 0) return -1;
|
||||
|
||||
// Self-closing tag?
|
||||
if (html[openTagEnd - 1] === "/") return openTagEnd + 1;
|
||||
|
||||
// Extract the tag name
|
||||
const tagNameMatch = html.slice(openTagStart).match(/^<([a-z][a-z0-9]*)/i);
|
||||
if (!tagNameMatch) return -1;
|
||||
const tagName = tagNameMatch[1]!;
|
||||
|
||||
// Walk forward counting open/close tags of the same name
|
||||
let depth = 1;
|
||||
let pos = openTagEnd + 1;
|
||||
const openRe = new RegExp(`<${tagName}(?:\\s|>|/>)`, "gi");
|
||||
const closeRe = new RegExp(`</${tagName}\\s*>`, "gi");
|
||||
|
||||
while (depth > 0 && pos < html.length) {
|
||||
openRe.lastIndex = pos;
|
||||
closeRe.lastIndex = pos;
|
||||
|
||||
const nextOpen = openRe.exec(html);
|
||||
const nextClose = closeRe.exec(html);
|
||||
|
||||
if (!nextClose) return -1;
|
||||
|
||||
if (nextOpen && nextOpen.index < nextClose.index) {
|
||||
// Check if it's self-closing
|
||||
const selfCloseCheck = html.lastIndexOf("/", html.indexOf(">", nextOpen.index));
|
||||
if (selfCloseCheck > nextOpen.index) {
|
||||
pos = html.indexOf(">", nextOpen.index) + 1;
|
||||
} else {
|
||||
depth++;
|
||||
pos = html.indexOf(">", nextOpen.index) + 1;
|
||||
}
|
||||
} else {
|
||||
depth--;
|
||||
if (depth === 0) return nextClose.index + nextClose[0].length;
|
||||
pos = nextClose.index + nextClose[0].length;
|
||||
}
|
||||
/** Just past the end of the element whose start tag is `tags[at]`, or -1 when it never closes. */
|
||||
function elementEnd(source: string, tags: SourceTag[], at: number): number {
|
||||
const open = tags[at]!;
|
||||
if (VOID_TAGS.has(open.lowercaseName) || selfClosing(source, open)) return open.endAfterBracket;
|
||||
let depth = 0;
|
||||
for (const tag of tags.slice(at)) {
|
||||
if (tag.lowercaseName !== open.lowercaseName || (!tag.closing && selfClosing(source, tag)))
|
||||
continue;
|
||||
depth += tag.closing ? -1 : 1;
|
||||
if (depth === 0) return tag.endAfterBracket;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert `newHtml` right after the element whose `data-hf-id` is `anchorHfId`, else just inside the composition
|
||||
* root, else at the end. Only real tags count: text inside a script, style or comment never anchors it.
|
||||
*/
|
||||
export function insertAsSibling(source: string, newHtml: string, anchorHfId?: string): string {
|
||||
const tags = [...tagsOutsideCommentsAndRawText(source)];
|
||||
if (anchorHfId) {
|
||||
const hfIdOf = (tag: SourceTag) => {
|
||||
const match = HF_ID_ATTRIBUTE.exec(tagText(source, tag));
|
||||
return match && (match[1] ?? match[2] ?? match[3]);
|
||||
};
|
||||
const at = tags.findIndex((tag) => !tag.closing && hfIdOf(tag) === anchorHfId);
|
||||
const end = at < 0 ? -1 : elementEnd(source, tags, at);
|
||||
if (end > 0) return source.slice(0, end) + "\n" + newHtml + source.slice(end);
|
||||
}
|
||||
const root = tags.find(
|
||||
(tag) => !tag.closing && /\sdata-composition-id\s*=/i.test(tagText(source, tag)),
|
||||
);
|
||||
return root
|
||||
? 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="([^"]+)"/;
|
||||
|
||||
Reference in New Issue
Block a user