---
title: "Markup components"
url: https://recursiveai.org/oneui/docs/markup/
description: "A component is a template, an optional stylesheet and a C# class with the same name:"
version: "1.0.0"
source: https://github.com/recursive-ai-oss/oneui-csharp/blob/4223040c97a50152bdf8fbee60168a3a0fa5c80f/docs/markup.md
---

# Markup components

A component is a template, an optional stylesheet and a C# class with the same name:

```
Counter.html   <button class="btn" on:click="Increment">Clicked {Count} times</button>
Counter.css    .btn { padding: 4px 12px; }
Counter.cs     public partial class Counter { [State] public partial int Count { get; set; } void Increment() => Count++; }
```

The package ships the markup compiler as an analyzer. Every `.html` file (and the `.css` next to it) in the project is passed to it
(`RecursiveAI.OneUI.targets` adds them as `AdditionalFiles`; set `OneUIMarkupGlob` to `false` to list them yourself). The class must be
a top-level, non-generic `partial class`; the compiler adds `: OneUI.Components.Component`, the state implementations and the `Build`
method. Every name in the template is checked at build time (see `diagnostics.md`).

## State and parameters

`[State] public partial T Name { get; set; }` is state; `[Param]` (optionally `Required = true`) is state a parent sets. Setting a
different value marks it changed; the bindings that read it run before the next commit and write only what differs. At most 63 per
component. `Notify<Name>Changed()` is generated for state that is mutated in place (a list that was added to).

## Template syntax

| | |
|---|---|
| Text | `Hello {Name}!`. `{{` and `}}` are literal braces. Values are formatted with the invariant culture; `bool` is `true`/`false`, null is empty. |
| Attributes | `title="Hi {Name}"`; one `{expr}` alone for booleans (`disabled="{Busy}"`: present or absent) or to remove a null (`href="{Url}"`). Quote the attribute with `'` when the expression contains `"`. |
| Classes, styles | `class:active="{IsActive}"` toggles one class; `style:color="{Color}"` sets one inline property (null removes it). A static `style="a: b; c: d"` is checked and applied property by property. |
| Events | `on:click="Handler"` calls `void Handler()` or `void Handler(MouseEvent e)`; `on:click="{count++}"` runs a statement (`e` is the event). Payloads: `MouseEvent`, `KeyboardEvent`, `InputEvent` (`input`, `change`), `FocusEvent`, `DomEvent`. |
| Two-way | `bind:value="Name"` on `input`, `textarea`, `select` (`input` events); `bind:checked="Agree"` on checkbox and radio inputs (`change` events). The target is any assignable expression. |
| Conditionals | `<template if="{A}">…</template><template else-if="{B}">…</template><template else>…</template>`, siblings. |
| Lists | `<template each="{Items}" item="todo" index="i" key="{todo.Id}">…</template>`. The key is required; rows keep their nodes while their key stays, and only rows outside the longest already-ordered run are moved. |
| Components | `<TodoRow Title="{todo.Title}" Done="{todo.Done}" />`: the tag is the class name (capitalised). A literal (`Count="3"`) converts to string, bool, int, long, float, double. Callbacks are `Action` parameters: `OnDone="{() => Remove(todo.Id)}"`. |
| Slots | In the child: `<slot />` and `<slot name="title">fallback</slot>`. In the parent: the tag's content fills the default slot; `<template slot="title">…</template>` fills a named one. Slot content reads the *declaring* component's state. |
| References | `<input ref="{Search}" />` binds an `ElementRef` member (`ElementRef Search { get; } = new();`) to the element once it is created. `Search.Focus()` asks the document to focus it (see below). The reference is unbound while the element does not exist; in a list row it points at the row created last. `ref` goes on elements, not components (`OUI0070`). |
| Lifecycle | `protected override void OnMounted()` runs after the commit that created the nodes, children before parents; `OnDisposed()` runs when the component is removed, parents before children. |

Whitespace: text that touches a tag and spans a line break is dropped; other runs collapse to one space.

## Components from other assemblies

A tag names a component class declared in the project or in any referenced assembly whose components are written with OneUI (a
`PackageReference` or `ProjectReference` to the library is all a consumer needs): the compiler reads their `[Param]` properties from the
assembly's metadata, and the slot names from `ComponentSlots` attributes that it wrote into the library when it compiled it, so parameters, required
parameters, slots and types are checked exactly as for a component in the project. A library component's scoped stylesheet is part of its
generated code, so it is added to the document the first time the component is created; the consumer does nothing. A component the project
declares wins over a referenced one of the same name; two referenced components of one name are `OUI0064` where used. A component written by
hand (no template) in a library takes any slot name. Only public (or `InternalsVisibleTo`) non-generic classes with a public parameterless
constructor count. Nothing is looked up at run time, so it is trim- and NativeAOT-safe.

