# NetWasm.UI > A reflection-free, signal-driven C# UI framework for the browser, compiled ahead-of-time to WebAssembly with NetWasm. Inspired by Solid and Svelte rather than Blazor: components build their DOM once, fine-grained signals patch exactly the nodes that changed, and components are written as `.nwui` templates (HTML with Razor-style `@`) or in C#. Key facts for code generation: - Packages are `NwUi.*` on NuGet (`NwUi.Browser` for an app, `NwUi.Templates` for `dotnet new netwasm-ui`); namespaces are `NetWasm.UI.*`. Apps target `net10.0-netwasm` with the NetWasm SDK pinned in `global.json`. - `Build()` and template markup run once. Only reads inside lambdas (`Text(() => …)`, `When`, `Each`, `@expr`) update. - There is no reflection: use source-generated `System.Text.Json`, and libraries that do not rely on reflection. - `.nwui` control flow is only `@if` and `@foreach`; each template, branch and loop body has exactly one root node. - The complete documentation in one file: [llms-full.txt](https://matengo.github.io/NetWasm.UI/llms-full.txt). An agent skill: [skills/netwasm-ui/SKILL.md](https://raw.githubusercontent.com/matengo/NetWasm.UI/main/skills/netwasm-ui/SKILL.md). --- # NetWasm.UI A reflection-free, signal-driven C# UI framework for the browser, compiled ahead-of-time to WebAssembly with [NetWasm](https://www.netwasm.com). Inspired by Solid and Svelte rather than Blazor: components build their DOM once, fine-grained signals patch exactly the nodes that changed, and every state change crosses the Wasm→JS boundary **at most once**. **Website and live examples: [matengo.github.io/NetWasm.UI](https://matengo.github.io/NetWasm.UI/)**, itself a NetWasm.UI app ([source](site/)). > **Status: 0.18, an early but usable release.** The packages are on NuGet and the framework is > tested in Chromium, Firefox and WebKit. The public API may still change in 0.x releases; every > change is listed in the [CHANGELOG](CHANGELOG.md). See > [Compatibility and versioning](docs/compatibility.md). ## Get started in 30 seconds You need the [.NET SDK 10.0.3xx or 11](https://dotnet.microsoft.com/download). ```shell dotnet new install NwUi.Templates dotnet new netwasm-ui -o MyApp cd MyApp dotnet nwui-dev # → http://localhost:8765, rebuilds and reloads on save ``` The template brings: - a router, - a C# component, - two `.nwui` pages, - CSS, - the `nwui-dev` dev server, as a local .NET tool. Want an ASP.NET Core backend on the same origin? Use the hosted template (needs .NET 11). It creates a client, a server and a shared library, with prerendering and live reload: ```shell dotnet new netwasm-ui-hosted -o MyApp cd MyApp dotnet watch --project MyApp.Server --no-hot-reload ``` Building a component library? `dotnet new netwasm-ui-lib -o MyUi` creates a headless library and its tests; see the [component library tutorial](docs/component-library-tutorial.md). Every template includes an `AGENTS.md` for AI coding agents; see [AI coding assistants](docs/ai-assistants.md). Read [Getting started](docs/getting-started.md) next. ## Packages All packages are on nuget.org and are released together with the same version number. Package IDs start with `NwUi` because the `NetWasm.` prefix on nuget.org belongs to the NetWasm toolchain; the namespaces are `NetWasm.UI`. | Package | What it is | Install | |---|---|---| | [`NwUi.Browser`](https://www.nuget.org/packages/NwUi.Browser) | The package an app references: the browser host and the `nwui.dom` module. It brings in `NwUi`. | `dotnet add package NwUi.Browser` | | [`NwUi`](https://www.nuget.org/packages/NwUi) | The core: signals, components, router, forms and the `.nwui` template compiler. | Comes with `NwUi.Browser`. | | [`NwUi.Templates`](https://www.nuget.org/packages/NwUi.Templates) | `dotnet new netwasm-ui`, `dotnet new netwasm-ui-hosted` (ASP.NET Core) and `dotnet new netwasm-ui-lib` (component library). | `dotnet new install NwUi.Templates` | | [`NwUi.DevServer`](https://www.nuget.org/packages/NwUi.DevServer) | `dotnet nwui-dev`: publishes, serves (Brotli, SPA fallback) and live-reloads. | In the template. Otherwise `dotnet tool install --local NwUi.DevServer`. | | [`NwUi.AspNetCore`](https://www.nuget.org/packages/NwUi.AspNetCore) | Hosts the app in ASP.NET Core next to your API: `MapNetWasmUI()`, live reload and client publishing. See [ASP.NET Core](docs/deployment.md#aspnet-core-with-an-api-on-the-same-origin). | `dotnet add package NwUi.AspNetCore` (in the server). | | [`NwUi.Workers`](https://www.nuget.org/packages/NwUi.Workers) (preview) | Typed C# Web Workers: a shared interface, `AddWorker()` / `AddWorkerPool()` and a source generator. See [Web Workers](docs/workers.md). | `dotnet add package NwUi.Workers` in the app, the worker and the contracts project. | | [`NwUi.Primitives`](https://www.nuget.org/packages/NwUi.Primitives) (preview) | Headless components for design systems: disclosure, compound tabs, focus scope and roving focus. See [Building a headless library](docs/headless-libraries.md#building-on-nwuiprimitives). | `dotnet add package NwUi.Primitives` in the component library or app. | | VS Code: *NetWasm.UI templates (.nwui)* | Syntax highlighting for `.nwui`. | See below. | ### VS Code extension The extension is not on the Marketplace yet. Install it from a GitHub release: 1. Download `nwui.vsix` from the [latest release](https://github.com/matengo/NetWasm.UI/releases/latest). 2. Run `code --install-extension nwui.vsix`. Or, in VS Code, open the Extensions view, click **…** and choose **Install from VSIX…**. To build it from source, see [tools/vscode-nwui](tools/vscode-nwui/README.md). ## Quick look You write components as `.nwui` templates (HTML with Razor-style `@`). A source generator compiles them at build time: ```razor @* CounterView.nwui → public partial class CounterView : Component *@

