From 26408a274ebd653c41f48c8ba7df51223e3a1605 Mon Sep 17 00:00:00 2001 From: Oleg Isonen Date: Fri, 13 Nov 2026 00:24:41 +0000 Subject: [PATCH 1/3] fix: Open projects with cyclic page folders (#6687) Projects with a saved page-folder cycle currently fail to open. Loading now repairs the cycle in memory and keeps its folders reachable. New folder cycles are still rejected on save. Closes #6686 ## Change - Visit the root folder first to preserve existing page paths. Remove only child links that close a cycle. - Visit detached folder trees before isolated cycles. Attach a repaired tree at its top folder so its pages remain visible. - Use one shared migration for current, serialized, and legacy page data. Loading does not write to the database; a normal save persists the repaired tree. - This adds 49 net non-test lines. The folder traversal is needed because the existing asset-folder repair handles database parent links and writes to a different store. ## Checklist - [x] Add regression tests for connected, detached, and self-referencing cycles in current, serialized, and legacy data. Confirm they fail before the fix and pass after it. - [x] Confirm new cycles remain rejected on save. - [x] Import the linked project's saved pages into an isolated local Builder project and open the Pages panel. The recovered folder appears. - [x] Review Builder docs. No update is needed: page-folder controls and normal behavior do not change. - [x] Review and simplify the repair. The final helper is seven lines shorter and handles a cycle below a detached parent folder. - [ ] Complete CI review for the final commit. ## Verification - Passed: project-migrations tests, typecheck, and build; project-build page tests and typecheck; Builder load-router tests and typecheck; project build-patch tests; SDK page-schema tests; repository lint; formatting and diff checks; fixture pipeline and a later fixture build. - The linked project's saved page data has 23 pages after legacy migration and two folders, including one self-reference. A local Builder E2E opened those pages and displayed the repaired folder. Other site content was synthetic because the share token cannot export the complete build. - Fixture sync pulled an unrelated remote change into two generated files. Those changes were stashed and excluded from this PR. - The approved full `pnpm evaluations` rerun exited 1: seven agent cases passed, two failed in unrelated form or guidance checks, and baselines were missing or incompatible. No evaluation files are included. - The production project still returns HTTP 500 until this change is deployed. --- packages/project-migrations/src/pages.test.ts | 127 ++++++++++++++++++ packages/project-migrations/src/pages.ts | 61 ++++++++- 2 files changed, 182 insertions(+), 6 deletions(-) diff --git a/packages/project-migrations/src/pages.test.ts b/packages/project-migrations/src/pages.test.ts index ca8a8d1a1d..e8452272ac 100644 --- a/packages/project-migrations/src/pages.test.ts +++ b/packages/project-migrations/src/pages.test.ts @@ -119,6 +119,133 @@ test("removes orphan folder children from current pages shape", () => { ).toEqual(["home"]); }); +test.each(["serialized", "current"])( + "repairs page-folder cycles in %s saved data without changing the input", + (shape) => { + const saved = { + homePageId: "home", + rootFolderId: "root", + pages: [ + { + id: "home", + name: "Home", + path: "", + title: `"Home"`, + meta: {}, + rootInstanceId: "homeRoot", + }, + ], + folders: [ + { id: "b", name: "B", slug: "b", children: ["a"] }, + { id: "root", name: "Root", slug: "", children: ["home", "a"] }, + { id: "a", name: "A", slug: "a", children: ["b"] }, + ], + }; + const input = + shape === "current" + ? { + ...saved, + pages: new Map(saved.pages.map((page) => [page.id, page])), + folders: new Map( + saved.folders.map((folder) => [folder.id, folder]) + ), + pageTemplates: new Map(), + } + : saved; + + const recovered = migratePages(input); + + expect(recovered.folders.get("root")?.children).toEqual(["home", "a"]); + expect(recovered.folders.get("a")?.children).toEqual(["b"]); + expect(recovered.folders.get("b")?.children).toEqual([]); + expect(saved.folders[0].children).toEqual(["a"]); + expect(() => serializePages(recovered)).not.toThrow(); + } +); + +test("reattaches the root of a detached folder tree containing a cycle", () => { + const recovered = migratePages({ + homePageId: "home", + rootFolderId: "root", + pages: [ + { + id: "home", + name: "Home", + path: "", + title: `"Home"`, + meta: {}, + rootInstanceId: "homeRoot", + }, + { + id: "nested", + name: "Nested", + path: "/nested", + title: `"Nested"`, + meta: {}, + rootInstanceId: "nestedRoot", + }, + ], + folders: [ + { id: "root", name: "Root", slug: "", children: ["home"] }, + { id: "a", name: "A", slug: "a", children: ["b"] }, + { id: "b", name: "B", slug: "b", children: ["c"] }, + { id: "c", name: "C", slug: "c", children: ["b", "nested"] }, + ], + }); + + expect(recovered.folders.get("root")?.children).toEqual(["home", "a"]); + expect(recovered.folders.get("a")?.children).toEqual(["b"]); + expect(recovered.folders.get("b")?.children).toEqual(["c"]); + expect(recovered.folders.get("c")?.children).toEqual(["nested"]); + expect(recovered.pages.has("nested")).toBe(true); + expect(() => serializePages(recovered)).not.toThrow(); +}); + +test("still rejects new page-folder cycles when saving", () => { + const loaded = migratePages({ + homePageId: "home", + rootFolderId: "root", + pages: [ + { + id: "home", + name: "Home", + path: "", + title: `"Home"`, + meta: {}, + rootInstanceId: "homeRoot", + }, + ], + folders: [ + { id: "root", name: "Root", slug: "", children: ["home", "a"] }, + { id: "a", name: "A", slug: "a", children: [] }, + ], + }); + loaded.folders.get("a")?.children.push("a"); + + expect(() => serializePages(loaded)).toThrow(); +}); + +test("repairs a self-referencing folder in legacy page data", () => { + const recovered = migratePages({ + homePage: { + id: "home", + name: "Home", + path: "", + title: `"Home"`, + meta: {}, + rootInstanceId: "homeRoot", + }, + pages: [], + folders: [ + { id: "root", name: "Root", slug: "", children: ["home", "a"] }, + { id: "a", name: "A", slug: "a", children: ["a"] }, + ], + }); + + expect(recovered.folders.get("a")?.children).toEqual([]); + expect(() => serializePages(recovered)).not.toThrow(); +}); + test("serializes map pages into arrays for JSON storage", () => { expect( serializePages({ diff --git a/packages/project-migrations/src/pages.ts b/packages/project-migrations/src/pages.ts index 3d59aced45..3ecc91bdd9 100644 --- a/packages/project-migrations/src/pages.ts +++ b/packages/project-migrations/src/pages.ts @@ -104,9 +104,10 @@ const isSerializedPages = (pages: unknown): pages is MigratablePages => { ); }; -const removeOrphanFolderChildren = ( +const normalizeFolderChildren = ( pages: Map, - folders: Map + folders: Map, + rootFolderId: Folder["id"] ) => { const nextFolders = new Map(); for (const [folderId, folder] of folders) { @@ -117,6 +118,49 @@ const removeOrphanFolderChildren = ( ), }); } + + const visiting = new Set(); + const visited = new Set(); + const visit = (folderId: Folder["id"]): boolean => { + const folder = nextFolders.get(folderId); + if (folder === undefined || visited.has(folderId)) { + return false; + } + visiting.add(folderId); + let repaired = false; + const children = folder.children.filter((childId) => { + if (nextFolders.has(childId) === false) { + return true; + } + if (visiting.has(childId)) { + repaired = true; + return false; + } + repaired = visit(childId) || repaired; + return true; + }); + nextFolders.set(folderId, { ...folder, children }); + visiting.delete(folderId); + visited.add(folderId); + return repaired; + }; + + // Keep existing paths from the root when choosing which cycle edge to remove. + visit(rootFolderId); + const referenced = new Set( + [...nextFolders.values()].flatMap((folder) => folder.children) + ); + const folderIds = [...nextFolders.keys()].sort(); + const root = nextFolders.get(rootFolderId); + // Visit detached tree roots before isolated cycles, then attach repaired trees. + for (const folderId of [ + ...folderIds.filter((id) => referenced.has(id) === false), + ...folderIds, + ]) { + if (visit(folderId) && root !== undefined) { + root.children.push(folderId); + } + } return nextFolders; }; @@ -154,9 +198,10 @@ export const migratePages = (pagesData: unknown): Pages => { const normalizedPages = { ...currentPages, pageTemplates: currentPages.pageTemplates ?? new Map(), - folders: removeOrphanFolderChildren( + folders: normalizeFolderChildren( currentPages.pages, - currentPages.folders + currentPages.folders, + currentPages.rootFolderId ), }; if (hasHistoricalFormComponentIdentityVersion(currentPages)) { @@ -179,7 +224,11 @@ export const migratePages = (pagesData: unknown): Pages => { pagesData.pageTemplates === undefined ? new Map() : toMap(pagesData.pageTemplates), - folders: removeOrphanFolderChildren(nextPages, nextFolders), + folders: normalizeFolderChildren( + nextPages, + nextFolders, + pagesData.rootFolderId + ), }; } @@ -250,6 +299,6 @@ export const migratePages = (pagesData: unknown): Pages => { rootFolderId: rootFolder.id, pages: nextPages, pageTemplates: new Map(), - folders: nextFolders, + folders: normalizeFolderChildren(nextPages, nextFolders, rootFolder.id), }; }; From ab82a5b634bc72db27e06b2be14bbccb6a732750 Mon Sep 17 00:00:00 2001 From: Oleg Isonen Date: Fri, 13 Nov 2026 15:03:40 +0000 Subject: [PATCH 2/3] fix: Load marketplace thumbnails without scanning copied assets (#6688) Marketplace items fail to load in Builder because the thumbnail lookup times out. It filters by asset ID alone, and project copies reuse those IDs. In production, 39 thumbnail IDs match about 113,000 asset rows across projects. Database logs identify this exact PostgREST query as the canceled statement. ## Change - Fetch thumbnail names by exact asset and marketplace project pairs. This lets PostgreSQL use the existing composite asset index for each thumbnail. - Fetch only the fields needed for thumbnail names, and match each result to its own project. - Keep the marketplace view and database schema unchanged. ## Checklist - [x] Add a regression test that fails for the old lookup and copied asset IDs. - [x] Fetch thumbnails by exact project and asset pairs. - [x] Run targeted tests, Builder typecheck, lint, and formatting checks. - [x] Review Builder docs. No update is needed because behavior and instructions are unchanged. - [x] Review CI results for the final commit. - [ ] Required CI green. Visual regression is blocked by a repeatable, unrelated color picker screenshot difference. ## Verification - The new regression test failed against the old lookup and passes with the paired filter. All six marketplace tests pass. - A read-only production query using the current 39 thumbnail IDs and 40 project IDs took about 14 ms for the broad asset lookup and 1.7 ms for exact pairs in a warm-cache comparison. The broad query returned 1,000 rows at its PostgREST limit; exact pairs returned 39. Query times vary with load. - The production Postgres log records 63 statement timeouts for the old Asset query in the last 24 hours. The earliest visible event is November 12 at 12:33 UTC; this is only the available log window, not the first-ever failure. - All 39 thumbnails exist in their own marketplace projects. The marketplace view still loads the 40 item records; this fix removes only the broad asset lookup. The paired filter URL grows with the number of marketplace items. - Builder typecheck, targeted oxlint, oxfmt, and git diff checks pass. No fixture inputs or outputs are affected. Agent evaluations were not run because this does not change agent-facing behavior. - [Main CI workflow](https://github.com/webstudio-is/webstudio/actions/runs/43421159979) passed all 23 jobs. [Visual regression](https://github.com/webstudio-is/webstudio/actions/runs/43421159955) failed on a 0.043% difference in the Design System color picker story and failed identically on retry. This PR changes only the marketplace server query and its test. --- .../app/shared/marketplace/db.server.test.ts | 34 +++++++++++++++++++ .../app/shared/marketplace/db.server.ts | 23 ++++++++----- 2 files changed, 48 insertions(+), 9 deletions(-) diff --git a/apps/builder/app/shared/marketplace/db.server.test.ts b/apps/builder/app/shared/marketplace/db.server.test.ts index 77d26d4703..ffe61546ab 100644 --- a/apps/builder/app/shared/marketplace/db.server.test.ts +++ b/apps/builder/app/shared/marketplace/db.server.test.ts @@ -103,6 +103,40 @@ describe("getItems (msw)", () => { expect(result[0].thumbnailAssetName).toBe("thumb.png"); }); + test("loads thumbnail names only from their marketplace projects", async () => { + server.use( + db.get("ApprovedMarketplaceProduct", () => + json([ + { + projectId: "proj-1", + marketplaceProduct: marketplaceProductJson, + authorizationToken: null, + }, + { + projectId: "proj-2", + marketplaceProduct: marketplaceProductJson, + authorizationToken: null, + }, + ]) + ), + db.get("Asset", ({ request }) => { + expect(new URL(request.url).searchParams.get("or")).toBe( + '(and(id.eq."asset-thumb",projectId.eq."proj-1"),and(id.eq."asset-thumb",projectId.eq."proj-2"))' + ); + return json([ + { id: "asset-thumb", projectId: "proj-1", name: "first.png" }, + { id: "asset-thumb", projectId: "proj-2", name: "second.png" }, + ]); + }) + ); + + const result = await getItems(ctx); + expect(result.map((item) => item.thumbnailAssetName)).toEqual([ + "first.png", + "second.png", + ]); + }); + test("returns items without thumbnailAssetName when asset missing", async () => { server.use( db.get("ApprovedMarketplaceProduct", () => diff --git a/apps/builder/app/shared/marketplace/db.server.ts b/apps/builder/app/shared/marketplace/db.server.ts index 85e196ad69..edec1ca60e 100644 --- a/apps/builder/app/shared/marketplace/db.server.ts +++ b/apps/builder/app/shared/marketplace/db.server.ts @@ -55,28 +55,33 @@ export const getItems = async ( ...parsedProduct.data, }); } - const assetIds = items - .map((item) => item.thumbnailAssetId) - .filter((value): value is string => value != null); - const assets = new Map(); - if (assetIds.length > 0) { + if (items.length > 0) { const data = await context.postgrest.client .from("Asset") - .select() - .in("id", assetIds); + .select("id,projectId,name") + .or( + items + .map( + (item) => + `and(id.eq.${JSON.stringify(item.thumbnailAssetId)},projectId.eq.${JSON.stringify(item.projectId)})` + ) + .join(",") + ); if (data.error) { throw data.error; } for (const asset of data.data) { - assets.set(asset.id, asset.name); + assets.set(`${asset.projectId}:${asset.id}`, asset.name); } } return items.map((item) => { return { ...item, - thumbnailAssetName: assets.get(item.thumbnailAssetId), + thumbnailAssetName: assets.get( + `${item.projectId}:${item.thumbnailAssetId}` + ), }; }); }; From b153fb389044cceb86f7fa98a2022c0c9d68b332 Mon Sep 17 00:00:00 2001 From: Oleg Isonen Date: Sun, 15 Nov 2026 10:07:56 +0000 Subject: [PATCH 3/3] 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. --- .github/workflows/fixtures-test.yml | 36 ++++ .../features/text-editor/interop.test.tsx | 57 ++++++ .../canvas/features/text-editor/interop.ts | 21 ++- .../src/runtime/mdx-authored-content.ts | 30 ++-- .../src/runtime/mdx-materialization.test.ts | 164 ++++++++++++++++++ 5 files changed, 290 insertions(+), 18 deletions(-) diff --git a/.github/workflows/fixtures-test.yml b/.github/workflows/fixtures-test.yml index 95c30afb21..68f208cd56 100644 --- a/.github/workflows/fixtures-test.yml +++ b/.github/workflows/fixtures-test.yml @@ -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: | diff --git a/apps/builder/app/canvas/features/text-editor/interop.test.tsx b/apps/builder/app/canvas/features/text-editor/interop.test.tsx index 03cd1cb6f5..fd4b15254d 100644 --- a/apps/builder/app/canvas/features/text-editor/interop.test.tsx +++ b/apps/builder/app/canvas/features/text-editor/interop.test.tsx @@ -154,6 +154,63 @@ test("convert element instances to lexical", async () => { ); }); +test("keeps explicit line break instances while editing", async () => { + const { instances } = renderData( + + JÄRKI + myyntistrategian + perustukset + + ); + const refs: Refs = new Map(); + const editor = createHeadlessEditor({ nodes: [LinkNode] }); + await new Promise((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((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; diff --git a/apps/builder/app/canvas/features/text-editor/interop.ts b/apps/builder/app/canvas/features/text-editor/interop.ts index b0735f6ac1..cda209c0ba 100644 --- a/apps/builder/app/canvas/features/text-editor/interop.ts +++ b/apps/builder/app/canvas/features/text-editor/interop.ts @@ -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" || diff --git a/packages/project-build/src/runtime/mdx-authored-content.ts b/packages/project-build/src/runtime/mdx-authored-content.ts index fb1a294308..4a7b084a95 100644 --- a/packages/project-build/src/runtime/mdx-authored-content.ts +++ b/packages/project-build/src/runtime/mdx-authored-content.ts @@ -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 = diff --git a/packages/project-build/src/runtime/mdx-materialization.test.ts b/packages/project-build/src/runtime/mdx-materialization.test.ts index eef35f7692..e2fd7d7282 100644 --- a/packages/project-build/src/runtime/mdx-materialization.test.ts +++ b/packages/project-build/src/runtime/mdx-materialization.test.ts @@ -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(` + + + + ## Before + + Card description + + + + + + `); + 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: "" }); + 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],