Files
Oleg Isonen 05706b5425 feat: Make Content Block templates the MDX authoring interface (#6307)
Closes #6306

## Outcome

Content Block templates are now the public component model for MDX
authoring.

- Standard Markdown resolves through matching Content Block templates.
- PascalCase JSX resolves to a named template first, then to a
registered component.
- Adding or changing a template immediately affects matching MDX,
including content authored before that template existed.
- Every supported standard MDX element is present in new Content Blocks
by default.
- Template `name` is a stable PascalCase JSX identifier. `label` remains
optional display text only.
- Lowercase JSX represents native HTML and SVG without exposing
`ws.element` in authored syntax.
- Unknown, ambiguous, and unsafe JSX stays in source, produces a
source-ranged Builder diagnostic, and is omitted from published output.
- Frontmatter images preserve exact `$ref` values and use the Asset
description for `alt` text.
- Keyboard and mouse insertion from the slash menu remove the trigger
slash and preserve the selected template.

## Public MDX contract

- Markdown is canonical for standard prose.
- Lowercase JSX creates native elements:
`<section><p>Text</p></section>`.
- PascalCase JSX uses templates and registered components:
`<PromotionCard />`, `<Heading tag="h1">Title</Heading>`, and `<YouTube
src="https://youtu.be/KI5JHpzBK1s" />`.
- Component-name collisions use stable qualified identifiers such as
`Checkbox` and `RadixCheckbox`.
- A self-closing template keeps its designed default subtree. An
explicitly paired empty template clears it.
- Static quoted values and bare booleans are supported.
- Imports, exports, expressions, spreads, functions, executable
JavaScript, unsafe attributes, `<$.*>`, and authored `<ws.element>` are
rejected.
- `ws` remains only for compiler primitives with no React component.

## Implementation

- [x] Add stable, unique template names and keep them separate from
labels.
- [x] Parse and validate Markdown and JSX through their ASTs with
precise source ranges.
- [x] Share component identity between template JSX, Content MDX,
Builder materialization, reload, copy, and publication.
- [x] Resolve templates live after add, edit, rename, reorder, removal,
undo/redo, collaboration updates, and reload.
- [x] Preserve authored props, children, Asset references, template
defaults, and the exact slash-menu template choice.
- [x] Make one typed MDX semantic inventory drive default templates and
slash-menu eligibility.
- [x] Move component-dependent template assembly into the component
registry.
- [x] Replace production `$`, `animation`, and `radix` JSX namespaces
with direct component imports.
- [x] Keep only explicit compiler primitives in `ws` template JSX.
- [x] Migrate repository templates, fixtures, stories, examples, MCP
guidance, CLI guidance, and generated outputs.
- [x] Add Builder unit and Playwright coverage for authoring,
diagnostics, insertion, synchronization, reload, and publication.
- [x] Review and update the authoritative Content Block and generated
MCP documentation.

## Compatibility

- Persisted project data continues to use namespaced component IDs and
`ws:element` for generic HTML elements. No project-data migration is
required.
- Legacy `<ws.element ws:tag="…">`, `<ws.element ws:name="…">`, `<$.*>`,
`<animation.*>`, and `<radix.*>` input remains readable during the
compatibility window.
- Current serializers and repository-owned sources emit only canonical
Markdown, lowercase intrinsic JSX, or PascalCase identifiers.
- Untouched user MDX is not rewritten automatically. Legacy syntax is
canonicalized when its owning source is edited.
- Deferred follow-up: remove legacy namespace readers and proxy support
only after the canonical writer is deployed and existing projects are
backfilled. This is intentionally outside this PR.

## Verification

- [x] CI package tests, typechecks, lint, package boundaries, generated
assets, migrations, and size checks pass.
- [x] All six Builder E2E shards pass.
- [x] Fixture checks pass on Ubuntu and Windows.
- [x] Targeted local Content Engine, Template, SDK, registry, Project
Build, migration, Builder, component, CLI, and Playwright tests pass.
- [x] Runtime contracts, CLI docs, and MCP docs were regenerated from
their owning sources.
- [x] Local fixture generation completed without an unexpected fixture
diff.
- [x] Documentation impact reviewed and included in this PR.
- [x] Review and approve the intentional List visual snapshot change.
- [x] Run the complete agent evaluation suite after explicit approval.
- [x] Run the network fixture link/sync pipeline against the matching PR
deployment after explicit permission.

## Known visual change

The generated List story now targets its actual default `ul` element
instead of `ol`, so the default list styling appears in the visual
snapshot. The visual change was reviewed and the approved visual check
passes.
2026-09-06 15:19:54 +02:00

273 lines
8.0 KiB
TypeScript

import { afterEach, describe, expect, test, vi } from "vitest";
import { atom } from "nanostores";
import type { SyncEmitter } from "@webstudio-is/sync-client";
import { __testing__ } from "./sync-client";
import type { LoadedBuilderData } from "~/shared/builder-data";
import { serverSyncStoreNames } from "./sync-stores";
import {
$externalContentRoots,
__testing__ as externalContentMutationsTesting,
subscribeExternalContentTemplateMutations,
type ExternalContentRoot,
} from "../external-content-mutations";
import {
NanoEventsSyncEmitter,
NanostoresSyncObject,
SyncClient,
} from "../sync-client";
const { applyBuilderData, getServerSyncState, resolveMultiplayerRelayUrl } =
__testing__;
const { observeExternalContentRootMutations } = externalContentMutationsTesting;
afterEach(() => {
$externalContentRoots.set(new Map());
});
describe("getServerSyncState", () => {
test("keeps only server-synchronized builder data", () => {
const data = {
id: "build-1",
version: 1,
projectId: "project-1",
project: { id: "project-1" },
publisherHost: "example.com",
pages: "pages",
breakpoints: "breakpoints",
instances: "instances",
styles: "styles",
styleSources: "styleSources",
styleSourceSelections: "styleSourceSelections",
props: "props",
dataSources: "dataSources",
resources: "resources",
assets: "assets",
assetFolders: "assetFolders",
marketplaceProduct: "marketplaceProduct",
projectSettings: "projectSettings",
} as unknown as LoadedBuilderData;
const serverSyncState = getServerSyncState(data);
expect([...serverSyncState.keys()]).toEqual([...serverSyncStoreNames]);
expect(serverSyncState).toEqual(
new Map<string, unknown>([
["pages", "pages"],
["breakpoints", "breakpoints"],
["instances", "instances"],
["styles", "styles"],
["styleSources", "styleSources"],
["styleSourceSelections", "styleSourceSelections"],
["props", "props"],
["dataSources", "dataSources"],
["resources", "resources"],
["assets", "assets"],
["assetFolders", "assetFolders"],
["projectSettings", "projectSettings"],
["marketplaceProduct", "marketplaceProduct"],
])
);
expect([...serverSyncState.keys()]).not.toContain("project");
expect([...serverSyncState.keys()]).not.toContain("publisherHost");
});
});
test("refreshes mounted external templates after a full project reload", () => {
$externalContentRoots.set(
new Map([
[
"current-root",
{
blockInstanceId: "current-block",
instanceIds: new Set<string>(),
mutationRevision: 0,
projectId: "project-1",
},
],
[
"other-root",
{
blockInstanceId: "other-block",
instanceIds: new Set<string>(),
mutationRevision: 0,
projectId: "project-2",
},
],
])
);
const refreshes: string[][] = [];
const unsubscribe = subscribeExternalContentTemplateMutations((rootKeys) => {
refreshes.push([...rootKeys]);
});
try {
applyBuilderData({
id: "build-1",
version: 1,
projectId: "project-1",
project: { id: "project-1" },
publisherHost: "example.com",
pages: {},
breakpoints: new Map(),
instances: new Map(),
styles: new Map(),
styleSources: new Map(),
styleSourceSelections: new Map(),
props: new Map(),
dataSources: new Map(),
resources: new Map(),
assets: new Map(),
assetFolders: new Map(),
marketplaceProduct: undefined,
projectSettings: { meta: {}, compiler: {} },
} as unknown as LoadedBuilderData);
} finally {
unsubscribe();
}
expect(refreshes).toEqual([["current-root"]]);
expect(
$externalContentRoots.get().get("current-root")?.templateMutationRevision
).toBe(1);
expect(
$externalContentRoots.get().get("other-root")?.templateMutationRevision
).toBeUndefined();
});
test("refreshes canvas templates once after a full project reload crosses realms", async () => {
$externalContentRoots.set(
new Map([
[
"current-root",
{
blockInstanceId: "current-block",
instanceIds: new Set<string>(),
mutationRevision: 0,
projectId: "project-1",
},
],
])
);
const $canvasRoots = atom(new Map<string, ExternalContentRoot>());
const canvasRefreshes: string[][] = [];
const unsubscribeCanvasObserver = observeExternalContentRootMutations({
store: $canvasRoots,
onMutation: () => {},
onTemplateMutation(rootKeys) {
canvasRefreshes.push([...rootKeys]);
},
});
const innerEmitter = new NanoEventsSyncEmitter();
// Builder and canvas have separate Nanostores listener queues. Deferring the
// shared emitter reproduces that boundary while both stores run in this test.
const emitter: SyncEmitter = {
emit(message) {
const received = structuredClone(message);
queueMicrotask(() => innerEmitter.emit(received));
},
on(handler) {
return innerEmitter.on(handler);
},
};
const builderController = new AbortController();
const canvasController = new AbortController();
new SyncClient({
role: "leader",
object: new NanostoresSyncObject(
"externalContentRoots",
$externalContentRoots
),
emitter,
}).connect({ signal: builderController.signal });
new SyncClient({
role: "follower",
object: new NanostoresSyncObject("externalContentRoots", $canvasRoots),
emitter,
}).connect({ signal: canvasController.signal });
try {
await vi.waitFor(() =>
expect($canvasRoots.get().has("current-root")).toBe(true)
);
expect(
$canvasRoots.get().get("current-root")?.templateMutationRevision
).toBeUndefined();
applyBuilderData({
id: "build-1",
version: 1,
projectId: "project-1",
project: { id: "project-1" },
publisherHost: "example.com",
pages: {},
breakpoints: new Map(),
instances: new Map(),
styles: new Map(),
styleSources: new Map(),
styleSourceSelections: new Map(),
props: new Map(),
dataSources: new Map(),
resources: new Map(),
assets: new Map(),
assetFolders: new Map(),
marketplaceProduct: undefined,
projectSettings: { meta: {}, compiler: {} },
} as unknown as LoadedBuilderData);
await vi.waitFor(() =>
expect(
$canvasRoots.get().get("current-root")?.templateMutationRevision
).toBe(1)
);
} finally {
builderController.abort();
canvasController.abort();
unsubscribeCanvasObserver();
}
expect(
$externalContentRoots.get().get("current-root")?.templateMutationRevision
).toBe(1);
expect($canvasRoots.get().get("current-root")?.templateMutationRevision).toBe(
1
);
expect(canvasRefreshes).toEqual([["current-root"]]);
});
describe("resolveMultiplayerRelayUrl", () => {
test("keeps configured absolute URL outside local wstd.dev", () => {
expect(
resolveMultiplayerRelayUrl(
"https://apps.webstudio.is/collab-relay",
"https://builder.webstudio.is/builder/project-id"
)
).toBe("https://apps.webstudio.is/collab-relay");
});
test("keeps configured absolute URL on local wstd.dev", () => {
expect(
resolveMultiplayerRelayUrl(
"https://apps.webstudio.is/collab-relay",
"https://p-project-id.wstd.dev:5173/builder/project-id"
)
).toBe("https://apps.webstudio.is/collab-relay");
});
test("proxies relative relay URLs through the local wstd.dev dev server", () => {
expect(
resolveMultiplayerRelayUrl(
"/collab-relay",
"https://p-project-id.wstd.dev:5173/builder/project-id"
)
).toBe("https://p-project-id.wstd.dev:5173/collab-relay");
});
test("supports relative relay URLs", () => {
expect(
resolveMultiplayerRelayUrl(
"/collab-relay",
"https://builder.webstudio.is/builder/project-id"
)
).toBe("https://builder.webstudio.is/collab-relay");
});
});