Skip to content

Commit 9282db0

Browse files
authored
Merge pull request #245 from taras/feat/testing-function-components
✨ Add tryContent() for a component that reports its content failure
2 parents b66de7a + 45b6a6f commit 9282db0

7 files changed

Lines changed: 448 additions & 24 deletions

File tree

‎packages/core/mod.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ export type {
2626
ComponentDefinition,
2727
ComponentInvocationMetadata,
2828
ComponentOrigin,
29+
PartialContent,
2930
ComponentRegistry,
3031
ComponentSelection,
3132
Registered,
@@ -63,6 +64,7 @@ export {
6364
content,
6465
retain,
6566
invocation,
67+
tryContent,
6668
} from "./src/component-api.ts";
6769

6870
export { renderSegments } from "./src/render.ts";

‎packages/core/src/component-api.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import type {
2626
ComponentHandling,
2727
ComponentInvocationMetadata,
2828
ComponentRegistry,
29+
PartialContent,
2930
ErrorSegment,
3031
EvalEnv,
3132
FunctionComponentDefinition,
@@ -149,6 +150,17 @@ export interface ComponentApi {
149150
* always its own call site.
150151
*/
151152
invocation(): Operation<ComponentInvocationMetadata>;
153+
/**
154+
* Render the invoking component's content, reporting a failure instead of
155+
* replacing the invocation with it.
156+
*
157+
* `content()` is the failure boundary and stays the ordinary way to ask. This
158+
* is for a component that renders something *in place of* the failure — a
159+
* test report — and so needs both what rendered before the stop and why it
160+
* stopped. It hands back text and a reason, never segments: there is no
161+
* recursion here and no reaching into the caller.
162+
*/
163+
tryContent(slot?: string): Operation<PartialContent>;
152164
/**
153165
* Components made resolvable by name for this scope (spec §5.3).
154166
*
@@ -231,6 +243,12 @@ export const Component: Api<ComponentApi> = createApi<ComponentApi>("Component",
231243
"Component.invocation() has no provider: not inside a function component invocation.",
232244
);
233245
},
246+
// deno-lint-ignore require-yield
247+
*tryContent(_slot?: string): Operation<PartialContent> {
248+
throw new Error(
249+
"Component.tryContent() has no provider: not inside a function component invocation.",
250+
);
251+
},
234252
registry: new Map(),
235253
});
236254

@@ -251,3 +269,4 @@ export const hasContent: Operations<ComponentApi>["hasContent"] = Component.oper
251269
export const retain: Operations<ComponentApi>["retain"] = Component.operations.retain;
252270
export const registry: Operations<ComponentApi>["registry"] = Component.operations.registry;
253271
export const invocation: Operations<ComponentApi>["invocation"] = Component.operations.invocation;
272+
export const tryContent: Operations<ComponentApi>["tryContent"] = Component.operations.tryContent;

‎packages/core/src/expand.ts‎

Lines changed: 66 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -282,7 +282,10 @@ function createProjectionHandle(state: ProjectionState): ProjectionHandle {
282282
// the content scope. Raising it there would poison the scope, and the
283283
// invocation's teardown would then re-report it as a teardown error,
284284
// replacing the documentation failure the caller is meant to see.
285-
const outcome = withResolvers<{ segments: Segment[] } | { failure: unknown }>();
285+
const outcome = withResolvers<{ segments: Segment[]; failure?: unknown }>();
286+
// Shared with the expansion below, so a failure still leaves behind what it
287+
// rendered before stopping.
288+
const rendered: Segment[] = [];
286289
const task = contentScope.scope.run(function* () {
287290
try {
288291
yield* AmbientErrorPolicy.set(options.policy);
@@ -296,29 +299,46 @@ function createProjectionHandle(state: ProjectionState): ProjectionHandle {
296299
}
297300
yield* ActiveProjection.set(options.inner);
298301
yield* ActiveLoop.set(options.loop);
299-
outcome.resolve({
300-
segments: yield* expandSegments(
301-
options.segments,
302-
options.meta,
303-
options.props,
304-
options.hideSet,
305-
state.counter,
306-
),
307-
});
302+
yield* expandSegments(
303+
options.segments,
304+
options.meta,
305+
options.props,
306+
options.hideSet,
307+
state.counter,
308+
rendered,
309+
);
310+
outcome.resolve({ segments: rendered });
308311
} catch (error) {
309-
outcome.resolve({ failure: error });
312+
outcome.resolve({ segments: rendered, failure: error });
310313
}
311314
});
312315
yield* ensure(() => task.halt());
313316
const result = yield* outcome.operation;
314-
if ("failure" in result) {
317+
if (result.failure !== undefined) {
315318
throw result.failure;
316319
}
317320
return [...options.errors, ...result.segments];
318321
});
319322
}
320323

321324
function* runProjection(request: ProjectionRequest): Operation<Segment[]> {
325+
const outcome = yield* runProjectionOutcome(request);
326+
if (outcome.failure !== undefined) {
327+
throw outcome.failure;
328+
}
329+
return outcome.segments;
330+
}
331+
332+
/**
333+
* Project, and report what happened rather than deciding it.
334+
*
335+
* `segments` holds everything rendered, which for a failure is everything
336+
* rendered *before* it — expansion accumulates into the array as it goes, so
337+
* a body that stops partway still surrenders what it produced.
338+
*/
339+
function* runProjectionOutcome(
340+
request: ProjectionRequest,
341+
): Operation<{ segments: Segment[]; failure?: unknown }> {
322342
const segments = select(request);
323343
const policy = request.policy ?? (yield* AmbientErrorPolicy.get()) ?? "collect";
324344
const contentScope = yield* state.invocation.useContentScope();
@@ -332,13 +352,17 @@ function createProjectionHandle(state: ProjectionState): ProjectionHandle {
332352
// the content scope (see runInContentScope): a throw-bound failure the
333353
// caller catches is explicit recovery, and the invocation must not
334354
// re-report it as a teardown error.
335-
const outcome = withResolvers<{ segments: Segment[] } | { failure: unknown }>();
355+
const outcome = withResolvers<{ segments: Segment[]; failure?: unknown }>();
356+
// Shared with the expansion below, so a failure still leaves behind what it
357+
// rendered before stopping.
358+
const rendered: Segment[] = [];
359+
// Slot errors are reported inside the policy-bound task, so an empty
360+
// selection cannot settle them under the invocation's baseline. Held out
361+
// here so a failure still reports them alongside what rendered.
362+
const errors: Segment[] = [];
336363
const task = contentScope.scope.run(function* () {
337364
try {
338365
yield* AmbientErrorPolicy.set(policy);
339-
// Slot errors are reported inside the policy-bound task, so an empty
340-
// selection cannot settle them under the invocation's baseline.
341-
const errors: Segment[] = [];
342366
if (!slotErrorsEmitted && slots.errors.length > 0) {
343367
slotErrorsEmitted = true;
344368
for (const slotError of slots.errors) {
@@ -358,24 +382,21 @@ function createProjectionHandle(state: ProjectionState): ProjectionHandle {
358382
// Dynamic markdown is the component's own text, so it is not written
359383
// where the caller's loop is and cannot break it.
360384
yield* ActiveLoop.set(request.kind === "markdown" ? undefined : state.callerLoop);
361-
const rendered = yield* expandSegments(
385+
yield* expandSegments(
362386
project(segments),
363387
state.meta,
364388
state.props,
365389
state.hideSet,
366390
state.counter,
391+
rendered,
367392
);
368393
outcome.resolve({ segments: [...errors, ...rendered] });
369394
} catch (error) {
370-
outcome.resolve({ failure: error });
395+
outcome.resolve({ segments: [...errors, ...rendered], failure: error });
371396
}
372397
});
373398
yield* ensure(() => task.halt());
374-
const result = yield* outcome.operation;
375-
if ("failure" in result) {
376-
throw result.failure;
377-
}
378-
return result.segments;
399+
return yield* outcome.operation;
379400
});
380401
}
381402

@@ -411,6 +432,7 @@ function createProjectionHandle(state: ProjectionState): ProjectionHandle {
411432
});
412433
},
413434
project: runProjection,
435+
tryProject: runProjectionOutcome,
414436
*projectToString(request: ProjectionRequest): Operation<string> {
415437
const collect = state.collect;
416438
if (collect === undefined) {
@@ -472,8 +494,15 @@ export function* expandSegments(
472494
parentProps: Record<string, Json>,
473495
hideSet: Set<string>,
474496
counter: BlockCounter = createBlockCounter(),
497+
/**
498+
* Where to accumulate, when the caller wants what was rendered even if this
499+
* does not finish. Expansion appends as it goes, so a caller holding the same
500+
* array still has everything produced before a failure — which is how a
501+
* `<Test>` keeps its output when its body stops partway.
502+
*/
503+
collect?: Segment[],
475504
): Operation<Segment[]> {
476-
const result: Segment[] = [];
505+
const result: Segment[] = collect ?? [];
477506
// Read once: `<Loop>` publishes its frame for the nested call that expands
478507
// its body, so the frame ambient here cannot change while this list runs.
479508
const loop = yield* ActiveLoop.get();
@@ -2009,6 +2038,19 @@ function* expandFunctionComponent(
20092038
*invocation(_args, _next) {
20102039
return metadata;
20112040
},
2041+
*tryContent([slotName], _next) {
2042+
const outcome = yield* handle.tryProject({ kind: "slot", name: slotName });
2043+
// A documentation failure is presented in the public shape, as
2044+
// `content()` does, so a component recovering from one sees the
2045+
// same thing either way.
2046+
const failure =
2047+
outcome.failure instanceof DocumentationError
2048+
? new ContentExpansionFailure([outcome.failure.segment], outcome.failure)
2049+
: outcome.failure;
2050+
return failure === undefined
2051+
? { text: renderSegments(outcome.segments) }
2052+
: { text: renderSegments(outcome.segments), failure };
2053+
},
20122054
},
20132055
{ at: "min" },
20142056
);

‎packages/core/src/projection.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,14 @@ export interface ProjectionHandle {
6868
* away silently; function components project structurally and install none.
6969
*/
7070
projectToString(request: ProjectionRequest): Operation<string>;
71+
/**
72+
* `project`, reporting a failure instead of throwing it.
73+
*
74+
* `segments` holds what was rendered — for a failure, everything produced
75+
* before it stopped. A component that means to render something in place of
76+
* the failure needs both halves; `project` is for one that does not.
77+
*/
78+
tryProject(request: ProjectionRequest): Operation<{ segments: Segment[]; failure?: unknown }>;
7179
}
7280

7381
/**

‎packages/core/src/types.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,19 @@ export interface FunctionComponentDefinition {
208208
fn: FunctionComponent;
209209
}
210210

211+
/**
212+
* What a component's content rendered, and why it stopped if it did.
213+
*
214+
* `text` is everything produced before the stop, so a component reporting a
215+
* failure can show the work that led to it. `failure` is what the content threw
216+
* — absent when it finished. Error segments the content *collected* are part of
217+
* `text`, not a failure: they settled under the ambient policy already.
218+
*/
219+
export interface PartialContent {
220+
readonly text: string;
221+
readonly failure?: unknown;
222+
}
223+
211224
/**
212225
* Where a function component was invoked (spec §5.5).
213226
*

0 commit comments

Comments
 (0)