Skip to content

Commit d9057ab

Browse files
authored
🐛 Substitute <Content /> at every position in a body (#402)
* 🐛 Substitute <Content /> at every position in a body `<Content />` was replaced only where a body's segments were mapped directly: a top-level segment, or a direct child of a top-level `<Output>`. Written anywhere else — inside another invocation, inside a structural construct, or several levels down — it survived substitution, reached component resolution, and failed as a reserved name. Substitution now descends through the body. Two identity rules the top-level path never exercised come with it: projection leaves a resolved `<Content />` alone, because a copy loses the claim that tells it apart from one an author wrote where nothing projects; and reading a slot consumes its `slot` prop, so a resolved projection nested inside another invocation partitions there by position rather than being read a second time as that invocation's named slot. Closes #328 * 🧪 Observe nested projection identity directly Rendered output cannot tell two expansions apart, so a nested projection under `<Each>` now reads `Expansion.id` from a probe: the iterations carry different identifiers and re-expansion reproduces the pair. Two behaviors the recursion settles get their own coverage. An unclaimed `<Content />` passed through a nested wrapper stays the reserved-name failure rather than being consumed by the enclosing component. The specification's `<Section slot="header">` wrap reaches a nested invocation's named slot. §6.3.4 states the substitution algorithm in prose. Its pseudocode spliced the selected children into the body, which the normative lifecycle in the same section already contradicted: the claimed element is what lets expansion run them in the invocation's content scope. The section-divider comments in named-slots.test.ts go with it; every tier is already named by its describe. --------- Co-authored-by: Taras Mankovski <[email protected]>
1 parent 2fc2fb2 commit d9057ab

5 files changed

Lines changed: 270 additions & 57 deletions

File tree

‎packages/core/src/expand.ts‎

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2796,13 +2796,16 @@ function makeProjectFn(callerEnv: EvalEnv | undefined): ProjectFn {
27962796
return segments;
27972797
}
27982798
return segments.map((seg) => {
2799-
if (seg.type === "component") {
2799+
if (seg.type === "component" && seg.name !== "Content") {
28002800
return {
28012801
...seg,
28022802
projectedEnv: callerEnv,
28032803
children: project(seg.children),
28042804
};
28052805
}
2806+
// A `<Content />` passing through is a projection the invocation that
2807+
// wrote it already resolved: its content carries that invocation's env,
2808+
// and it is recognized by identity, which a copy would lose.
28062809
return seg;
28072810
});
28082811
};
@@ -2815,6 +2818,11 @@ function makeProjectFn(callerEnv: EvalEnv | undefined): ProjectFn {
28152818
* expansion frame is installed, so a current binding named `props` is used.
28162819
* Slot validation errors are emitted once, at the first projection point,
28172820
* tracked via the shared `state`.
2821+
*
2822+
* A projection point is wherever the body writes one, so this descends through
2823+
* every authored element on the way. Only the body is walked: what a projection
2824+
* resolves to belongs to the caller, and the caller's own body already
2825+
* substituted it.
28182826
*/
28192827
function substituteSegmentList(
28202828
segments: Segment[],
@@ -2824,7 +2832,10 @@ function substituteSegmentList(
28242832
claim: ClaimFn,
28252833
): Segment[] {
28262834
return segments.flatMap((segment): Segment[] => {
2827-
if (segment.type === "component" && segment.name === "Content") {
2835+
if (segment.type !== "component") {
2836+
return [segment];
2837+
}
2838+
if (segment.name === "Content") {
28282839
const targetSlot = segment.props.slot;
28292840
const pendingErrors = !state.errorsEmitted ? slots.errors : [];
28302841
if (pendingErrors.length > 0) {
@@ -2839,10 +2850,23 @@ function substituteSegmentList(
28392850
targetSlot !== undefined
28402851
? project((slots.named.get(String(targetSlot)) ?? []).map(stripSlotProp))
28412852
: project(slots.default);
2842-
const element: ComponentElement = { ...segment, children: projected, selfClosing: false };
2853+
// `slot` names which of this invocation's slots to read, and reading
2854+
// them consumes it (§6.3.5). A resolved projection nested inside another
2855+
// invocation is ordinary content there, so it partitions by position.
2856+
const { slot: _, ...props } = segment.props;
2857+
const element: ComponentElement = {
2858+
...segment,
2859+
props,
2860+
children: projected,
2861+
selfClosing: false,
2862+
};
28432863
return [...pendingErrors, claim(element)];
28442864
}
2845-
return [segment];
2865+
const children = substituteSegmentList(segment.children, slots, project, state, claim);
2866+
const untouched =
2867+
children.length === segment.children.length &&
2868+
children.every((child, index) => child === segment.children[index]);
2869+
return untouched ? [segment] : [{ ...segment, children }];
28462870
});
28472871
}
28482872

‎packages/core/tests/expansion-identity.test.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -443,6 +443,26 @@ describe("Tier XP — expansion identity", () => {
443443
expect(twoProbes[0]).not.toBe(twoProbes[1]);
444444
});
445445

446+
// A projection written inside an iterating construct is one authored
447+
// `<Content />` expanded once per item, so its identity has to come from the
448+
// path it expands under rather than from the element. `<Each>` adds its item
449+
// frame before the projection point is reached; dropping that frame, or
450+
// deriving the projection from the element that carries it, is what this
451+
// kills — both would report one identifier twice.
452+
it("XP26: a projection nested in <Each> differs per iteration and reproduces itself", function* () {
453+
const source = "<EachHost>\n<Probe />\n</EachHost>\n";
454+
const definitions = {
455+
EachHost: markdown("EachHost", '<Each in={[1, 2]} let="n">\n<Content />\n</Each>\n'),
456+
};
457+
458+
const first = yield* identifiers(source, definitions);
459+
const second = yield* identifiers(source, definitions);
460+
461+
expect(first).toHaveLength(2);
462+
expect(first[0]).not.toBe(first[1]);
463+
expect(second).toEqual(first);
464+
});
465+
446466
// The projection ordinal is the one discriminator that is not read off the
447467
// source, so it has to follow the component's own program order rather than
448468
// the order projections finish in. Two runs of one component, with the

‎packages/core/tests/invocation-scope.test.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,22 @@ describe("Tier O — Eval scope hierarchy", () => {
154154
expect(timeline).toEqual(["start:projected", "start:own", "stop:projected", "stop:own"]);
155155
});
156156

157+
// O41: the same contract when the projection point sits inside another
158+
// invocation. The wrapper completes before the provider retains its own
159+
// resource, so a projection that had moved into the wrapper's scope would
160+
// stop before `start:own` rather than after it.
161+
it("O41: a nested <Content /> keeps the invocation's content scope", function* () {
162+
const timeline: string[] = [];
163+
const definitions = {
164+
Provider: markdown("Provider", `<Wrapper><Content /></Wrapper>\n\n${WATCH_BLOCK_OWN}`),
165+
Wrapper: markdown("Wrapper", "<Content />"),
166+
};
167+
168+
yield* expandAll(`<Provider>\n${WATCH_BLOCK}\n</Provider>`, definitions, timeline);
169+
170+
expect(timeline).toEqual(["start:projected", "start:own", "stop:projected", "stop:own"]);
171+
});
172+
157173
// O11/O12: the same teardown order on a propagated body error, for both
158174
// component forms. The body throws after projecting, so the projected
159175
// resource is still alive when the invocation starts unwinding.

‎packages/core/tests/named-slots.test.ts‎

Lines changed: 149 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
/**
2-
* Named slots tests — Tiers NS-A through NS-G.
2+
* Named slots tests — Tiers NS-A through NS-H.
33
*
44
* Covers slot partitioning, content substitution, expansion integration,
5-
* slot prop reservation, renderChildren interaction, edge cases, and
6-
* boundary scanner confirmation.
5+
* slot prop reservation, renderChildren interaction, edge cases,
6+
* boundary scanner confirmation, and nested projection points.
77
*/
88

99
import { describe, it, beforeAll } from "@executablemd/test-support/bdd";
@@ -162,10 +162,6 @@ function cleanup(dir: string): void {
162162
fs.rmSync(dir, { recursive: true, force: true });
163163
}
164164

165-
// ═══════════════════════════════════════════════════════════════════════════
166-
// Tier NS-A — Slot partitioning (unit)
167-
// ═══════════════════════════════════════════════════════════════════════════
168-
169165
describe("Tier NS-A — Slot partitioning", () => {
170166
// deno-lint-ignore require-yield
171167
it("NS-A1: no slot props — all in default", function* () {
@@ -268,10 +264,6 @@ describe("Tier NS-A — Slot partitioning", () => {
268264
});
269265
});
270266

271-
// ═══════════════════════════════════════════════════════════════════════════
272-
// Tier NS-B — Content substitution (unit)
273-
// ═══════════════════════════════════════════════════════════════════════════
274-
275267
describe("Tier NS-B — Content substitution", () => {
276268
it("NS-B1: backward compat — no slots anywhere", function* () {
277269
const layout = makeComponent("Layout", "before\n<Content />\nafter");
@@ -410,10 +402,6 @@ describe("Tier NS-B — Content substitution", () => {
410402
});
411403
});
412404

413-
// ═══════════════════════════════════════════════════════════════════════════
414-
// Tier NS-C — Expansion integration
415-
// ═══════════════════════════════════════════════════════════════════════════
416-
417405
describe("Tier NS-C — Expansion integration", () => {
418406
it("NS-C1: basic named slot expansion", function* () {
419407
const report = makeComponent(
@@ -617,10 +605,6 @@ describe("Tier NS-C — Expansion integration", () => {
617605
});
618606
});
619607

620-
// ═══════════════════════════════════════════════════════════════════════════
621-
// Tier NS-D — slot prop reservation
622-
// ═══════════════════════════════════════════════════════════════════════════
623-
624608
describe("Tier NS-D — slot prop reservation", () => {
625609
it("NS-D1: slot in props frontmatter → error", function* () {
626610
const { props } = parseFrontmatter({
@@ -691,10 +675,6 @@ describe("Tier NS-D — slot prop reservation", () => {
691675
});
692676
});
693677

694-
// ═══════════════════════════════════════════════════════════════════════════
695-
// Tier NS-E — renderChildren() interaction
696-
// ═══════════════════════════════════════════════════════════════════════════
697-
698678
describe("Tier NS-E — renderChildren interaction", () => {
699679
beforeAll(() => useTempFileCompiler());
700680
it("NS-E1: renderChildren includes all slots", function* () {
@@ -814,10 +794,6 @@ describe("Tier NS-E — renderChildren interaction", () => {
814794
});
815795
});
816796

817-
// ═══════════════════════════════════════════════════════════════════════════
818-
// Tier NS-F — Edge cases
819-
// ═══════════════════════════════════════════════════════════════════════════
820-
821797
describe("Tier NS-F — Edge cases", () => {
822798
it("NS-F1: slot on self-closing component", function* () {
823799
const layout = makeComponent("Layout", '<Content slot="icon" />\n<Content />');
@@ -984,10 +960,6 @@ describe("Tier NS-F — Edge cases", () => {
984960
});
985961
});
986962

987-
// ═══════════════════════════════════════════════════════════════════════════
988-
// Tier NS-G — Boundary scanner (confirms no changes needed)
989-
// ═══════════════════════════════════════════════════════════════════════════
990-
991963
describe("Tier NS-G — Boundary scanner", () => {
992964
// deno-lint-ignore require-yield
993965
it("NS-G1: slot parsed as string prop", function* () {
@@ -1030,3 +1002,149 @@ describe("Tier NS-G — Boundary scanner", () => {
10301002
expect(segments[0]!.type).toBe("text");
10311003
});
10321004
});
1005+
1006+
describe("Tier NS-H — Nested projection points", () => {
1007+
it("NS-H1: inside another component invocation", function* () {
1008+
const echo = makeComponent("Echo", "ECHO(<Content />)");
1009+
const host = makeComponent("Host", "<Echo>prefix <Content /> suffix</Echo>");
1010+
const segments = scanSegments("<Host>MATERIAL</Host>");
1011+
const expanded = yield* expandAll(segments, { Echo: echo, Host: host });
1012+
expect(renderSegments(expanded)).toContain("ECHO(prefix MATERIAL suffix)");
1013+
});
1014+
1015+
it("NS-H2: several levels deep", function* () {
1016+
const inner = makeComponent("Inner", "IN(<Content />)");
1017+
const outer = makeComponent("Outer", "OUT{<Content />}");
1018+
const host = makeComponent("Host", "<Outer><Inner>deep <Content /></Inner></Outer>");
1019+
const segments = scanSegments("<Host>MATERIAL</Host>");
1020+
const expanded = yield* expandAll(segments, { Inner: inner, Outer: outer, Host: host });
1021+
expect(renderSegments(expanded)).toContain("OUT{IN(deep MATERIAL)}");
1022+
});
1023+
1024+
it("NS-H3: named slot in a nested position", function* () {
1025+
const echo = makeComponent("Echo", "ECHO(<Content />)");
1026+
const host = makeComponent("Host", '<Echo><Content slot="header" /></Echo>\n\n<Content />');
1027+
const headerComp = makeComponent("Header", "HEADER-TEXT");
1028+
const segments = scanSegments('<Host>\n<Header slot="header" />\ndefault text\n</Host>');
1029+
const expanded = yield* expandAll(segments, { Echo: echo, Host: host, Header: headerComp });
1030+
const output = renderSegments(expanded);
1031+
expect(output).toContain("ECHO(HEADER-TEXT)");
1032+
expect(output).toContain("default text");
1033+
expect(output.indexOf("ECHO(HEADER-TEXT)")).toBeLessThan(output.indexOf("default text"));
1034+
});
1035+
1036+
it("NS-H4: two projections at different depths receive the same content", function* () {
1037+
const echo = makeComponent("Echo", "ECHO(<Content />)");
1038+
const host = makeComponent("Host", "top: <Content />\n\n<Echo><Content /></Echo>");
1039+
const segments = scanSegments("<Host>MATERIAL</Host>");
1040+
const expanded = yield* expandAll(segments, { Echo: echo, Host: host });
1041+
const output = renderSegments(expanded);
1042+
expect(output).toContain("top: MATERIAL");
1043+
expect(output).toContain("ECHO(MATERIAL)");
1044+
});
1045+
1046+
it("NS-H5: nested inside a top-level <Output> region", function* () {
1047+
const echo = makeComponent("Echo", "ECHO(<Content />)");
1048+
const host = makeComponent("Host", "<Output><Echo><Content /></Echo></Output>");
1049+
const segments = scanSegments("<Host>MATERIAL</Host>");
1050+
const expanded = yield* expandAll(segments, { Echo: echo, Host: host });
1051+
expect(renderSegments(expanded)).toContain("ECHO(MATERIAL)");
1052+
});
1053+
1054+
it("NS-H6: slot validation errors are still emitted once", function* () {
1055+
const echo = makeComponent("Echo", "ECHO(<Content />)");
1056+
const host = makeComponent("Host", "<Echo><Content /></Echo>\nsecond: <Content />");
1057+
const bad = makeComponent("Bad", "BAD");
1058+
const segments = scanSegments('<Host>\n<Bad slot="123invalid" />\n</Host>');
1059+
const expanded = yield* expandAll(segments, { Echo: echo, Host: host, Bad: bad });
1060+
const errors = expanded.filter((segment) => segment.type === "error");
1061+
expect(errors).toHaveLength(1);
1062+
});
1063+
1064+
it("NS-H7: nested inside a structural construct", function* () {
1065+
const tmpDir = makeTempDir();
1066+
try {
1067+
writeFiles(tmpDir, {
1068+
"components/HostCap.md": [
1069+
"---",
1070+
"props: { type: object, properties: {}, additionalProperties: false }",
1071+
"---",
1072+
'<Capture as="c">captured: <Content /></Capture>',
1073+
"<Output>host got: {c}</Output>",
1074+
].join("\n"),
1075+
"doc.md": "<HostCap>MATERIAL</HostCap>",
1076+
});
1077+
const output = yield* collect(
1078+
yield* execute({
1079+
path: path.join(tmpDir, "doc.md"),
1080+
stream: new InMemoryStream(),
1081+
componentDirs: [path.join(tmpDir, "components"), tmpDir],
1082+
}),
1083+
);
1084+
expect(output).toContain("host got: captured: MATERIAL");
1085+
} finally {
1086+
cleanup(tmpDir);
1087+
}
1088+
});
1089+
1090+
it("NS-H8: nested inside an iterating construct", function* () {
1091+
const tmpDir = makeTempDir();
1092+
try {
1093+
writeFiles(tmpDir, {
1094+
"components/EachHost.md": [
1095+
"---",
1096+
"props: { type: object, properties: {}, additionalProperties: false }",
1097+
"---",
1098+
'<Each in={[1, 2]} let="n">',
1099+
"item {n}: <Content />",
1100+
"</Each>",
1101+
].join("\n"),
1102+
"doc.md": "<EachHost>MATERIAL</EachHost>",
1103+
});
1104+
const output = yield* collect(
1105+
yield* execute({
1106+
path: path.join(tmpDir, "doc.md"),
1107+
stream: new InMemoryStream(),
1108+
componentDirs: [path.join(tmpDir, "components"), tmpDir],
1109+
}),
1110+
);
1111+
expect(output).toContain("item 1: MATERIAL");
1112+
expect(output).toContain("item 2: MATERIAL");
1113+
} finally {
1114+
cleanup(tmpDir);
1115+
}
1116+
});
1117+
1118+
it("NS-H9: an unclaimed <Content /> stays reserved through a nested wrapper", function* () {
1119+
const echo = makeComponent("Echo", "ECHO(<Content />)");
1120+
const host = makeComponent("Host", "<Echo><Content /></Echo>");
1121+
// Written in the document, where nothing projects: no invocation resolved
1122+
// it, so passing it through two nested bodies must not make it mean one.
1123+
const segments = scanSegments("<Host><Content /></Host>");
1124+
const expanded = yield* expandAll(segments, { Echo: echo, Host: host });
1125+
const errors = expanded.filter((segment) => segment.type === "error");
1126+
expect(errors).toHaveLength(1);
1127+
expect(errors[0]!.message).toContain("<Content> is reserved");
1128+
});
1129+
1130+
it("NS-H10: a wrapped projection reaches a nested invocation's named slot", function* () {
1131+
const layout = makeComponent("Layout", 'LAYOUT(<Content slot="header" />)');
1132+
const section = makeComponent("Section", "<Content />");
1133+
const host = makeComponent(
1134+
"Host",
1135+
'<Layout><Section slot="header"><Content slot="header" /></Section></Layout>',
1136+
);
1137+
const headerComp = makeComponent("Header", "HEADER-TEXT");
1138+
const segments = scanSegments('<Host>\n<Header slot="header" />\ndefault text\n</Host>');
1139+
const expanded = yield* expandAll(segments, {
1140+
Layout: layout,
1141+
Section: section,
1142+
Host: host,
1143+
Header: headerComp,
1144+
});
1145+
const output = renderSegments(expanded);
1146+
expect(output).toContain("LAYOUT(HEADER-TEXT)");
1147+
// Host's default slot is not projected, so nothing else rides along.
1148+
expect(output).not.toContain("default text");
1149+
});
1150+
});

0 commit comments

Comments
 (0)