Skip to content

Commit dd7378b

Browse files
authored
fix(sdk): keep <br> line breaks editable and uncorrupted in setText (#2742)
A `<br>` is a void element but `resolveSingleChildTextTarget` treated a lone `<br>` child as the element's text target. So `getOwnText(<h1>A<br>B</h1>)` read the `<br>`'s (empty) textContent → `text: null`, which consumers surface as "not editable", and `setOwnText` wrote into the `<br>`, corrupting it (serialized as invalid `</br>`). Exclude void elements from the single-child text target; read `<br>` as "\n"; and rebuild the text/`<br>` run from the newline-separated value on write, reusing existing `<br>` nodes so their identity (data-hf-id) survives an in-place edit.
1 parent 222aec4 commit dd7378b

2 files changed

Lines changed: 112 additions & 2 deletions

File tree

‎packages/sdk/src/engine/model.ts‎

Lines changed: 56 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -302,18 +302,55 @@ function isHTMLElementTarget(el: Element): boolean {
302302
return "style" in el;
303303
}
304304

305+
// Void elements can't hold text, so a lone `<br>`/`<img>`/`<hr>`/… child is
306+
// never the element's text target. Treating one as such made getOwnText read
307+
// "" (→ `text: null`, surfaced as "not editable") and setOwnText write into the
308+
// void element, corrupting it — e.g. a `<br>` gained a text child and
309+
// serialized as invalid `</br>`.
310+
const VOID_TEXT_TARGET_TAGS = new Set([
311+
"AREA",
312+
"BASE",
313+
"BR",
314+
"COL",
315+
"EMBED",
316+
"HR",
317+
"IMG",
318+
"INPUT",
319+
"LINK",
320+
"META",
321+
"PARAM",
322+
"SOURCE",
323+
"TRACK",
324+
"WBR",
325+
]);
326+
327+
function isBrElement(node: Node): boolean {
328+
return node.nodeType === 1 && (node as Element).tagName === "BR";
329+
}
330+
331+
/** A flat text leaf: no element children, or only `<br>` line breaks
332+
* (e.g. `<h1>First<br>Second</h1>`). Such an element's entire content is its
333+
* own text, so setText owns it end-to-end. Vacuously true for zero children. */
334+
function isTextOrBrLeaf(el: Element): boolean {
335+
return Array.from(el.children).every((child) => child.tagName === "BR");
336+
}
337+
305338
function resolveSingleChildTextTarget(el: Element): Element | null {
306339
const inner = el.children.length === 1 ? el.firstElementChild : null;
307-
return inner && isHTMLElementTarget(inner) ? inner : null;
340+
if (!inner || !isHTMLElementTarget(inner)) return null;
341+
if (VOID_TEXT_TARGET_TAGS.has(inner.tagName)) return null;
342+
return inner;
308343
}
309344

310-
/** Read the text target used by SDK setText. */
345+
/** Read the text target used by SDK setText. `<br>` line breaks are surfaced as
346+
* "\n" so a multi-line leaf round-trips through setOwnText. */
311347
export function getOwnText(el: Element): string {
312348
const singleChild = resolveSingleChildTextTarget(el);
313349
if (singleChild) return singleChild.textContent ?? "";
314350
let text = "";
315351
el.childNodes.forEach((n) => {
316352
if (n.nodeType === 3) text += (n as Text).nodeValue ?? "";
353+
else if (isBrElement(n)) text += "\n";
317354
});
318355
return text;
319356
}
@@ -327,6 +364,23 @@ export function setOwnText(el: Element, text: string): void {
327364
}
328365

329366
const doc = el.ownerDocument;
367+
368+
// Flat text leaf (text and/or `<br>` only): rebuild the text/`<br>` run from
369+
// the "\n"-separated value — the inverse of getOwnText. Existing `<br>` nodes
370+
// are reused in order so their identity (data-hf-id, etc.) survives an edit
371+
// that keeps the line, and a new one is only minted when a line is added.
372+
// Never writes text into a `<br>`, so no `</br>` corruption.
373+
if (isTextOrBrLeaf(el)) {
374+
const spareBrs = Array.from(el.children).filter((child) => child.tagName === "BR");
375+
while (el.firstChild) el.removeChild(el.firstChild);
376+
const lines = text.split("\n");
377+
lines.forEach((line, index) => {
378+
if (index > 0) el.appendChild(spareBrs.shift() ?? doc.createElement("br"));
379+
if (line) el.appendChild(doc.createTextNode(line));
380+
});
381+
return;
382+
}
383+
330384
const children = Array.from(el.childNodes);
331385
// Track original position of the first text node so we restore there, not at firstChild.
332386
let firstTextIdx = -1;

‎packages/sdk/src/engine/mutate.test.ts‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,62 @@ describe("setText", () => {
262262
it("override-set key maps correctly", () => {
263263
expect(pathToKey("/elements/hf-title/text")).toBe("hf-title.text");
264264
});
265+
266+
// A `<br>` line break is a void element, not the element's text target. It
267+
// must not make the heading read as empty (→ non-editable) nor be corrupted
268+
// by setText. See getOwnText / setOwnText in model.ts.
269+
describe("<br> line-break leaves", () => {
270+
const brDoc = () =>
271+
parseMutable(
272+
'<div data-hf-id="hf-s" data-hf-root><h1 data-hf-id="hf-br">Centrifugal<br>Force</h1></div>',
273+
);
274+
275+
it("reads a <br>-split heading as editable text (newline-joined), not empty", () => {
276+
const parsed = brDoc();
277+
// The inverse patch value is the pre-edit text — proves getOwnText read
278+
// the heading as "Centrifugal\nForce" rather than "" (which surfaced as
279+
// `text: null` → "not editable" in the studio panel).
280+
const { inverse } = applyOp(parsed, { type: "setText", target: "hf-br", value: "x" });
281+
expect(inverse[0]).toMatchObject({ value: "Centrifugal\nForce" });
282+
});
283+
284+
it("preserves the <br> when setting text (no </br> corruption)", () => {
285+
const parsed = brDoc();
286+
applyOp(parsed, { type: "setText", target: "hf-br", value: "Centripetal\nForce" });
287+
const html = serializeDocument(parsed);
288+
expect(html).toContain("Centripetal");
289+
expect(html).toContain("Force");
290+
expect(html).toContain("<br");
291+
// The <br> must stay empty — never gains a text child.
292+
const br = parsed.document.querySelector('[data-hf-id="hf-br"] br');
293+
expect(br?.textContent).toBe("");
294+
});
295+
296+
it("drops the line break when the new text has no newline", () => {
297+
const parsed = brDoc();
298+
applyOp(parsed, { type: "setText", target: "hf-br", value: "Centrifugal Force" });
299+
const h1 = parsed.document.querySelector('[data-hf-id="hf-br"]');
300+
expect(h1?.querySelector("br")).toBeNull();
301+
expect(h1?.textContent).toBe("Centrifugal Force");
302+
});
303+
304+
it("reuses the existing <br> node so an in-place edit round-trips exactly", () => {
305+
const parsed = parseMutable(
306+
'<div data-hf-id="hf-s" data-hf-root><h1 data-hf-id="hf-br">Centrifugal<br data-hf-id="hf-x5px">Force</h1></div>',
307+
);
308+
const before = serializeDocument(parsed);
309+
// Same line count → the <br> (and its data-hf-id) is preserved, and undo
310+
// is byte-exact.
311+
const { inverse } = applyOp(parsed, {
312+
type: "setText",
313+
target: "hf-br",
314+
value: "Angular\nMomentum",
315+
});
316+
expect(serializeDocument(parsed)).toContain('<br data-hf-id="hf-x5px">');
317+
applyPatchesToDocument(parsed, inverse);
318+
expect(serializeDocument(parsed)).toBe(before);
319+
});
320+
});
265321
});
266322

267323
// ─── setAttribute ─────────────────────────────────────────────────────────────

0 commit comments

Comments
 (0)