diff --git a/packages/core/src/compiler/htmlDocument.test.ts b/packages/core/src/compiler/htmlDocument.test.ts index fa73321984..bbaacc22af 100644 --- a/packages/core/src/compiler/htmlDocument.test.ts +++ b/packages/core/src/compiler/htmlDocument.test.ts @@ -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 = `

x


`; + const tags = [...tagsOutsideCommentsAndRawText(html)].map( + ({ lowercaseName, closing, start, endAfterBracket }) => + `${closing ? "/" : ""}${lowercaseName}:${html.slice(start, endAfterBracket)}`, + ); + expect(tags).toEqual([ + 'p:

', + "/p:

", + "script:", + "style:", + "br:
", + ]); + }); +}); diff --git a/packages/core/src/compiler/htmlDocument.ts b/packages/core/src/compiler/htmlDocument.ts index 242034122c..2bca064612 100644 --- a/packages/core/src/compiler/htmlDocument.ts +++ b/packages/core/src/compiler/htmlDocument.ts @@ -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 { + 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[] = []; diff --git a/packages/studio/src/hooks/useClipboard.test.ts b/packages/studio/src/hooks/useClipboard.test.ts index 123721a574..b3d4e2087b 100644 --- a/packages/studio/src/hooks/useClipboard.test.ts +++ b/packages/studio/src/hooks/useClipboard.test.ts @@ -304,7 +304,8 @@ describe("pasteElementHtml", () => { ROOT.replace("", '

Hello there

'), ); const copied = stamped.match(/]*id="title"[^>]*>.*?<\/p>/)![0]; - const content = pasteElementHtml(stamped, { html: copied, originSelector: "#title" }); + const content = pasteElementHtml(stamped, { html: copied, saved: true }, true); + expect(content.indexOf("

") + 4).toBe(content.indexOf("\n 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); diff --git a/packages/studio/src/utils/clipboardPayload.test.ts b/packages/studio/src/utils/clipboardPayload.test.ts index d677328bf7..8801b0ce31 100644 --- a/packages/studio/src/utils/clipboardPayload.test.ts +++ b/packages/studio/src/utils/clipboardPayload.test.ts @@ -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 = '
'; + const PASTED = 'new'; + + it("places the paste right after the element the file names by that id", () => { + const source = `${ROOT}

one two

three

`; + expect(insertAsSibling(source, PASTED, "a1")).toBe( + `${ROOT}

one two

\n${PASTED}

three

`, + ); + }); + + it("never anchors on tag text inside a script, style or comment", () => { + const script = ``; + const style = + ''; + const source = `${script}${style}${ROOT}

one

`; + expect(insertAsSibling(source, PASTED, "w1")).toBe( + `${script}${style}${ROOT}${PASTED}

one

`, + ); + }); + + it("takes an anchor no element has, a pattern-like one too, as no anchor, at once", () => { + const source = `${ROOT}${"a".repeat(5000)}!`; + const started = performance.now(); + expect(insertAsSibling(source, PASTED, "(a+)+$")).toBe( + `${ROOT}${PASTED}${"a".repeat(5000)}!`, + ); + expect(performance.now() - started).toBeLessThan(500); + }); +}); diff --git a/packages/studio/src/utils/clipboardPayload.ts b/packages/studio/src/utils/clipboardPayload.ts index 227505d1ee..fef60cc4dd 100644 --- a/packages/studio/src/utils/clipboardPayload.ts +++ b/packages/studio/src/utils/clipboardPayload.ts @@ -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(``, "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="([^"]+)"/;