fix: Persist nested MDX heading edits (#6692)

Editing a heading inside a nested MDX template appeared in the canvas
but was lost after refreshing the Builder. Explicit line breaks in
copied headings also disappeared when text editing began, including in
Design mode outside Content Blocks.

This PR keeps Markdown block structure when serializing edits inside
nested named templates, preserves inline formatting inside headings, and
keeps existing `br` instances through text editing. Self-closing
template instances continue using their defaults.

Ref #6306

## Checklist
- [x] Reproduce the heading edit and refresh failure in the shared
project.
- [x] Add regression coverage for a heading nested through multiple
templates and verify it survives serialization and reload.
- [x] Add regression coverage for inline formatting in a self-closing
heading template; confirmed the test failed before the fix.
- [x] Preserve explicit `br` instances when entering and saving text
editing in either Builder mode; confirmed the test failed before the
fix.
- [x] Review the authoritative Content Block documentation; the existing
guidance already covers this behavior, so no documentation change is
needed.
- [x] Run the relevant tests, Builder typecheck, lint, and formatting
checks.
- [x] Review the final diff and worktree for unrelated changes.
- [x] Wait for the PR Builder compatibility endpoint before fixture
sync; fixture sync passed on Ubuntu and Windows.
- [x] Verify all GitHub checks for the latest commit.

## Verification
- Text editor interop and component tests: 21 passed.
- Builder typecheck, focused lint, formatting, and `git diff --check`
passed.
- The new line-break regression failed before the fix and passed after
it.
- Latest CI passed: Main workflow, visual regression, lint, and staging
fixtures on Ubuntu and Windows.
This commit is contained in:
Oleg Isonen authored and GitHub committed 2026-11-15 11:07:56 +01:00
1 parent ab82a5b634
commit b153fb3890
5 files changed
+290 -18

No files matched your search

+36
View File
@@ -54,6 +54,42 @@ jobs:
- name: Testing cli link command
run: pnpm --filter='./fixtures/*' --sequential run fixtures:link
- name: Wait for Builder deployment
shell: bash
run: |
node --input-type=module <<'NODE'
const url = `https://${process.env.BUILDER_HOST}/rest/cli-compatibility`;
for (let attempt = 1; attempt <= 30; attempt++) {
try {
const response = await fetch(url, {
headers: { "x-webstudio-automation": "webstudio" },
signal: AbortSignal.timeout(5_000),
});
await response.body?.cancel();
if (response.ok) {
console.log(`Builder is ready at ${url}`);
process.exit(0);
}
console.log(
`Builder returned HTTP ${response.status} (attempt ${attempt}/30)`
);
} catch (error) {
console.log(
`Builder is not reachable yet (attempt ${attempt}/30): ${error.cause?.code ?? error.message}`
);
}
if (attempt < 30) {
await new Promise((resolve) => setTimeout(resolve, 5_000));
}
}
throw new Error(`Builder did not become ready at ${url} within 5 minutes`);
NODE
- name: Testing cli sync command
shell: bash
run: |
@@ -154,6 +154,63 @@ test("convert element instances to lexical", async () => {
);
});
test("keeps explicit line break instances while editing", async () => {
const { instances } = renderData(
<ws.element ws:tag="h3" ws:id="heading">
JÄRKI <ws.element ws:tag="br" ws:id="firstBreak" />
myyntistrategian <ws.element ws:tag="br" ws:id="secondBreak" />
perustukset
</ws.element>
);
const refs: Refs = new Map();
const editor = createHeadlessEditor({ nodes: [LinkNode] });
await new Promise<void>((resolve) => {
editor.update(() => $convertToLexical(instances, "heading", refs), {
onUpdate: resolve,
});
});
expect(editor.getEditorState().read(() => $getRoot().getTextContent())).toBe(
"JÄRKI \nmyyntistrategian \nperustukset"
);
expect(
editor
.getEditorState()
.read(() =>
$convertToUpdates(
instances.get("heading")!,
refs,
new Map(),
() => "new"
)
)
).toEqual(Array.from(instances.values()));
await new Promise<void>((resolve) => {
editor.update(
() => {
$getRoot()
.getAllTextNodes()
.find((node) => node.getTextContent() === "perustukset")!
.setTextContent("new foundations");
},
{ onUpdate: resolve }
);
});
const updates = editor
.getEditorState()
.read(() =>
$convertToUpdates(instances.get("heading")!, refs, new Map(), () => "new")
);
expect(updates[0].children).toEqual([
{ type: "text", value: "JÄRKI " },
{ type: "id", value: "firstBreak" },
{ type: "text", value: "myyntistrategian " },
{ type: "id", value: "secondBreak" },
{ type: "text", value: "new foundations" },
]);
});
test("convert lexical to element instances updates", async () => {
const refs: Refs = new Map();
let nextId = 0;
@@ -113,7 +113,19 @@ const $writeUpdates = (
);
}
if ($isLineBreakNode(child)) {
instanceChildren.push({ type: "text", value: "\n" });
const id = refs.get(child.getKey());
if (id === undefined) {
instanceChildren.push({ type: "text", value: "\n" });
} else {
instanceChildren.push({ type: "id", value: id });
instancesList.push({
type: "instance",
id,
component: elementComponent,
tag: "br",
children: [],
});
}
}
if ($isLinkNode(child)) {
const { parentUpdates, formats } = wrapFormats(child);
@@ -230,6 +242,13 @@ const $writeLexical = (
continue;
}
if (instance.component === elementComponent && instance.tag === "br") {
const lineBreakNode = $createLineBreakNode();
refs.set(lineBreakNode.getKey(), instance.id);
parent.append(lineBreakNode);
continue;
}
// convert instances
const isLinkInstance =
instance.component === "RichTextLink" ||
@@ -2584,23 +2584,19 @@ export const reconcileMdxAuthoredContent = ({
}
return { ...original, props: normalizedProps, children };
}
if (expandsToAuthoredChildren) {
return {
...original,
selfClosing: false,
props: normalizedProps,
children,
mdxMode:
mode === "text" ||
(provenance.editableTextChildren && children.length > 0)
? "text"
: original.mdxMode,
};
}
return mode === "text" ||
(provenance.editableTextChildren && children.length > 0)
? { ...original, props: normalizedProps, children, mdxMode: "text" }
: { ...original, props: normalizedProps, children };
return {
...original,
...(expandsToAuthoredChildren ? { selfClosing: false } : {}),
props: normalizedProps,
children,
mdxMode:
mode === "text" ||
(provenance.editableTextChildren &&
children.length > 0 &&
getInsertedNodeMode(instance.children) === "text")
? "text"
: original.mdxMode,
};
}
const owningTemplate = templateByExpandedInstanceId.get(instanceId);
const isExpandedTemplateDescendant =
@@ -20,6 +20,7 @@ import {
} from "./mdx-materialization";
import {
materializeMdxAuthoredContent,
rebaseMdxAuthoredContent,
serializeMdxAuthoredContent,
} from "./mdx-authored-content";
import {
@@ -274,6 +275,169 @@ const getUnresolvedTemplate = (
};
describe("materializeMdxTemplates", () => {
test("persists Markdown heading edits inside nested named templates", async () => {
const data = createData();
const templates = [
{ id: "link", name: "ServiceCard", tag: "a" },
{ id: "shell", name: "CardShell", tag: "div" },
{ id: "text", name: "CardText", tag: "div" },
];
for (const template of templates) {
data.instances.set(template.id, {
...template,
type: "instance",
component: "ws:element",
children: [{ type: "text", value: "Template default" }],
});
}
data.instances.get("templates")!.children = templates.map(({ id }) => ({
type: "id",
value: id,
}));
const materialize = async (source: string) => {
const document = await parseMdxDocument({ source });
const templateMaterialization = await materializeMdxTemplates({
identity,
resolution: resolveMdxTemplates({
document,
identity,
instances: data.instances,
metas,
}),
data,
metas,
projectId: "target-project",
});
return materializeMdxAuthoredContent({
identity,
document,
templateMaterialization,
});
};
const root = await materialize(`
<ServiceCard href="/services">
<CardShell>
<CardText>
## Before
Card description
</CardText>
</CardShell>
</ServiceCard>
<CardText />
`);
const fragment = structuredClone(root.fragment);
const heading = fragment.instances.find(({ tag }) => tag === "h2");
expect(heading?.children).toEqual([{ type: "text", value: "Before" }]);
heading!.children = [{ type: "text", value: "After" }];
const next = await rebaseMdxAuthoredContent({
root,
fragment,
latest: root.document,
});
const reopened = await materialize(serializeMdxDocument(next));
expect(reopened.document.children).toMatchObject([
{
name: "ServiceCard",
children: [
{
name: "CardShell",
children: [
{
name: "CardText",
children: [
{
syntax: "markdown",
tag: "h2",
children: [{ type: "text", value: "After" }],
},
{ syntax: "markdown", tag: "p" },
],
},
],
},
],
},
{ name: "CardText", selfClosing: true, children: [] },
]);
expect(
reopened.fragment.instances.find(({ tag }) => tag === "h2")?.children
).toEqual([{ type: "text", value: "After" }]);
});
test("keeps inline formatting inside a self-closing heading template", async () => {
const data = createData();
data.instances.set("title", {
type: "instance",
id: "title",
component: "ws:element",
tag: "h2",
name: "Title",
children: [{ type: "text", value: "Bold title" }],
});
data.instances.get("templates")!.children.push({
type: "id",
value: "title",
});
const document = await parseMdxDocument({ source: "<Title />" });
const templateMaterialization = await materializeMdxTemplates({
identity,
resolution: resolveMdxTemplates({
document,
identity,
instances: data.instances,
metas,
}),
data,
metas,
projectId: "target-project",
});
const root = materializeMdxAuthoredContent({
identity,
document,
templateMaterialization,
});
const fragment = structuredClone(root.fragment);
const heading = fragment.instances.find(({ tag }) => tag === "h2")!;
heading.children = [{ type: "id", value: "strong" }];
fragment.instances.push({
type: "instance",
id: "strong",
component: "ws:element",
tag: "strong",
children: [{ type: "text", value: "Bold title" }],
});
const next = await rebaseMdxAuthoredContent({
root,
fragment,
latest: root.document,
});
const reopened = await materializeMdxAuthoredContent({
identity,
document: await parseMdxDocument({
source: serializeMdxDocument(next),
}),
templateMaterialization,
});
const reopenedHeading = reopened.fragment.instances.find(
({ tag }) => tag === "h2"
)!;
const inlineChildId = reopenedHeading.children.find(
(child) => child.type === "id"
)?.value;
expect(
reopened.fragment.instances.find(({ id }) => id === inlineChildId)?.tag
).toBe("strong");
expect(reopened.fragment.instances.map(({ tag }) => tag)).not.toContain(
"p"
);
});
test.each([
["existing source", undefined, "image", true],
["existing source, mismatched", undefined, "other-image", false],