Counter

Count: @count · doubled: @doubled

@if (count.Value >= 10) {

That's a lot of clicks!

}
@code { private readonly Signal count = new(0); private Computed doubled = null!; partial void OnInit() => doubled = new Computed(() => count.Value * 2); } ``` Prefer plain properties? `[Reactive]` puts a signal behind a `partial` property, in `@code` or any C# class ([Reactive properties](docs/reactivity.md#reactive-properties)): ```razor @code { [Reactive] private partial int Count { get; set; } } ``` You can also write components directly in C#, which is what the generator emits: ```csharp public sealed class CounterView : Component { private readonly Signal count = new(0); protected override Node Build() { var doubled = new Computed(() => count.Value * 2); return Section( H2("Counter"), P("Count: ", Strong(Text(count)), " · doubled: ", Text(doubled)), Button(OnClick(() => count.Value++), "+1"), Button(Disabled(() => count.Value == 0), OnClick(() => count.Value = 0), "Reset"), When(() => count.Value >= 10, () => P("That's a lot of clicks!"))); } } ``` ## Size and speed - **Size:** the whole demo app (counter, todos, router, forms, nested components) is about **135 KB** with Brotli, Wasm and JavaScript together. CI fails a pull request that grows it past its [size budget](size-budget.json). - **Speed:** in a [js-framework-benchmark-style comparison](docs/benchmarks.md), DOM updates are on par with SolidJS (0.85–1.07× its time; slowest when appending rows), and reactive and compute workloads are faster than Solid, most of them about 2× (up to 9× for compute). It is faster than React on every DOM case, and 3–36× faster than Blazor WebAssembly (interpreter) with a ~17× smaller download. - **Startup:** `dotnet publish` adds preload tags for the runtime modules and the Wasm to `index.html`, so everything downloads in parallel instead of one import level at a time. On ordinary broadband the demo app renders in about 315 ms instead of 700 ms. See [Startup preloading](docs/deployment.md#startup-preloading). With `NetWasmUIPrerender=true`, the first screen of each listed page is rendered into its HTML at publish time, so content shows before the Wasm has loaded. See [Prerendering](docs/deployment.md#prerendering). ## Requirements | | | |---|---| | .NET SDK | 10.0.3xx or 11.0.x (C# 15 needs 11). The NetWasm SDK is resolved from `global.json`. | | NetWasm.Sdk | 0.15.2, target framework `net10.0-netwasm` | | Browsers | Chrome/Edge 137+, Firefox 131+, Safari 18.4+ (needed for Wasm exception handling with `exnref`) | **Licensing.** NetWasm.UI is MIT. The NetWasm compiler and tools use the [NetWasm Community License](https://github.com/zion-sati/NetWasm): - It is free for individuals, open source, education, and organisations with fewer than 250 employees and under USD 10 M in revenue. - Larger organisations need a sponsorship. - NetWasm's CoreLib and runtime are MIT, and the apps you build can use any license. Check the current terms before you adopt it. ## Try the samples From a clone of this repository: ```powershell dotnet run --project tools/DevServer -- samples/Counter # counter, todos, routing, forms, components dotnet run --project tools/DevServer -- samples/Fetch # HttpClient + System.Text.Json with Suspense dotnet run --project tools/DevServer -- samples/Widgets # several apps on one page dotnet run --project tools/DevServer -- samples/Interop # a JS library wrapped in a component dotnet run --project tools/DevServer -- samples/Primitives # dialog, popover, tabs, disclosure, generic select and table dotnet run --project tools/DevServer -- samples/Tsp # route optimizer in a pool of Web Workers dotnet run --project tools/DevServer -- site # the project website dotnet run --project samples/Hosted/Hosted.Server # hosted in ASP.NET Core with an API ``` ## Documentation - [Getting started](docs/getting-started.md): the template, the dev server and a first component - [Components and the C# API](docs/components.md), including [building component libraries](docs/components.md#building-component-libraries): element calls, outside-click listeners, DOM reads, portals and ids - [Templates (`.nwui`)](docs/templates.md) - [Tutorial: a component library](docs/component-library-tutorial.md): headless library, tests, design system, NuGet - [Building a headless library](docs/headless-libraries.md): conventions, compound components, patterns, accessibility - [Reactivity](docs/reactivity.md): signals, batching, context, events, lifecycle - [Services and DI](docs/services.md): `Services`, `Inject()`, `@inject` - [Async data and Suspense](docs/async.md): `Resource`, `Suspense`, `HttpClient` - [Forms and validation](docs/forms.md) - [Routing](docs/routing.md): parameters, nested routes, base path - [Testing](docs/testing.md): rendering components in unit tests (preview) - [Error handling](docs/error-handling.md): `ErrorBoundary` and `App.OnError` - [Web Workers](docs/workers.md): C# services in Web Workers, one per service or a pool (preview) - [JavaScript interop](docs/js-interop.md): `[JSImport]`, callbacks, wrapping JS libraries - [Libraries and packages](docs/libraries.md): NuGet, .NET Standard and component libraries - [Embedding and several apps on one page](docs/embedding.md) - [Publishing and size](docs/deployment.md) - [Security](docs/security.md): Content Security Policy, Trusted Types, XSS - [Compatibility and versioning](docs/compatibility.md) - [Architecture](docs/architecture.md) - [Benchmarks](docs/benchmarks.md) - [Troubleshooting and known limitations](docs/troubleshooting.md) - [AI coding assistants](docs/ai-assistants.md): `AGENTS.md`, the agent skill, Context7, `llms.txt` ## AI coding assistants NetWasm.UI is new, so AI models have not seen it in training. Give your assistant the docs: - **`AGENTS.md`:** projects created with `dotnet new netwasm-ui`, `netwasm-ui-hosted` and `netwasm-ui-lib` include an `AGENTS.md` with the rules agents most often get wrong. - **Agent skill:** copy [`skills/netwasm-ui`](skills/netwasm-ui/SKILL.md) to your project's `.github/skills/` (GitHub Copilot) or `.claude/skills/` (Claude Code). - **Context7:** assistants with the Context7 MCP server can look up the current docs and samples. - **`llms.txt`:** [llms.txt](https://matengo.github.io/NetWasm.UI/llms.txt) indexes the guides, and [llms-full.txt](https://matengo.github.io/NetWasm.UI/llms-full.txt) is all of them in one file. [AI coding assistants](docs/ai-assistants.md) shows how to set each one up. ## Repository layout | Path | What | |------------------------------|----------------------------------------------------------------------| | `src/NetWasm.UI` | Core: reactivity, binary renderer, component/builder API, router, forms. Targets `net10.0-netwasm`, plus `net10.0` for tests. | | `src/NetWasm.UI.Browser` | Browser host: `[JSImport]` bindings and the `dom.mjs` decoder. `net10.0-netwasm` only. | | `src/NetWasm.UI.Generator` | Roslyn source generator: `*.nwui` templates → `Component` partial classes. Ships inside the `NwUi` package. | | `src/NetWasm.UI.AspNetCore` | `NwUi.AspNetCore`: hosting in ASP.NET Core, live reload and client publishing. | | `src/NetWasm.UI.Primitives` | `NwUi.Primitives`: headless components (`netstandard2.1`): disclosure, compound tabs, focus scope. | | `samples/Counter` | Demo app: counter, todos, routing, nested routes, forms and `/components`. | | `samples/Fetch` | `HttpClient` + `System.Text.Json` with `Resource` and `Suspense`. | | `samples/Widgets` | Several independent apps (Wasm instances) on one page. | | `samples/Interop` | `[JSImport]`, `JSObject`, callbacks and Promises: a JS library in a component. | | `samples/Primitives` | Reference components for a component library: dialog, popover, tabs, disclosure, generic select and data table. | | `samples/Primitives.Theme` | A design system on top of `NwUi.Primitives`: wrapper components and a stylesheet asset. | | `samples/Tsp` | Route optimizer (traveling salesman) in a pool of Web Workers; also on GitHub Pages at `/tsp/`. | | `samples/Hosted` | ASP.NET Core server with a weather API hosting a prerendered client; uses only the NuGet packages. | | `site/` | The project website, built with NetWasm.UI and published to GitHub Pages. | | `templates/` | The `dotnet new netwasm-ui`, `netwasm-ui-hosted` and `netwasm-ui-lib` template package. | | `tests/NetWasm.UI.Tests` | xunit tests against an in-memory `FakeDomHost`. | | `tests/NetWasm.UI.E2E` | Playwright browser tests against the samples (Chromium, Firefox, WebKit). | | `tools/DevServer` | `nwui-dev`: Kestrel dev server with Brotli, live reload and an error overlay. | | `tools/size-report` | Brotli/gzip size report and the budget check CI runs. | | `tools/vscode-nwui` | VS Code extension: `.nwui` syntax highlighting. | | `benchmarks/` | Comparison with SolidJS, React and Blazor WebAssembly. | ## Known limitations - No reflection on NetWasm, so libraries that rely on it throw at run time. See [Libraries and packages](docs/libraries.md). - One app per Wasm module. - No server-side rendering (SSR) per request. Pages can be [prerendered](docs/deployment.md#prerendering) at publish time, but the app replaces that markup when it starts (no hydration yet), so handlers only work once the Wasm has loaded. - No hash routing; the server must fall back to `index.html` for app routes. - No hot reload; live reload takes ~3 s and keeps simple signal values and form state. - `.nwui` has syntax highlighting but no IntelliSense. Control flow is only `@if`/`@foreach`, and generic components need explicit type arguments (`TItem="Fruit"`). See [Troubleshooting](docs/troubleshooting.md#known-limitations). ## Contributing See [CONTRIBUTING.md](CONTRIBUTING.md) for building, tests, the public API workflow and the roadmap. See [CHANGELOG.md](CHANGELOG.md) for what has changed. ## License MIT – see [LICENSE](LICENSE). --- # Getting started ## Prerequisites - .NET SDK 10.0.303 or later; .NET 11 works too and is needed for C# 15. `global.json` rolls forward to the latest installed SDK. - The NetWasm SDK is pinned in `global.json` (`"msbuild-sdks": { "NetWasm.Sdk": "0.15.2" }`). It downloads its host tooling on first restore. - A browser listed in [Compatibility](compatibility.md#browsers). ## From the template ```shell dotnet new install NwUi.Templates dotnet new netwasm-ui -o MyApp cd MyApp dotnet nwui-dev ``` `dotnet new` restores the project and the local `nwui-dev` tool. Open http://localhost:8765/. The template contains: | File | What it is | |---|---| | `MyApp.csproj` | A NetWasm page app that references `NwUi.Browser`. | | `global.json` | Pins the NetWasm SDK. | | `.config/dotnet-tools.json` | The `nwui-dev` dev server. | | `Program.cs` | The `[JSExport("start")]` entry point. | | `App.cs` | The root component: navigation and routes, written in C#. | | `Pages/*.nwui` | Two pages written as templates. | | `wwwroot/` | `index.html`, `app.mjs` and `app.css`. Published to the site root. | | `AGENTS.md` | Instructions for AI coding agents, with links to the full docs. See [AI coding assistants](ai-assistants.md). | ## The pieces, by hand To add NetWasm.UI to an existing NetWasm project, you need the same pieces as the template. **`MyApp.csproj`** ```xml net10.0-netwasm JsModule page MyApp ``` The packages set up the rest: - `NwUi.Browser` adds the `nwui.dom` JavaScript module to the app. Set `false` to supply your own module, for example a custom `createDomHost` (see [Embedding](embedding.md)). - `NetWasm.UI` feeds every `*.nwui` file to the template compiler. Set `false` to turn that off. **`Program.cs`** – the entry point that JavaScript calls: ```csharp using System.Runtime.InteropServices.JavaScript; using NetWasm.UI.Browser; namespace MyApp; public static partial class Program { [JSExport("start")] public static void Start() => BrowserApp.Start(new App(), "#app"); } ``` `BrowserApp.Start` connects the DOM host, installs the browser router and mounts the root component into the element that matches the selector. **`App.cs`** – the root component: ```csharp using NetWasm.UI; using NetWasm.UI.Reactive; using static NetWasm.UI.Html; namespace MyApp; public sealed class App : Component { private readonly Signal count = new(0); protected override Node Build() => Main( H1("Hello NetWasm.UI"), Button(OnClick(() => count.Value++), "Clicked ", Text(count), " times")); } ``` **`wwwroot/index.html`** and **`wwwroot/app.mjs`** – the page and the module that starts the app. Use absolute URLs so that deep links such as `/todos/3` still find the assets: ```html MyApp
``` ```js import { open } from "/browser/MyApp.mjs"; const app = await open(); app.start(); ``` ## Developing ```shell dotnet nwui-dev # in the app folder; or: dotnet nwui-dev path/to/MyApp ``` The dev server does the following: - publishes the app; - serves it with the right MIME types, Brotli/gzip and a fallback to `index.html` for deep links; - watches `.cs`, `.nwui` and asset files; - reloads the browser after each rebuild; - shows build errors as an overlay in the page. Install it outside the template with `dotnet tool install NwUi.DevServer`. `dotnet run` from the NetWasm SDK also serves the app, but it has no deep-link fallback, so a reload on `/counter` returns 404. | Option | Meaning | |---|---| | `--port ` | Port (default 8765) | | `-O O0\|O1\|Oz` | NetWasm optimization (default `O0`: only changed methods are recompiled) | | `--release` | Same as `-c Release -O Oz`: production sizes | | `-c Debug\|Release` | Configuration (default `Debug`) | | `--no-watch` | Serve only | | `--no-publish` | Skip the initial publish | | `-w ` | Watch root (default: the nearest folder containing `.git` or `global.json`) | There is no hot reload. NetWasm compiles ahead of time, so there is no runtime to patch. A rebuild after a one-line change takes about 3 s from save to reloaded page; see [CONTRIBUTING.md](../CONTRIBUTING.md#rebuild-time) for where the time goes. The reload keeps your state: - `Signal`, `Signal` and `Signal` values (also inside `Computed` inputs, components and services); - text fields, checkboxes and selects, the focused element and the cursor position; - the scroll position. Signals are matched by the order they are created in and by their initial value. A signal whose initial value changed in the edit, or that is created in a different order (for example after you navigated elsewhere), starts fresh. Lists and other object values are not kept. Pressing F5 always starts clean. State is kept only in `Debug` builds: the source generator then adds a module initializer that connects to the dev server. `--release` and production builds do not include it. Set `false` to turn it off, or `true` to force it on. ## Next - [Components and the C# API](components.md) or [Templates (`.nwui`)](templates.md) to build UI. - [Reactivity](reactivity.md) for state. - [Libraries and packages](libraries.md) to use NuGet packages or your own component libraries. - [Publishing and size](deployment.md) when you are ready to ship. - [AI coding assistants](ai-assistants.md) to give your coding agent the current docs. --- # Components and the C# API Everything in NetWasm.UI is built from the static methods on `NetWasm.UI.Html`. `.nwui` [templates](templates.md) compile to exactly these calls, so this page describes both. ```csharp using NetWasm.UI; using NetWasm.UI.Reactive; using static NetWasm.UI.Html; ``` ## Components ```csharp public sealed class CounterView : Component { private readonly Signal count = new(0); protected override Node Build() { var doubled = new Computed(() => count.Value * 2); return Section( H2("Counter"), P("Count: ", Strong(Text(count)), " · doubled: ", Text(doubled)), Button(OnClick(() => count.Value++), "+1"), Button(Disabled(() => count.Value == 0), OnClick(() => count.Value = 0), "Reset"), When(() => count.Value >= 10, () => P("That's a lot of clicks!"))); } } ``` - `Build()` runs **exactly once**, untracked, inside the component's own `Scope`. It is not a render function: nothing re-runs it. Updates come from reactive pieces (`Text(() => …)`, `Class(() => …)`, `When`, `Each`, …) that each own a small effect. - A component can be used anywhere content is expected: `Div(new CounterView())`. - `Render()` builds it (once) and returns the root node; `Root` is that node; `Dispose()` removes it from the DOM and disposes everything created in its scope. ### Static components A piece of UI without state doesn't need a class. A plain method that returns a `Node` works anywhere content is expected: ```csharp private static Node Card(string title, string body) => Div(Class("card"), H3(title), P(body)); Section( Card("Fast", "Signals update only what changed."), Card("Small", "About 150 KB Brotli for the demo app.")); ``` It runs once when it is called and has no scope of its own. Its reactive parts, such as `Text(() => …)`, belong to the component that called it. Use a `Component` when you need signals that are local to the component, lifecycle hooks or `Dispose()`. ## Elements and content Element functions take `params Content[]`. `Content` converts implicitly from `string`, `Node`, `Attr`, `Listener`, `Component` and fragments (`When`, `Each`, `Slot`, `Routes`), so attributes, events and children can be mixed in any order: ```csharp Div(Class("card"), H3("Title"), P("Body"), Button(OnClick(Save), "Save")) ``` Elements: `Div`, `Span`, `P`, `H1`–`H3`, `Ul`, `Ol`, `Li`, `Button`, `Input`, `Label`, `Form`, `Section`, `Header`, `Footer`, `Main`, `Nav`, `A`, `Strong`, `Em`, `Small`, `Table`, `Thead`, `Tbody`, `Tr`, `Th`, `Td`, `Select`, `Option`, `Textarea`, `Pre`, `Code`, `Img`, `Br`, `Hr`. Anything else: `El("article", …)`. SVG elements are made with `SvgEl`, the `` element and everything inside it: `SvgEl("svg", Attr("viewBox", "0 0 10 10"), SvgEl("circle", Attr("r", "4")))`. An element made with `El` is an HTML element, which the browser does not draw inside an ``. An `Element` you keep a reference to can be focused (`input.Focus()`) or given more content later (`el.Add(...)`). ## Text | Call | Updates when | |---|---| | `"literal"` or `Text("literal")` | never | | `Text(signal)` | the signal or computed changes | | `Text(() => a.Value + " " + b.Value)` | any signal read in the lambda changes | | `Text(() => count.Value)` | same; numbers, `bool` and strings are formatted without boxing, `null` prints nothing | ## Attributes and properties | Call | Notes | |---|---| | `Attr("data-x", "1")`, `Attr("aria-label", () => …)` | static or reactive attribute; returning `null` removes it | | `Class(…)`, `Style(…)` | string or `Func` | | `Id`, `Type`, `Href`, `Src`, `Alt`, `Placeholder`, `Title` | static attributes | | `Disabled(bool)`, `Disabled(() => …)` | toggled attribute | | `Autofocus()` | | | `Value("…")`, `Value(() => …)` | sets the `value` **property** (what the user sees), not the attribute | | `Checked(() => …)` | sets the `checked` property | Reactive attributes only send an op when the value actually changed. ## Events ```csharp Button(OnClick(() => count.Value++), "+1") Input(OnInput(e => name.Value = e.Value)) Input(OnKeyDown(e => { if (e.Key == "Enter") Add(); })) Form(OnSubmit(_ => Save()), …) // OnSubmit prevents the default submit Div(On("pointerdown", e => Start(e.ClientX, e.ClientY), ListenerFlags.StopPropagation)) ``` Helpers: `OnClick`, `OnInput`, `OnChange`, `OnKeyDown`, `OnSubmit`, `OnDblClick`, `OnBlur`, and `On(name, handler, flags)` for any event. `ListenerFlags` (in `NetWasm.UI.Dom`): `PreventDefault`, `StopPropagation`, `PreventDefaultPlainClick` (prevent only an unmodified primary click; used by `Link`), `Capture` (run in the capture phase, before listeners below) and `Passive` (promise not to call `preventDefault`, for `touchmove`, `wheel` and `scroll`). `Capture` and `Passive` listeners are added to the element itself instead of being delegated; `Passive` with `PreventDefault` throws. `DomEvent` carries `Value`, `Checked`, `Key`, `Repeat`, `Ctrl`/`Shift`/`Alt`/`Meta`, `Button`, `ClientX`/`ClientY` and `IsPlainClick`. For overlays it also has `TargetId` and `RelatedTargetId` (the ids of the framework elements involved, 0 otherwise; test with `e.IsTarget(element)`), `Inside`/`RelatedInside` (see `within` under [Building component libraries](#building-component-libraries)) and `NewState` (`"open"`/`"closed"` for `toggle` events of `popover` and `
`). Each handler runs inside a scheduler batch, so a handler that writes ten signals still produces one DOM update. ## Two-way binding `Bind` returns the `value`/`checked` property plus the matching listener; place it with `Spread`: ```csharp var name = new Signal(""); var done = new Signal(false); Input(Placeholder("Name"), Spread(Bind(name))) Input(Type("checkbox"), Spread(Bind(done))) ``` ## Conditionals and lists ```csharp When(() => user.Value is null, () => P("Signed out"), () => P("Hello ", Text(() => user.Value!.Name))) // the else branch is optional Ul(Each(items, i => i.Id, item => Li(Class(() => item.Done.Value ? "todo done" : "todo"), Label(Input(Type("checkbox"), Spread(Bind(item.Done))), " ", item.Title), Button(OnClick(() => Remove(item)), "×")))) ``` - `When` only rebuilds when the condition flips. The branch gets its own scope and is disposed when it is hidden. - `Each(items, key, render)` takes a `Func>` or an `IReadOnlySignal>`. Rows are keyed: a row is built once per key and moved, not rebuilt, when the list is reordered (a longest-increasing-subsequence diff gives the minimum number of moves). Put per-row state that changes in signals on the item (`item.Done`). - A row shows its key's item. When a new list has a different item for a key that stays (another object, or for a value type a value that is not equal), that row is disposed and rendered again for the new item, in the same place, and its local state starts over. Keep the same object to keep the row. - To change a list, assign a new list to the signal (`items.Value = newList`) or mutate and call `items.Touch()`. ### Exit animations `When(…).AnimateExit()` and `Each(…).AnimateExit()` (`@if (…) animate-exit` and `@foreach (…) animate-exit` in templates) let removed content animate out before it leaves the DOM. Shown content and new rows get `data-state="open"`. When a branch is hidden or a row removed, the element gets `data-state="closed"` and `inert`, and is removed once its CSS animations and transitions, and those of its descendants, have finished. With none, it is removed at once. The animation is plain CSS: ```css .toast { transition: opacity .2s, translate .2s; } @starting-style { .toast { opacity: 0; translate: 0 8px; } } /* entering */ .toast[data-state=closed] { animation: fade-out .2s forwards; } /* leaving */ @keyframes fade-out { to { opacity: 0; } } ``` The C# side is done with the content at once: its scope is disposed and a new branch or row can render beside it while it fades. A row that is rebuilt for a new item (see above) does not animate. `data-state` goes on the root element of the branch or row. A `` or `popover` element needs no `AnimateExit`: it stays in the DOM, so animate it with `transition-behavior: allow-discrete` on `display` and `overlay`: ```css dialog { opacity: 0; transition: opacity .2s, display .2s allow-discrete, overlay .2s allow-discrete; } dialog[open] { opacity: 1; } @starting-style { dialog[open] { opacity: 0; } } ``` ## Static templates (fast rows) `Div(…)`, `Td(…)` and friends send one op per element, attribute and text. For markup that is created many times (list rows, cards), parse the static part once with a `Template` and clone it: ```csharp static readonly Template RowTemplate = new( "
" + "" + "
×"); Node Row(Item item) => RowTemplate.Clone() .With(0, Class(() => selected.Value == item.Id ? "danger" : null)) // hole 0 = root .Text(1, item.Id.ToString()) // .With(2, OnClick(() => Select(item))) // .Text(3, () => item.Label.Value) // reactive text .With(4, OnClick(() => Remove(item))) .With(5, When(() => item.Open.Value, () => Td("details"))) // .Root; ``` Holes are numbered in document order; the root element is always hole 0: | Marker | Hole | Fill with | |---|---|---| | root element, or an element with a bare `$` attribute | element | `With(i, attrs, events, children…)`, `Ref(i, out el)`, `Element(i)` | | `` | text node | `Text(i, "…")`, `Text(i, () => …)`, `Text(i, () => number)` | | `` | insertion point | `With(i, …)`: content is inserted before the marker (`When`, `Each`, components, nodes) | The HTML must have one root element. Whitespace-only text that contains a line break is dropped, as in templates. The template is sent to the browser once and then cloned with `cloneNode`, so creating a row costs one op plus one per hole instead of one per node. `.nwui` templates do this automatically. Markup that is cloned into an ``, such as a row of circles, is SVG content: create it with `Template.Svg("")`, so its elements are SVG elements. ## Events and delegation Common bubbling events (`click`, `input`, `change`, `keydown`, `submit`, pointer/mouse up/down, `focusin`/`focusout`, …) are delegated: `dom.mjs` has one listener per event type on `document` and walks up from the target. `StopPropagation` stops that walk. Because the delegated handler runs at the document, a native listener you add yourself on an ancestor runs **before** it. Other events (`blur`, `focus`, `scroll`, `mouseenter`, …) get a listener on the element. ## Props Plain properties are read once when the parent builds: ```csharp public sealed class Badge : Component { public string Label { get; set; } = ""; protected override Node Build() => Span(Class("badge"), Label); } Div(new Badge { Label = "new" }) ``` For a value the child should follow, use `Prop`. It holds either a fixed value or a getter, and reading `.Value` inside a reactive context tracks whatever the getter reads: ```csharp public sealed class ProgressBar : Component { public Prop Value { get; set; } = 0; public Prop Max { get; set; } = 100; protected override Node Build() => Div(Class("progress"), Span(Text(() => Value.Value.ToString() + " / " + Max.Value.ToString()))); } new ProgressBar { Value = done } // Signal or Computed new ProgressBar { Value = new(() => done.Value * 10) } // any expression new ProgressBar { Value = 3 } // a fixed value ``` Reading `Value.Value` directly in `Build()` gives a snapshot, because `Build` is untracked. For two-way state, pass the `Signal` itself: `public Signal Count { get; set; } = new(0);`. ## Child content (slots) A `Slot` is content the parent supplies and the child places: ```csharp public sealed class Card : Component { public Slot? Actions { get; set; } public Slot? ChildContent { get; set; } protected override Node Build() => Section(Class("card"), Div(Class("actions"), Actions), // an unset slot renders nothing Div(Class("body"), ChildContent)); } new Card { Actions = new Slot(() => Button(OnClick(Reset), "Reset")), ChildContent = new Slot(() => P("Body ", Text(count))), } ``` The slot is built where the child places it, so it lives in the child's scope (and is disposed with it) but still reads the parent's signals. A `Slot` takes an argument, for per-item templates such as table cells. Place it with `slot.With(arg)`; in a template, `@render(slot, arg)`: ```csharp public Slot? Cell { get; set; } Td(Cell?.With(person)) new Table { Cell = new(p => Span(p.Name)) } ``` ## Spread `Spread(params Content[])` groups several pieces of content into one, which is handy for helpers that return attributes plus listeners (`Bind` is one): ```csharp static Content Tooltip(string text) => Spread(Attr("title", text), Attr("aria-label", text)); ``` ## Attributes Every component has `Attributes` (`Content[]`), which templates fill with the lowercase or dashed attributes and `@on…` handlers given on its tag (see [Attribute splatting](templates.md#attribute-splatting)). Apply them with `Splat`, which joins `class`/`style` with the given base value and attaches a fresh listener each time it is applied: ```csharp protected override Node Build() => Button(Attr("type", "button"), Splat(Attributes, baseClass: "btn"), Text(() => Label.Value)); ``` The caller sets them like any other property: ```csharp new MyButton { Label = label, Attributes = [Class("wide"), Attr("aria-label", "Save"), OnClick(Save)] } ``` ## Building component libraries The core has no dialog, popover or select. It has the pieces to build them in a separate library; `samples/Primitives` (a dialog, popover, tabs, select and data table) uses all of them. **Element calls.** `Element.Call(method, args…)` calls a method on the DOM element, after the pending DOM updates, with string arguments. Helpers: `ShowModal()`, `Show()`, `Close(returnValue)`, `ShowPopover()`, `HidePopover()`, `TogglePopover()`, `Focus()`, `Blur()`, `Select()` and `ScrollIntoView(block)`. Call them from an event handler, an effect or `OnMount`: ```csharp var dialog = El("dialog", On("close", () => open.Value = false), content); new Effect(() => { if (open.Value) dialog.ShowModal(); else dialog.Close(); }); ``` `showModal()` needs the element in the document, so if the dialog can start open, wait for `OnMount` first (see `samples/Primitives/Dialog.cs`). For anything else, such as a JS library, `BrowserDom.GetHandle(element)` (in `NetWasm.UI.Browser`) returns the element as a `JSObject`. **Document and window listeners.** `OnDocument(event, handler, flags, within)` and `OnWindow(…)` listen outside the component and are removed with the current component or effect run. Inside an effect, that gives "listen only while open". With `within`, the handler gets `e.Inside` (the target is inside that element) and `e.RelatedInside`: ```csharp new Effect(() => { if (!open.Value) return; OnDocument("pointerdown", e => { if (!e.Inside) open.Value = false; }, within: panel); OnDocument("keydown", e => { if (e.Key == "Escape") { open.Value = false; trigger.Focus(); } }); }); ``` Outside a component or effect (in an event handler), they return an `IDisposable` that you dispose yourself. `OnResize(element, rect => …)` observes an element's size the same way. **DOM reads.** `element.GetRect()`, `element.Contains(other)`, `element.HasFocus()`, `ActiveElementId()` and `Viewport()` read the live DOM synchronously. They apply the pending DOM updates first. Call them from event handlers or `OnMount`, not while building or inside an effect (they throw there, because a read would make the effect depend on layout). Under a host without reads (for example the prerenderer's) they throw `NotSupportedException`; prerendering returns zeros. **Focus.** `element.FocusFirst()` and `FocusLast()` focus the first or last tabbable element inside `element` (the element itself when there is none), skipping disabled, hidden, `inert`, invisible and `tabindex="-1"` elements. They run after the pending DOM updates, so call them from `OnMount` to focus a panel that was just rendered. `Html.Focus(id)` focuses an element by the id `ActiveElementId()` returned, to give focus back when a panel closes. For a modal, use `.showModal()`, which traps and restores focus natively. A focus scope with a trap and roving tabindex are library components built on these; see `NwUi.Primitives` (`FocusScope`, `RovingFocus`) and [Building a headless library](headless-libraries.md). **Portal.** `Portal(target, content…)` (or `…` in a template) renders content at the end of the element matching the CSS selector `target`, inside a `
`. Use it for toasts and menus that must escape `overflow: hidden` or a stacking context. The content still belongs to the component: context, listeners, cleanup and error boundaries work as usual, and it is removed with the component. A modal `` and a `popover` element already render in the top layer and need no portal. **Ids.** `UseId(prefix)` returns an id that is unique in the app (`"nw7"`), for `aria-labelledby`, `aria-controls` and `for`. Ids come from a counter, so the same tree built in the same order (as prerendering and the client do) gets the same ids. **Generic components.** `@typeparam`, `Slot`, `context=` and `@bind-Prop`: see [Generic components and slots with parameters](templates.md#generic-components-and-slots-with-parameters). ## Examples `samples/Counter/Components` builds the same room UI twice, once as a template (`RoomRazor.nwui`) and once in C# (`RoomCode.cs`), from a template component with slots (`Panel.nwui`), one with `@prop` and two-way binding (`Stepper.nwui`) and a C# component with `Prop` (`ProgressBar.cs`). The [attribute splatting example](https://matengo.github.io/NetWasm.UI/examples/splatting) (`site/Demos/SplatDemo.nwui`) has a button component that takes `class`, `type`, `disabled`, `aria-*` and `@onclick` from its tag, an icon button that forwards them with `@attributes`, and a text field that takes `placeholder` and `@onkeydown`. --- # Templates (`.nwui`) Components can be written as `.nwui` files: HTML with Razor-style `@` expressions. A Roslyn source generator turns each file into a `partial class` that calls the [C# API](components.md), so there is no template engine at runtime and nothing reflection-based for NetWasm to trip over. The static HTML of each element subtree becomes a [static template](components.md#static-templates-fast-rows) that the browser parses once and clones; only bindings, handlers, `@expr` text and components/blocks are set per instance. ```razor @* CounterView.nwui → public partial class CounterView : Component *@

