fix(studio): group clone attribute predicates by element

This commit is contained in:
Miguel Ángel
2026-10-16 12:19:21 -04:00
parent e4fd2c71e6
commit ebb07ea502
4 changed files with 77 additions and 22 deletions
@@ -455,3 +455,33 @@ it.each(["shape", "element-1-fixed-node-2"])(
expect(view.records[1]!.files["index.html"]!.after).toBe(view.files["index.html"]);
},
);
it.each(["duplicate", "paste"] as const)(
"preserves authored dual-attribute aggregate truth through same-file %s",
async (action) => {
const view = mount({
html: "<div>unused</div>",
css: "",
width: 100,
height: 100,
warnings: [],
});
view.files["index.html"] = SOURCE.replace(
"</div></body>",
'<div id="authored" class="clip" data-start="0" data-duration="5" data-track-index="0"><style>#authored use[*|href$="-2"]{opacity:.25}</style><svg><defs><path id="other-2" d="M0 0L1 1"/><path id="shape" d="M0 0L1 1"/></defs><use role="img" href="#other-2" xlink:href="#shape"/></svg></div></div></body>',
);
view.navigate("index.html");
view.select("authored");
await cloneSelected(view, action);
for (const doc of [view.doc(), view.preview()]) {
const use = doc.getElementById("authored-2")!.querySelector("use")!;
expect(use.getAttribute("href")).toBe("#other-2-2");
expect(use.getAttribute("xlink:href")).toBe("#shape-2");
expect(matchingDeclarations(doc, use, "opacity")).toContain(".25");
expect(
matchingDeclarations(doc, doc.getElementById("authored")!.querySelector("use")!, "opacity"),
).toContain(".25");
}
expect(view.records[0]!.files["index.html"]!.after).toBe(view.files["index.html"]);
},
);
@@ -1,5 +1,9 @@
import postcss from "postcss";
import { rebindClipboardSelector, type ClipboardAttributeRewrite } from "./clipboardSelectors";
import {
clipboardNodeSelector,
rebindClipboardSelector,
type ClipboardAttributeRewrite,
} from "./clipboardSelectors";
import {
decodeAuthoredAttribute,
scanHtmlOpeningTags,
@@ -64,7 +68,7 @@ interface SourceEdit {
function attributeEdit(
attr: HtmlAttributeSpan,
renames: ReadonlyMap<string, string>,
): (SourceEdit & { reference: ClipboardAttributeRewrite }) | null {
): SourceEdit | null {
if (attr.kind !== "value") return null;
const value = decodeAuthoredAttribute(attr.value);
const rewritten = attributeValue(attr.name, value, renames);
@@ -77,7 +81,6 @@ function attributeEdit(
start: attr.valueStart,
end: attr.valueEnd,
text: attr.quote ? encoded : `"${encoded}"`,
reference: { name: attr.name, before: value, after: rewritten },
};
}
@@ -85,12 +88,21 @@ export function clipboardAttributeRewrites(
html: string,
renames: ReadonlyMap<string, string>,
): ClipboardAttributeRewrite[] {
return scanHtmlOpeningTags(html).flatMap((tag) =>
tag.attributes.flatMap((attr) => {
const edit = attributeEdit(attr, renames);
return edit ? [edit.reference] : [];
}),
);
const template = document.createElement("template");
template.innerHTML = html;
return Array.from(template.content.querySelectorAll("*")).flatMap((node) => {
const attributes = Array.from(node.attributes, (attr) => ({
name: attr.name,
before: attr.value,
after:
attr.name === "id"
? (renames.get(attr.value) ?? attr.value)
: attributeValue(attr.name, attr.value, renames),
}));
if (!attributes.some((attr) => attr.before !== attr.after)) return [];
const target = clipboardNodeSelector(node, renames);
return attributes.map((attr) => ({ ...attr, target }));
});
}
/** Rebind a clone's own references before insertion; destination styles and scripts stay untouched. */
@@ -100,14 +112,13 @@ export function rebindClipboardReferences(
): string {
if (!renames.size) return html;
const edits: SourceEdit[] = [];
const attributes: ClipboardAttributeRewrite[] = [];
const attributes = clipboardAttributeRewrites(html, renames);
const tags = scanHtmlOpeningTags(html);
for (const tag of tags)
for (const attr of tag.attributes) {
const edit = attributeEdit(attr, renames);
if (edit) {
edits.push(edit);
attributes.push(edit.reference);
}
}
for (const tag of tags) {
@@ -15,6 +15,16 @@ export interface ClipboardAttributeRewrite {
after: string;
}
export function clipboardNodeSelector(node: Element, ids: ReadonlyMap<string, string>): string {
if (node.id) return `#${escapeCssIdentifier(ids.get(node.id) ?? node.id)}`;
const siblings = Array.from(node.parentNode?.childNodes ?? [node]).filter(
(sibling): sibling is Element =>
sibling instanceof Element && sibling.localName === node.localName,
);
const part = `${node.localName}:nth-of-type(${siblings.indexOf(node) + 1})`;
return node.parentElement ? `${clipboardNodeSelector(node.parentElement, ids)} > ${part}` : part;
}
type ValuePredicate = NonNullable<ReturnType<typeof parseAttributeSelector>>;
type Predicate = ValuePredicate | NonNullable<ReturnType<typeof parseAttributeSelectorPresence>>;
const MATCHES = {
@@ -85,7 +95,17 @@ function predicateChanges(parsed: Predicate, references: readonly ClipboardAttri
attributeMatches(parsed, reference.afterName ?? reference.name) &&
valueMatches(parsed, reference.after),
);
if (before !== after) (before ? include : exclude).add(outputPredicate(parsed, group[0]!));
if (before !== after)
(before ? include : exclude).add(
outputPredicate(
parsed,
group.find(
(reference) =>
reference.before !== reference.after ||
reference.name !== (reference.afterName ?? reference.name),
) ?? group[0]!,
),
);
}
return { include, exclude };
}
@@ -1,4 +1,4 @@
import type { ClipboardAttributeRewrite } from "./clipboardSelectors";
import { clipboardNodeSelector, type ClipboardAttributeRewrite } from "./clipboardSelectors";
import {
ELEMENT_CLIPBOARD_MAX_NODES,
type ElementClipboard,
@@ -64,14 +64,6 @@ function writeAttribute(
});
}
function nodeSelector(node: Element, wrapper: Element): string {
if (node === wrapper) return `#${wrapper.id}`;
const siblings = Array.from(node.parentElement!.children).filter(
(sibling) => sibling.localName === node.localName,
);
return `${nodeSelector(node.parentElement!, wrapper)} > ${node.localName}:nth-of-type(${siblings.indexOf(node) + 1})`;
}
function copyResource(node: Element, clean: Element, attr: Attr, context: CopyContext): void {
const fragment = context.ids.get(attr.value.slice(1));
if (attr.value.startsWith("#") && fragment)
@@ -203,7 +195,9 @@ export function prepareElementClipboard(
)
.map((reference) => reference.node),
);
const targets = new Map(Array.from(changedNodes, (node) => [node, nodeSelector(node, wrapper)]));
const targets = new Map(
Array.from(changedNodes, (node) => [node, clipboardNodeSelector(node, new Map())]),
);
const writes = finalAttributes.flatMap(({ node, ...reference }) => {
const target = targets.get(node);
return target ? [{ ...reference, target }] : [];