A library that turns on `GenerateDocumentationFile` needs no `NoWarn`: generated members carry `<inheritdoc />`.

## Focus

`ElementRef.Focus()` moves keyboard focus as the DOM's `focus()` does (a control, a link with `href`, an element with `tabindex`; nothing happens for
anything else, a disabled or hidden element, or one that is not attached). Call it from `OnMounted` for initial focus, from a key handler for
roving focus (give the selected tab `tabindex="0"` and the others `-1`), and on the opener when a dialog closes. It records a `Focus` change, which
every backend applies after the commit's other changes; the focus events come back through `on:focus`, `on:blur`, `on:focusin` and `on:focusout`.
Calling it on an unbound reference throws `InvalidOperationException`. See `change-sets.md` for the contract and for what the reference
document simulates (`ActiveElement`, Tab, Enter and Space activation, label clicks).

## SVG

`<svg>` and these elements inside it are created in the SVG namespace: `g`, `defs`, `symbol`, `use`, `path`, `circle`, `ellipse`, `rect`, `line`,
`polyline`, `polygon`, `linearGradient`, `radialGradient`, `stop`, `clipPath`, `mask`, `title`, `desc`. Their geometry attributes
(`d`, `cx`, `points`, `viewBox`, ...) and the SVG 2 presentation attributes (`fill`, `stroke`, `stroke-width`, `stroke-linecap`, `opacity`,
`transform`, `clip-path`, ...) are checked per element, `class`, `id`, `style`, `data-*` and `aria-*` are always allowed, and every attribute can be
bound with `{expr}` like an HTML one, as can `class:` and `style:` and `on:`. Names are case-sensitive: write `viewBox`, not `viewbox` (`OUI0011`).
`xmlns` is accepted and ignored. Inside `<svg>`, `<template if|each>` works; components, slots, HTML elements, SVG text, animation, filters,
patterns and markers are `OUI0013`. Not supported by the native renderer yet, and so not diagnosed: the page's CSS rules do not reach elements
inside an inline `<svg>` (set presentation attributes on the shapes; `currentColor` follows the `<svg>`'s CSS `color`).

## What updates what

Each binding records a bitmask of the state its expression reads (identifiers that name `[State]`/`[Param]` properties; row variables
of an enclosing `each`). A state change runs only the bindings whose mask intersects it, and each writes one mutation only if its
value changed. A binding that reads any other member of the class (a plain property, or a method call) is re-checked after every
change, so computed values stay correct; make constants `const` or `static readonly` to avoid that. A lambda passed whole as a
parameter reads nothing when it is assigned.

## Scoped styles

A component's `.css` applies only to its own elements: the last compound selector of each rule gets a `[data-oui-<id>]` attribute, which the
component's elements carry. `:global(sel)` opts a selector out. `@media`, `@supports`, `@layer`, `@keyframes` and `@font-face` are accepted.
Every property must be one the renderer supports (`css-support.md`).

## Without markup

A component is a class deriving from `Component` whose `Build(Scope, int parent, int before)` calls the same `Scope` methods the
generated code does (`Element`, `Text`, `Attr`, `ClassIf`, `Style`, `Listen`, `BindValue`, `If`, `Each`, `Child`, `Slot`, `Insert`) and
whose state setters call `SetState`. `tests/OneUI.Components.Tests/HandWrittenTests.cs` has one.

## Types for generated code

The markup compiler's output calls a few public types that exist only for it. They live in the `OneUI.GeneratorSupport` namespace, are
hidden from IntelliSense (`[EditorBrowsable(Never)]`) and are not a stable authoring API: they can change in any release, so application
code does not name them.

| Type | Was | Used for |
|---|---|---|
| `OneUI.GeneratorSupport.Fmt` | `OneUI.Components.Fmt` | text of `{expr}` bindings |
| `OneUI.GeneratorSupport.SlotContent` | `OneUI.Components.SlotContent` | markup a parent passes into a slot |
| `OneUI.GeneratorSupport.ComponentSlotsAttribute` | `OneUI.Components.ComponentSlotsAttribute` | slot names written into a library assembly |

Members that only generated code calls stay on their types and are hidden the same way: `Component.SetState`, `Component.SetSlot`,
`Component.TryGetState`, `Component.StateNames`, `Scope.Param`, `Scope.ItemDeps` and `Scope.AllDeps`.

Both authoring and generated code use these, so they stay in `OneUI.Components`: `Component`, `Scope`, `BlockBuilder`, `Row<T>` and
`RowBuilder<T>` (a component written without markup overrides `Build` and calls `Scope`), `StateAttribute`, `ParamAttribute`, `ElementRef`.
