Creating a component
A component is a class deriving from Component. Its
Render method returns a virtual node tree. Styles are real
CSS files embedded in the assembly.
From the CLI
Run this from the project directory:
donkeh new component FileList
That creates one folder per component:
It also updates the project file and writes the assembly attribute:
using Donkeh.UILab;
using static Donkeh.UILab.HtmlHelper;
[assembly: Donkeh.UILab.Stylesheet("src/Components/FileList/FileList.css")]
namespace MyApp.Components;
public sealed class FileList : Component
{
public override Node Render() =>
Div(new() { ClassName = "file-list" });
}
.file-list {
display: block;
}
<ItemGroup>
<EmbeddedResource Include="src/Components/FileList/FileList.css" />
</ItemGroup>
Writing one by hand
Components can render elements, text, other components, fragments and
conditional/list helpers. Use the typed HtmlHelper builders
for common tags, or the terse _ helpers such as
H and Text.
using Donkeh.UILab;
using static Donkeh.UILab.HtmlHelper;
using static Donkeh.UILab._;
[assembly: Donkeh.UILab.Stylesheet("src/Components/Card/Card.css")]
namespace MyApp.Components;
public sealed class Card : Component
{
public override Node Render() =>
Div(new() { ClassName = "card" },
H2(new() { ClassName = "card-title" }, Text("Hello")),
P(new() { ClassName = "card-copy" },
Text("A small card component.")),
Button(new()
{
ClassName = "card-action",
OnClick = () => Console.WriteLine("clicked")
}, Text("Open")));
}
.card {
padding: 20px;
border: 1px solid #dce2ec;
border-radius: 14px;
background: #ffffff;
}
.card-title {
margin: 0 0 8px;
font-size: 18px;
}
.card-action:hover {
background: #eef1ff;
}
Typed HTML helpers
HtmlHelper provides one factory per common HTML element. The
first argument is a Props instance, so target-typed
new() keeps the call short, and the remaining arguments are
children.
using static Donkeh.UILab.HtmlHelper;
using static Donkeh.UILab._;
public override Node Render() =>
Div(new() { ClassName = "toolbar" },
Span(new() { ClassName = "toolbar-title" }, Text("Files")),
Input(new() { Type = "search", Placeholder = "Search" }),
Button(new() { ClassName = "primary" }, Text("Open")));
| Helper | Element |
|---|---|
Div, Section, Main | Page structure |
H1…H6, P | Headings and paragraphs |
Span, A, Strong | Inline content |
Button, Input, Select, Textarea | Form controls |
Img, Picture, Source | Media |
The typed helpers produce the same nodes as
H("div", ...), so the two styles can be mixed freely. Use
whichever makes the component easier to read.
Props and typed components
A component receives values from its parent through a props object.
Define a props class, then derive the component from
Component<TProps>. Inside the component, the current
payload is available as the Props property.
Defining custom props
Props are plain classes. Properties are usually init-only
with sensible defaults, so callers set only the values they need:
using Donkeh.UILab;
using static Donkeh.UILab._;
public sealed class BadgeProps
{
public string Label { get; init; } = "";
public bool Strong { get; init; }
public string? Tooltip { get; init; }
}
public sealed class Badge : Component<BadgeProps>
{
public override Node Render() =>
H("span", new Props
{
ClassName = Props.Strong ? "badge badge-strong" : "badge",
Title = Props.Tooltip
}, Text(Props.Label));
}
A props class does not have to derive from anything. Derive from
Props instead when you want its ready-made HTML attribute
surface, such as ClassName, Id or event
handlers, to be available on your props object.
Props is both a type and a property
In Component<TProps>, Props names the
current payload. When a local variable or parameter is also called
props, write this.Props to reach the payload.
The type keeps its full name Props.
H("div", new Props { ClassName = "toolbar" },
C<Badge, BadgeProps>(new BadgeProps { Label = "New" }),
C<Badge, BadgeProps>(new BadgeProps
{
Label = "Urgent",
Strong = true,
Tooltip = "Needs attention"
}));
Use the typed C<TComponent, TProps> overload so the
compiler checks the payload type. The untyped
C<TComponent>(object?) overload also works when the
payload is built dynamically.
Accepting children
When a component should wrap content supplied by its parent, derive its
props from PropsWithChildren. That class contains a single
Children property and nothing else, so components that only
want children do not have to inherit the whole HTML attribute surface.
using Donkeh.UILab;
using static Donkeh.UILab.HtmlHelper;
using static Donkeh.UILab._;
public sealed class PanelProps : PropsWithChildren
{
public string Heading { get; init; } = "";
}
public sealed class Panel : Component<PanelProps>
{
public override Node Render() =>
Section(new() { ClassName = "panel" },
H2(new() { ClassName = "panel-heading" }, Text(Props.Heading)),
Div(new() { ClassName = "panel-body" },
F(Props.Children ?? [])));
}
C<Panel, PanelProps>(new PanelProps
{
Heading = "Files",
Children =
[
P(new() { ClassName = "empty" }, Text("No files yet.")),
Button(new() { ClassName = "primary" }, Text("Upload"))
]
});
Children is a Node?[]?. The parent builds the
nodes and the component decides where they appear. It is
null when the caller passes none, so use
Props.Children ?? []. F groups the nodes without
adding an element, which is what lets them sit directly inside an element
that also has its own children.
A component that needs nothing but children can use
Component<PropsWithChildren> directly:
public sealed class Panel : Component<PropsWithChildren>
{
public override Node Render() =>
Div(new() { ClassName = "panel" }, F(Props.Children ?? []));
}
// Usage
C<Panel, PropsWithChildren>(new PropsWithChildren
{
Children = [Text("Everything passed here is rendered inside the panel.")]
});
If a component needs its own values and children, derive the
props class from PropsWithChildren and add the extra
properties, as PanelProps does above. Children are always
passed through the props object, not as extra arguments to C.
Composition helpers
| Helper | Use |
|---|---|
H(tag, props, children) | Create an element node. |
Text(value) | Create a text node; null becomes no node. |
C<T>() | Create a component node. |
Show(condition, node) | Include a node only when true. |
Each(items, item => node) | Project a sequence into a fragment. |
F(params nodes) | Group nodes in a transparent fragment. |
Give list children a stable Key so reordering reuses the
existing node and component state:
var rows = items.Select(item =>
H("div", new Props
{
Key = item.Id,
ClassName = "row"
}, Text(item.Name))).ToArray();
return H("div", new Props { ClassName = "list" }, rows);
CSS in the assembly
The [Stylesheet] attribute is metadata only. The CSS file must
also be an EmbeddedResource in the same assembly. The host
loads every declaration through Stylesheet.Load() and merges
them in declaration order after the built-in user-agent sheet.
<ItemGroup>
<EmbeddedResource Include="src/Components/Card/Card.css" />
<EmbeddedResource Include="src/Components/Toolbar/Toolbar.css" />
</ItemGroup>
src/Components/Name/Name.css.
Styles are ordinary CSS: class selectors, IDs, attribute selectors, pseudo-classes, media queries, custom properties, keyframes and transitions. The built-in inspector can edit the matched rules live.
Hot reload
Hot reload is opt-in. Enable it once for the executable project:
donkeh enable-feature hot-reload
donkeh watch
The first command adds a reference that exists only in the Debug
configuration. The second runs the project through dotnet watch
and keeps it running. Supported C# edits, such as changing a
Render method body, are applied to the running process by .NET
Hot Reload. The development package watches source files, waits for the
patch to settle and then asks the window to re-render every mounted
component. Instance state survives when the hook order did not change.
Edits that require new types, signatures or base classes make
dotnet watch restart the app. Changing the hook order or a
hook's type is not detected automatically; press Ctrl+R to restart when
doing that.
Stylesheet edits take a different path. The desktop host watches the source
file behind every [Stylesheet] declaration and rebuilds the
entire cascade in place: user-agent rules, author sheets, style caches and
layout engines. CSS is marked Watch="false" for
dotnet watch, so a stylesheet save does not cause a build or
restart.
The build still embeds every stylesheet. At runtime the reloader prefers
the file on disk and falls back to the embedded copy when a file cannot be
found. Declared paths are resolved relative to the project that wrote
them, so both src/Components/Card/Card.css and
test-container/Styles/gallery.css are found from a test
container. Files are polled on the frame thread and read only after they
have been stable for one interval, which avoids loading a half-written
file.
Release builds do not reference the hot reload package, so neither its assembly nor the file watcher is copied to the final application. The feature is development-only by construction, not removed by a publish step.
var window = new DonkehWindow(settings);
#if DEBUG
Donkeh.HotReload.HotReloadHost.Attach(window);
#endif
window.Run(root);
Set DONKEH_HOT_RELOAD=0, false or
off to disable it. Only declared stylesheets are watched;
external @import targets and embedded images are resolved by
the normal loader and cached for the session.
Embedded images
Images use the same pattern: declare them with [Image] and
embed the file. The resolver checks the on-disk path first, then the
embedded bytes declared in the assembly.
<ItemGroup>
<EmbeddedResource Include="Assets/logo.png" />
<EmbeddedResource Include="Assets/hero.jpg" />
</ItemGroup>
[assembly: Donkeh.UILab.Image("Assets/logo.png")]
[assembly: Donkeh.UILab.Image("Assets/hero.jpg")]
H("img", new Props
{
Src = "Assets/logo.png",
Alt = "Logo"
});
// CSS
H("div", new Props { ClassName = "hero" });
.hero {
min-height: 280px;
background-image: url("Assets/hero.jpg");
background-size: cover;
background-position: center;
}
The same asset pipeline is used by img, CSS
url(...) backgrounds, and the window icon through
AppRoot.Icon or WindowSettings.Icon. For code
that needs raw bytes, use Image.TryGetBytes("Assets/logo.png", out var bytes).
EmbeddedResource, declare
it with [Image], and refer to it with the same
project-relative path. The browser host receives the decoded image
through the same virtual tree.