Components#
A Craft component is a function, not a class. No decorator, no separate template file, no host element wrapped around your markup.
Use it for application components. loadCraftComponent mounts a Craft component on a route.
Install#
The component renderer is published as a separate package and is currently on the beta channel:
npm i @craft-ts/core@beta @craft-ts/component@beta
See @craft-ts/component on npm.
The shape#
craftComponent(name, meta, template);
| Argument | What it is |
|---|---|
name | the component's name — used for host tags, snapshots, diagnostics |
meta | providers, host |
template | the component: it declares what it takes, then returns nodes |
import { craftComponent, forNode, h1, li, ul } from '@craft-ts/component';
import { craftService, state } from '@craft-ts/core';
type Task = { id: string; title: string; done: boolean };
const { TasksView, provideTasksView } = craftService(
{ name: 'tasksView', providedIn: 'toProvide' },
function* () {
yield* state('tasks', [] as Task[]);
},
);
export const Tasks = craftComponent(
'Tasks',
{ providers: [provideTasksView()] },
() => [
h1('Tasks'),
ul(
forNode(
function* () {
return yield* (yield* TasksView()).tasks();
},
{ track: (task) => task.id },
(task) =>
li(function* () {
return (yield* task()).title;
}),
),
),
],
);
One function, read top to bottom. What the component takes — its service, its primitives, its inputs — is declared with yield*; what it renders is what it returns. The service is the seam: it holds the behaviour, so it can be tested without a DOM while the template is tested against it. See Testing components.
The function#
A function* when it needs dependencies — every yield* is tracked and folds into the component's dependency type:
function* () {
const tasks = yield* TaskList();
return ul(/* … */);
}
A plain arrow when it needs none:
() => ul(/* … */);
Local state that must survive a rerender belongs to a primitive or to the component's service — never to a plain const in the body, which is rebuilt on every render.
Inputs and outputs#
They are the members of the single parameter, typed with Input<T> and Output<Handler>:
import {
Input,
Output,
button,
craftComponent,
div,
span,
} from '@craft-ts/component';
import { deepYieldable } from '@craft-ts/core';
type User = { name: string };
const UserCard = craftComponent(
'UserCard',
{},
function* (inputs: {
readonly user: Input<User>;
readonly onRemove: Output<(user: User) => void>;
}) {
const user = deepYieldable(inputs.user);
const { onRemove } = inputs;
return div([
span(user.name),
button(
'remove',
{
type: 'button',
*click() {
onRemove(yield* user());
},
},
'Remove',
),
]);
},
);
An Input<T> is a yieldable reader — yield* user() reads the current value. An Output<H> is a plain callback: call it.
Rendering a child is a function call, so there is no binding layer to get wrong:
UserCard({ user: currentUser, onRemove: removeUser });
| Contract | Craft |
|---|---|
| Input | an Input<T> member of the inputs object |
| Output | an Output<H> member, called directly |
| Component call | UserCard({ user: u, onRemove: fn }) |
| Missing required input | compile error |
What it returns#
Nodes are built with hyperscript helpers — div, ul, button, and h(tag, …) for anything without one. Pass a yieldable reader to a binding. Use a generator when the binding must format or call a method:
return [
h1(function* () {
return `Tasks — ${yield* tasks.remaining()} left`;
}),
h1(`Tasks — static`), // static text needs no reader
];
SVG icons use the same typed nodes and bindings:
import { svg, path } from '@craft-ts/component';
return svg({ viewBox: '0 0 24 24', 'aria-hidden': true }, [
path({ d: 'M5 12h14', stroke: 'currentColor', 'stroke-width': 2 }),
]);
svg and its descendants are created in the SVG namespace, including during server rendering. foreignObject switches its children back to HTML. Shape helpers include path, circle, rect, and g; h() also accepts SVG tags. URL bindings retain the usual security checks.
The same binding boundary applies to attributes, DOM properties, classes, styles, and host props. Prefer exposing a derived reader on the primitive (tasks.isEmpty) and passing it (disabled: tasks.isEmpty) over wrapping a synchronous call.
See Fine-grained reactivity for the complete rendering model, structural scopes, observability expectations, and migration checklist.
See Progressive forNode rendering when a large collection needs frame-based scheduling.
Keep render callbacks pure. They may read signals and calculate values, but must not call set, update, or mutate. Perform writes from DOM events, outputs, mutations, or explicit business effects. Enable craft-ts/no-render-writes to diagnose common violations.
Control flow is made of functions rather than syntax — forNode, ifNode, matchNode, deferNode. The relationship between these blocks, and why a raw ternary is the wrong tool for structure, is in Learn step 2.
The meta#
import { card } from './card.style';
craftComponent(
'Card',
{
providers: [provideCardStore()],
host: { class: card.root },
},
/* … */
);
providers— the component's own DI scope, mounted before the function runs.host— default properties for the root element. Itsclasscomes from a sheet, like every class.
The meta carries no CSS. A component's look lives in a *.style.ts sheet beside it — see Styling a component: the only way. craft-ts/no-component-css refuses any .css import.
Composing behaviour#
.pipe(...) attaches directives, which transform the service the component takes and the template it returns, left to right:
const EditablePanel = Panel.pipe(WithPermission);
The same mechanism carries withProviders(...) and the exception handlers below. Use withComponentProviders(...) to configure instance-local services from the component's typed input readers. See Directives and .pipe(...).
Mounting the root#
The app root is a Craft component too:
// app.config.ts
export const appConfig = craftAppConfig({
providers: [provideCraftRootComponent(App)],
});
// main.ts
import { bootstrapCraft } from '@craft-ts/component';
import { appConfig } from './app.config';
bootstrapCraft({ config: appConfig });
bootstrapCraft builds the root injector, runs the app-start hooks, then mounts the root component into <craft-root> (or the element you pass as host).
Pitfalls#
Reading a reader outside a binding. h1(tasks().length) evaluates once at build time. Pass the reader (p(tasks.remaining)) or use a generator: h1(function* () { return yield* tasks.remaining(); }).
Forgetting track in forNode. Without a stable identity the renderer cannot reuse, move or remove the right node.
Exceptions raised while the component declares itself, or by its providers, don't vanish. They become the component's initialization exceptions and flow up to the route unless handled with .pipe(catchNode.exhaustive(...)) — see Exceptions as values.
Naming mismatch. The first argument must match the exported binding; the craft-component-name-match rule enforces it.
See Also#
Learn: your first state — the guided version
Reactive list positions#
The render callback's second argument is a read-only InputValue<number>. Read it in the binding or action that needs the current position:
import { craftComponent, forNode, p } from '@craft-ts/component';
const users = craftSignal([
{ id: 1, name: 'Ada' },
{ id: 2, name: 'Lin' },
]);
const NumberedList = craftComponent('NumberedList', {}, () =>
forNode(users, { track: (user) => user.id }, (user, index) =>
p(function* () {
return `${(yield* index()) + 1}. ${(yield* user()).name}`;
}),
),
);
Pass the reader directly to a child input, for example Row({ position: index }) when Row declares position: Input<number>. Its identity stays stable for the lifetime of the key. renderTemplate(row, { index }) also accepts the reader; it resolves that context field reactively before calling the template.
Reordering moves existing DOM and updates index consumers. A row template that does not read its index does not rerun solely because its position changed. An item replacement or a changed render callback still updates the row.
The track(item, index) callback continues to receive a plain numeric index. Use a stable item key such as user.id for reorderable lists. There is no numeric render-callback overload: replace index + 1 with (yield* index()) + 1 inside a generator binding. Interpolation of the reader (String(index) or `${index}`) is rejected by craft-ts/no-raw-for-index.
Overlays outside the component DOM#
Use portalNode to mount an overlay in the document body or an application overlay root while keeping its template's injector, reactivity and cleanup.