Counter

Count: @count · doubled: @doubled

@if (count.Value >= 10) {

That's a lot of clicks!

}
@code { private readonly Signal count = new(0); private Computed doubled = null!; partial void OnInit() => doubled = new Computed(() => count.Value * 2); } ``` ## Setup A `Foo.nwui` file becomes `public partial class Foo : Component` in `RootNamespace` plus the folder path (or the namespace given with `@namespace X.Y`). For example, `Pages/Home.nwui` in `MyApp` becomes `MyApp.Pages.Home`; add `using MyApp.Pages;` where you use it from another namespace. The `NwUi` package contains the generator and feeds it every `*.nwui` file in the project, so there is nothing to set up. Set `false` to turn it off. The dev server watches `.nwui` files like `.cs` files. Every generated file has these usings, plus your own `@using` lines: ```csharp using System.Collections.Generic; using System.Threading.Tasks; using NetWasm.UI; using NetWasm.UI.Forms; using NetWasm.UI.Reactive; using NetWasm.UI.Routing; using static NetWasm.UI.Html; ``` ## Syntax | Syntax | Becomes | |---|---| | `@name`, `@a.b(c)[0]`, `@(x + 1)` | reactive text `Text(() => expr)`; a `Signal`/`Computed` prints (and tracks) its value | | `@render(expr)` | any `Content` (node, component, fragment) inserted as-is | | `@render(Row, item)` | a `Slot` rendered with an argument (`Row.With(item)`); an unset slot renders nothing. See [Generic components](#generic-components-and-slots-with-parameters) | | `class="a @b"`, `title="@x"` | static `Attr`, or reactive `Attr(name, () => …)` when it contains `@`; a `bool` value is written `"true"`/`"false"` (for `aria-*` and `data-*`) | | `disabled="@cond"` (also `checked`, `hidden`, `readonly`, `required`, `selected`, `multiple`, `autofocus`, `open`, `inert`, `novalidate`, `formnovalidate`, `default`, `playsinline`, `nomodule`) | toggled attribute / `checked` property | | `value="…"` | the `value` property (`Value(...)`) | | `@onclick="() => …"`, `@onsubmit="Save"` | `On("click", handler)`; the handler is an `Action` or `Action` | | `@onclick:preventDefault`, `@onclick:stopPropagation`, `@onsubmit:preventDefault="false"` | listener flags (`submit` prevents default unless turned off) | | `@onfocus:capture`, `@onwheel:passive` | `ListenerFlags.Capture` / `Passive`: the listener goes on the element itself instead of being delegated | | `@bind="signal"` | `Spread(Bind(signal))` for `Signal` / `Signal`, and for `Field` / `Field` (with `id`, touched and ARIA state; see [Forms](forms.md)) | | `@ref="field"` | assigns the `Element` (or component) to a generated field | | `@if (c) { … } else if (c2) { … } else { … }` | `When(...)`; a chain shares one memoized selector | | `@if (c) animate-exit { … }`, `@foreach (…) animate-exit { … }` | `.AnimateExit()`: removed content keeps `data-state="closed"` until its CSS animation ends; see [Exit animations](components.md#exit-animations) | | `@foreach (var x in items) {
  • …
  • }` | a keyed list (see [Rows of an `@foreach`](#rows-of-an-foreach)); `items` may be a list expression or an `IReadOnlySignal>`; without `@key` the item itself is the key | | `` | `new Badge { Label = "hi", Count = n }` (an uppercase tag is a component; constructor parameters are filled with `Inject()`, see [constructor injection](services.md#constructor-injection)) | | `