@microsoft/webui 0.0.28 → 0.0.29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -0
- package/ai.md +1537 -0
- package/bin/webui +0 -0
- package/package.json +12 -10
- package/wasm/all/package.json +1 -1
- package/wasm/all/webui_wasm_all.js +47 -43
- package/wasm/all/webui_wasm_all_bg.wasm +0 -0
- package/wasm/handler/package.json +1 -1
- package/wasm/handler/webui_wasm_handler.js +41 -37
- package/wasm/handler/webui_wasm_handler_bg.wasm +0 -0
- package/wasm/parser/package.json +1 -1
- package/wasm/parser/webui_wasm_parser.js +36 -32
- package/wasm/parser/webui_wasm_parser_bg.wasm +0 -0
package/ai.md
ADDED
|
@@ -0,0 +1,1537 @@
|
|
|
1
|
+
---
|
|
2
|
+
layout: page
|
|
3
|
+
description: Authoritative WebUI framework reference for generating correct application code - template-first authoring rules, template syntax, styling, interactivity, routing, state JSON, and anti-patterns.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# WebUI Framework - AI Reference
|
|
7
|
+
|
|
8
|
+
> **Single-page reference for LLMs.** Everything an AI coding assistant needs to
|
|
9
|
+
> generate correct WebUI code. Read the Rules first - they are the constraints
|
|
10
|
+
> that most often get violated. Deep-dive links are indexed at the bottom.
|
|
11
|
+
>
|
|
12
|
+
> Install the loader skill **once** with
|
|
13
|
+
> `npx skills add microsoft/webui --skill webui-reference` - see
|
|
14
|
+
> [AI Coding Agents](/guide/installation#ai-coding-agents).
|
|
15
|
+
> It reads `node_modules/@microsoft/webui/ai.md`, so upgrading `@microsoft/webui`
|
|
16
|
+
> updates the reference without reinstalling the skill.
|
|
17
|
+
>
|
|
18
|
+
> Links starting with `/guide/` or `/tutorials/` refer to the
|
|
19
|
+
> [documentation site](https://microsoft.github.io/webui/), which tracks the
|
|
20
|
+
> current release rather than your installed version.
|
|
21
|
+
|
|
22
|
+
## Rules
|
|
23
|
+
|
|
24
|
+
These four rules decide almost every authoring question. When in doubt, re-read
|
|
25
|
+
them before writing code.
|
|
26
|
+
|
|
27
|
+
### 1. The template is the UI
|
|
28
|
+
|
|
29
|
+
All UI structure lives in `.html` template files. There is no other way to
|
|
30
|
+
create UI.
|
|
31
|
+
|
|
32
|
+
- Never `document.createElement()`, `innerHTML`, `insertAdjacentHTML`,
|
|
33
|
+
`appendChild`, `cloneNode`, or `new DOMParser()` to build UI.
|
|
34
|
+
- Show and hide with `<if>`. Repeat with `<for>`. Swap regions with `<outlet>`.
|
|
35
|
+
- If the markup you need does not exist yet, add it to the template and gate it
|
|
36
|
+
with `<if>` - do not build it from JavaScript.
|
|
37
|
+
- **The single exception** is mounting a lazily loaded component, which has no
|
|
38
|
+
template representation until it is fetched. See
|
|
39
|
+
[Lazy component mounting](#lazy-component-mounting).
|
|
40
|
+
|
|
41
|
+
### 2. CSS owns all styling and animation
|
|
42
|
+
|
|
43
|
+
All styling lives in `.css` files. All animation is declarative CSS.
|
|
44
|
+
|
|
45
|
+
- Never `el.style.color = ...`, `classList.add/remove/toggle`,
|
|
46
|
+
`setAttribute('style', ...)`, `adoptedStyleSheets`, or injected `<style>` tags.
|
|
47
|
+
- To style from state, bind an attribute in the template and select on it in CSS:
|
|
48
|
+
`?data-active="{{isActive}}"` plus `[data-active] { ... }`.
|
|
49
|
+
- Animate with `transition`, `@keyframes`, `@starting-style`, and view
|
|
50
|
+
transitions. Never `element.animate()`, `requestAnimationFrame` tweening,
|
|
51
|
+
`setInterval` timers, or a JavaScript animation library.
|
|
52
|
+
|
|
53
|
+
### 3. JavaScript is opt-in, and only for interactivity
|
|
54
|
+
|
|
55
|
+
A component needs **no** `.ts` file at all unless something interactive happens
|
|
56
|
+
in it. Scriptless components still render bindings, `<if>`, and `<for>` on the
|
|
57
|
+
server, and still activate for browser state and soft navigation.
|
|
58
|
+
|
|
59
|
+
- `WebUIElement`, `@observable`, and `@attr` are **optional**. Add them only
|
|
60
|
+
when JavaScript actually reads or writes the value, or when the value is part
|
|
61
|
+
of the component's public API that another module sets.
|
|
62
|
+
- A value that only appears in the template belongs in the server state JSON,
|
|
63
|
+
not in an `@observable`.
|
|
64
|
+
- JavaScript is for event handlers, network calls, focus management, and
|
|
65
|
+
imperative browser APIs. Nothing else.
|
|
66
|
+
|
|
67
|
+
### 4. Use the web platform
|
|
68
|
+
|
|
69
|
+
Prefer a built-in HTML element or modern CSS feature over a hand-built one.
|
|
70
|
+
|
|
71
|
+
- `<dialog>` over a div-based modal. `popover` over a JS dropdown.
|
|
72
|
+
`<details>` over a JS accordion.
|
|
73
|
+
- `:has()`, `@container`, `@starting-style`, `field-sizing`, `color-mix()`,
|
|
74
|
+
`light-dark()`, `content-visibility`, `inert`, `@layer`.
|
|
75
|
+
- Native form validation, `<input type="...">` variants, `loading="lazy"`.
|
|
76
|
+
- No UI libraries, no CSS frameworks, no polyfills for baseline features.
|
|
77
|
+
|
|
78
|
+
## What to reach for
|
|
79
|
+
|
|
80
|
+
| You need | Use this | Not this |
|
|
81
|
+
|---|---|---|
|
|
82
|
+
| Show / hide a region | `<if condition="...">` | `el.hidden`, `style.display` |
|
|
83
|
+
| Render a list | `<for each="x in xs">` | `createElement` in a loop |
|
|
84
|
+
| Style from state | `?data-x="{{expr}}"` + CSS attribute selector | `classList.toggle` |
|
|
85
|
+
| Toggle a class-like variant | `?data-variant="{{mode == 'compact'}}"` | `className = ...` |
|
|
86
|
+
| Modal | `<dialog>` + `showModal()` | div overlay + z-index juggling |
|
|
87
|
+
| Dropdown / tooltip / menu | `popover` + `:popover-open` | JS positioning library |
|
|
88
|
+
| Accordion / disclosure | `<details><summary>` | click handler + height math |
|
|
89
|
+
| Tabs | radio inputs or `?data-selected` + CSS | JS show/hide of panels |
|
|
90
|
+
| Enter / exit animation | `@starting-style` + `transition-behavior: allow-discrete` | `element.animate()` |
|
|
91
|
+
| Looping animation | `@keyframes` | `requestAnimationFrame` loop |
|
|
92
|
+
| Page transition | `view-transition-name` + `::view-transition-*` | manual fade with JS |
|
|
93
|
+
| Responsive to container | `@container` | `ResizeObserver` + inline styles |
|
|
94
|
+
| Style a parent from a child | `:has()` | JS class propagation |
|
|
95
|
+
| Theme values | CSS custom properties + `--theme` | JS theme objects |
|
|
96
|
+
| Derived boolean | `<if condition="items.length">` | `@observable hasItems` |
|
|
97
|
+
| Text that never changes on the client | server state JSON | `@observable` |
|
|
98
|
+
| Focus / scroll / measure | `w-ref="{el}"` + a `.ts` file | `querySelector` |
|
|
99
|
+
|
|
100
|
+
## Mental model
|
|
101
|
+
|
|
102
|
+
**Trusted Types:** WebUI automatically uses its private `webui` policy for compiled
|
|
103
|
+
templates and generated CSS import maps. No setup call or special import order is
|
|
104
|
+
needed. To enforce Trusted Types, use `require-trusted-types-for 'script'; trusted-types webui`
|
|
105
|
+
alongside the normal nonce CSP. Share one framework module across bundles; do not
|
|
106
|
+
pre-create its policy. Raw triple-brace state HTML, FAST strings and arbitrary
|
|
107
|
+
scripts/URLs are not promoted. Client-side router partial navigation is not yet
|
|
108
|
+
supported under enforcement. See
|
|
109
|
+
[Trusted Types](/guide/concepts/hydration#trusted-types).
|
|
110
|
+
|
|
111
|
+
```
|
|
112
|
+
BUILD TIME SERVER RENDER CLIENT HYDRATION
|
|
113
|
+
--------------- --------------- -----------------
|
|
114
|
+
HTML + CSS + TS -> protocol.bin -> Web Components
|
|
115
|
+
webui build + JSON state hydrate as islands
|
|
116
|
+
-> rendered HTML
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
WebUI is a **language-agnostic server-side rendering framework**. Templates
|
|
120
|
+
compile to a binary Protocol Buffer at build time. At runtime any backend
|
|
121
|
+
(Rust, Node, Go, C#, Python) supplies JSON state and produces HTML. On the
|
|
122
|
+
client, interactive components hydrate as islands.
|
|
123
|
+
|
|
124
|
+
1. **Every template binding should exist in the server state JSON.** If the
|
|
125
|
+
template uses `{{title}}`, the server must provide `{ "title": "..." }`.
|
|
126
|
+
Missing text and attribute paths render empty. A missing condition identifier
|
|
127
|
+
is falsy, so `path` is false and `!path` is true. No error is raised.
|
|
128
|
+
2. **Derived state belongs in the template or the server.** Use expressions like
|
|
129
|
+
`items.length` or `status == 'active'`. Compute complex values server-side.
|
|
130
|
+
3. **The server is the source of truth for the initial render.** The client
|
|
131
|
+
takes over after hydration for user interactions.
|
|
132
|
+
4. **Scriptless components are dormant, not dead.** Their bindings render on the
|
|
133
|
+
server and contribute no initial bootstrap state. Compiler-owned hosts can
|
|
134
|
+
still activate for browser-applied state, parent property writes, or soft
|
|
135
|
+
navigation. Events and lifecycle code need a same-named `.ts` or `.js`.
|
|
136
|
+
5. **Hydration state is client-facing.** It reduces CPU and bytes but is not a
|
|
137
|
+
secrecy boundary. Never put credentials or private tokens in render state.
|
|
138
|
+
|
|
139
|
+
## Project structure
|
|
140
|
+
|
|
141
|
+
```
|
|
142
|
+
my-app/
|
|
143
|
+
|- src/
|
|
144
|
+
| |- index.html <- Entry template
|
|
145
|
+
| |- index.ts <- Hydration entry point
|
|
146
|
+
| |- my-component/
|
|
147
|
+
| | |- my-component.html <- Component template
|
|
148
|
+
| | |- my-component.css <- Component styles (scoped)
|
|
149
|
+
| | \- my-component.ts <- Optional: only if interactive
|
|
150
|
+
| \- static-widget/
|
|
151
|
+
| |- static-widget.html <- Scriptless: no .ts needed
|
|
152
|
+
| \- static-widget.css
|
|
153
|
+
|- data/state.json <- Server state for dev
|
|
154
|
+
\- dist/
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
**Component discovery:**
|
|
158
|
+
|
|
159
|
+
- HTML files with a hyphen in the name are components
|
|
160
|
+
(`my-card.html` -> `<my-card>`).
|
|
161
|
+
- CSS files with the same name are auto-paired.
|
|
162
|
+
- A same-named `.ts` or `.js` file opts the component into authored behavior.
|
|
163
|
+
Most components should not have one.
|
|
164
|
+
- Discovery is recursive through subdirectories.
|
|
165
|
+
|
|
166
|
+
## Template syntax
|
|
167
|
+
|
|
168
|
+
### HTML structure
|
|
169
|
+
|
|
170
|
+
Write browser-valid HTML nesting. Native void tags are matched
|
|
171
|
+
case-insensitively, and direct `<col>` / `<tr>` runs receive the browser-implied
|
|
172
|
+
`<colgroup>` / `<tbody>` in compiled client metadata. When an `<if>` or `<for>`
|
|
173
|
+
controls table columns or rows, author the corresponding `<colgroup>` or
|
|
174
|
+
`<tbody>` explicitly so both SSR hydration markers stay in the same browser
|
|
175
|
+
parsing context.
|
|
176
|
+
|
|
177
|
+
### Text binding
|
|
178
|
+
|
|
179
|
+
```html
|
|
180
|
+
<span>{{user.name}}</span>
|
|
181
|
+
<p>{{items.length}} items</p>
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
- `{{expr}}` - HTML-escaped output (safe for user input)
|
|
185
|
+
- `{{{expr}}}` - raw/unescaped output (only for trusted content)
|
|
186
|
+
|
|
187
|
+
Text bindings do path lookups only. They cannot do arithmetic or call functions.
|
|
188
|
+
|
|
189
|
+
### Conditionals
|
|
190
|
+
|
|
191
|
+
```html
|
|
192
|
+
<if condition="isLoggedIn">
|
|
193
|
+
<p>Welcome back, {{username}}!</p>
|
|
194
|
+
</if>
|
|
195
|
+
|
|
196
|
+
<if condition="!hasItems">
|
|
197
|
+
<p>No items found.</p>
|
|
198
|
+
</if>
|
|
199
|
+
|
|
200
|
+
<if condition="status == 'active'">
|
|
201
|
+
<span class="badge">Active</span>
|
|
202
|
+
</if>
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
Operators: `==`, `!=`, `>`, `<`, `>=`, `<=`, `&&`, `||`, `!`
|
|
206
|
+
|
|
207
|
+
**Constraints:** max 5 logical operators per expression; cannot mix `&&` and
|
|
208
|
+
`||` in one expression; no parentheses for grouping; no ternary; **no
|
|
209
|
+
arithmetic**.
|
|
210
|
+
|
|
211
|
+
Each side of a comparison is either a literal (number, quoted string, `true`,
|
|
212
|
+
`false`) or a dotted state path. Anything else is read as a path, so
|
|
213
|
+
`{{currentIndex == items.length - 1}}` looks up a key literally named
|
|
214
|
+
`items.length - 1`, finds nothing, and the condition is silently false. Have the
|
|
215
|
+
server send a precomputed `lastIndex` (or `isLast`) instead. Bare `.length` on an
|
|
216
|
+
array or string does work: `<if condition="items.length > 3">`.
|
|
217
|
+
|
|
218
|
+
### Loops
|
|
219
|
+
|
|
220
|
+
```html
|
|
221
|
+
<for each="item in items">
|
|
222
|
+
<div>{{item.name}} - {{item.price}}</div>
|
|
223
|
+
</for>
|
|
224
|
+
|
|
225
|
+
<for each="item in reorderableItems">
|
|
226
|
+
<todo-row key="{{item.id}}" title="{{item.title}}"></todo-row>
|
|
227
|
+
</for>
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
- The collection must be a JSON array.
|
|
231
|
+
- Nested loops are supported; outer loop variables remain accessible.
|
|
232
|
+
- Recursive trees use a file-local `id` on a defining loop and self-closing
|
|
233
|
+
references with the same item variable. Write `each="item in items"` without
|
|
234
|
+
binding braces:
|
|
235
|
+
|
|
236
|
+
```html
|
|
237
|
+
<for id="tree-item" each="item in items">
|
|
238
|
+
<div>{{item.name}}</div>
|
|
239
|
+
<for id="tree-item" each="item in item.children" />
|
|
240
|
+
</for>
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
Define each ID once per file. The definition renders normally, references
|
|
244
|
+
can precede it, and other files may reuse the ID independently. Missing or
|
|
245
|
+
empty child arrays end the recursion; pass finite trees, not cyclic data.
|
|
246
|
+
The recursive `item in item.children` resolves the parent's children first,
|
|
247
|
+
then shadows `item` for the shared body and restores it on return. A second
|
|
248
|
+
body for the same ID is a `duplicate-for-id` build error.
|
|
249
|
+
Use `id`, not `template`; the removed `template` attribute is a build error.
|
|
250
|
+
Native WebUI supports recursive client updates; FAST components reject named
|
|
251
|
+
references with an actionable build error.
|
|
252
|
+
[Recursive loops](guide/concepts/directives/for.md#recursive-loops) covers
|
|
253
|
+
validation and keys.
|
|
254
|
+
- Repeats reconcile by array position by default; item attributes never act as
|
|
255
|
+
keys, and `data-key` is an ordinary application attribute.
|
|
256
|
+
- Add compiler-only `key="{{item.id}}"` to the first concrete child to preserve
|
|
257
|
+
identity across reorder. Leading `<if>` wrappers are transparent; `key`
|
|
258
|
+
directly on `<if>`, `<for>`, or `<outlet>` is invalid.
|
|
259
|
+
- `key="{{item}}"` supports arrays of unique string or finite-number primitives.
|
|
260
|
+
Key paths must be rooted at the loop variable or the build fails with
|
|
261
|
+
`invalid-for-key`. Duplicate or invalid runtime keys warn once and fall back
|
|
262
|
+
to positions.
|
|
263
|
+
- **Components inside loops do NOT inherit loop variables.** Pass data via
|
|
264
|
+
attributes:
|
|
265
|
+
|
|
266
|
+
```html
|
|
267
|
+
<for each="contact in contacts">
|
|
268
|
+
<contact-card name="{{contact.name}}" email="{{contact.email}}"></contact-card>
|
|
269
|
+
</for>
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
### Attributes
|
|
273
|
+
|
|
274
|
+
```html
|
|
275
|
+
<!-- Dynamic attribute -->
|
|
276
|
+
<a href="{{url}}">{{linkText}}</a>
|
|
277
|
+
|
|
278
|
+
<!-- Boolean attribute (rendered when truthy, omitted when falsy) -->
|
|
279
|
+
<button ?disabled="{{isLoading}}">Submit</button>
|
|
280
|
+
<input type="checkbox" ?checked="{{isSelected}}" />
|
|
281
|
+
|
|
282
|
+
<!-- Boolean attributes accept the same expressions as <if condition="...">.
|
|
283
|
+
Compare against existing state instead of creating mirror observables. -->
|
|
284
|
+
<button ?disabled="{{currentIndex == 0}}">Prev</button>
|
|
285
|
+
<button ?disabled="{{currentIndex == lastIndex}}">Next</button>
|
|
286
|
+
<option ?selected="{{item.id == selectedId}}">{{item.name}}</option>
|
|
287
|
+
|
|
288
|
+
<!-- Mixed static + dynamic -->
|
|
289
|
+
<img src="/img/{{user.avatar}}" alt="{{user.name}}" />
|
|
290
|
+
|
|
291
|
+
<!-- Complex/property binding -->
|
|
292
|
+
<my-widget :config="{{settings}}"></my-widget>
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
`?attr` is also the styling hook. Bind a `data-*` attribute and select on it in
|
|
296
|
+
CSS rather than touching `classList` from JavaScript.
|
|
297
|
+
|
|
298
|
+
Property bindings use `:` to write directly to DOM properties. For
|
|
299
|
+
client-created trees, initial property bindings are applied before a child's
|
|
300
|
+
`connectedCallback` runs, so children can read parent-provided values during
|
|
301
|
+
setup and still receive later updates through the live binding.
|
|
302
|
+
|
|
303
|
+
### Events
|
|
304
|
+
|
|
305
|
+
```html
|
|
306
|
+
<button @click="{handleClick()}">Click me</button>
|
|
307
|
+
<input @keydown="{onKeydown(e)}" />
|
|
308
|
+
<button @click="{selectItem(item.id, 'details', e)}">Select</button>
|
|
309
|
+
<div @mouseenter="{onHover()}" @mouseleave="{onLeave()}">Hover</div>
|
|
310
|
+
```
|
|
311
|
+
|
|
312
|
+
Handler arguments can be `e`, dotted component or repeat-scope paths, or
|
|
313
|
+
string/number/boolean/null literals. Nested JavaScript expressions are not
|
|
314
|
+
parsed in templates. An `@event` requires a `.ts` file on that component.
|
|
315
|
+
|
|
316
|
+
Each `@event` gets its own listener on the element it is written on - bindings
|
|
317
|
+
are never delegated to a shared root. Non-bubbling events (`@focus`, `@blur`,
|
|
318
|
+
`@mouseenter`, `@load`, `@error`, `@toggle`) therefore work, and an ancestor's
|
|
319
|
+
bubble-phase `stopPropagation()` cannot suppress them.
|
|
320
|
+
|
|
321
|
+
### DOM references
|
|
322
|
+
|
|
323
|
+
```html
|
|
324
|
+
<input w-ref="{searchInput}" type="text" />
|
|
325
|
+
```
|
|
326
|
+
|
|
327
|
+
The braces are **required**. A non-braced `w-ref="searchInput"` fails the build
|
|
328
|
+
with `invalid-w-ref`. Declare the property in the class:
|
|
329
|
+
`searchInput!: HTMLInputElement;`
|
|
330
|
+
|
|
331
|
+
Use `w-ref` only for imperative browser APIs - `focus()`, `scrollIntoView()`,
|
|
332
|
+
`showModal()`, `showPopover()`, measurement. Never use it to read or write
|
|
333
|
+
state that a template binding could express.
|
|
334
|
+
|
|
335
|
+
`w-ref` is scalar. Reusing one ref name inside `<for>` overwrites the same
|
|
336
|
+
property, so the last wired occurrence wins; repeat `key` and position do not
|
|
337
|
+
create an indexed ref collection. For item lookup, use a stable authored `id`
|
|
338
|
+
with `Document.getElementById()` / `ShadowRoot.getElementById()`, or put the ref
|
|
339
|
+
inside an item component.
|
|
340
|
+
|
|
341
|
+
### The `<template>` tag
|
|
342
|
+
|
|
343
|
+
Unwrapped components default to Shadow. In a `--dom light` build they use
|
|
344
|
+
authored/global Light DOM:
|
|
345
|
+
|
|
346
|
+
A sole bare top-level `<template>` is also an explicit Light wrapper and is
|
|
347
|
+
unwrapped, even when the build fallback is Shadow. Templates with attributes or
|
|
348
|
+
`w-render`/`w-hydrate` are not mode selectors; nested templates remain inert
|
|
349
|
+
template content.
|
|
350
|
+
|
|
351
|
+
```html
|
|
352
|
+
<!-- my-card.html -->
|
|
353
|
+
<h2>{{title}}</h2>
|
|
354
|
+
<p>{{description}}</p>
|
|
355
|
+
```
|
|
356
|
+
|
|
357
|
+
In a Light build, use a sole top-level
|
|
358
|
+
`<template shadowrootmode="open">` when the component must remain Shadow for a
|
|
359
|
+
native `<slot>`, native isolation, CSS-heavy frequent restyling, or root host
|
|
360
|
+
events:
|
|
361
|
+
|
|
362
|
+
```html
|
|
363
|
+
<!-- todo-app.html -->
|
|
364
|
+
<template shadowrootmode="open"
|
|
365
|
+
@toggle-item="{onToggleItem(e)}"
|
|
366
|
+
@delete-item="{onDeleteItem(e)}"
|
|
367
|
+
>
|
|
368
|
+
<for each="item in items">
|
|
369
|
+
<todo-item id="{{item.id}}"></todo-item>
|
|
370
|
+
</for>
|
|
371
|
+
</template>
|
|
372
|
+
```
|
|
373
|
+
|
|
374
|
+
The wrapper must contain the complete component. `closed`, a dynamic or invalid
|
|
375
|
+
value, placement on another element, multiple declarations, or extra top-level
|
|
376
|
+
content fails the build. `<slot>` is a build error only when the effective mode
|
|
377
|
+
is Light.
|
|
378
|
+
|
|
379
|
+
Root host events catch custom events bubbling up from child components. To
|
|
380
|
+
cross any Shadow boundary between the child and the listener, an event must
|
|
381
|
+
bubble and be `composed`; `this.$emit()` always sets both so Light components
|
|
382
|
+
nested in a Shadow tree work too. A hand-built `new CustomEvent(name)` defaults
|
|
383
|
+
to neither and will never reach the root - pass
|
|
384
|
+
`{ bubbles: true, composed: true }` or bind it on the child element.
|
|
385
|
+
|
|
386
|
+
The binding sits on the host element, so it also catches events targeted at the
|
|
387
|
+
host itself - what host-interactive components (host `tabindex`, presentational
|
|
388
|
+
shadow content) rely on. It does not see non-composed events (`change`,
|
|
389
|
+
`submit`, `select`, media); bind those per element.
|
|
390
|
+
|
|
391
|
+
One root listener also serves an arbitrarily large `<for>`, so this is the way
|
|
392
|
+
to trade per-row listeners for a single handler on a very long list. For rows
|
|
393
|
+
inside the shadow tree `e.target` is the host, so use `e.composedPath()[0]` to
|
|
394
|
+
find the element that was hit.
|
|
395
|
+
|
|
396
|
+
### Outlet
|
|
397
|
+
|
|
398
|
+
```html
|
|
399
|
+
<!-- Parent component template -->
|
|
400
|
+
<nav>...</nav>
|
|
401
|
+
<main><outlet /></main>
|
|
402
|
+
```
|
|
403
|
+
|
|
404
|
+
`<outlet></outlet>` is also valid, but outlets are empty directives and the
|
|
405
|
+
self-closing form is preferred.
|
|
406
|
+
|
|
407
|
+
### Entry template
|
|
408
|
+
|
|
409
|
+
```html
|
|
410
|
+
<!DOCTYPE html>
|
|
411
|
+
<html lang="en" dir="{{textdirection}}">
|
|
412
|
+
<head>
|
|
413
|
+
<meta charset="UTF-8">
|
|
414
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
415
|
+
<title>{{title}}</title>
|
|
416
|
+
</head>
|
|
417
|
+
<body>
|
|
418
|
+
<app-shell></app-shell>
|
|
419
|
+
<script type="module" src="/index.js"></script>
|
|
420
|
+
</body>
|
|
421
|
+
</html>
|
|
422
|
+
```
|
|
423
|
+
|
|
424
|
+
## Styling
|
|
425
|
+
|
|
426
|
+
Keep ordinary paired component CSS. Light CSS is authored/global in its owning
|
|
427
|
+
Document or ShadowRoot; selectors, keyframes, and cascade layers are not
|
|
428
|
+
rewritten. Shadow components retain native Shadow CSS scoping. No CSS-in-JS or
|
|
429
|
+
styles written from script.
|
|
430
|
+
|
|
431
|
+
```css
|
|
432
|
+
/* my-component.css */
|
|
433
|
+
my-component {
|
|
434
|
+
display: block;
|
|
435
|
+
padding: 1rem;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
my-component[disabled] {
|
|
439
|
+
opacity: 0.5;
|
|
440
|
+
pointer-events: none;
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
my-component[variant="primary"] {
|
|
444
|
+
background: var(--colorBrandBackground);
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
.header { font-weight: bold; }
|
|
448
|
+
```
|
|
449
|
+
|
|
450
|
+
- `:host` styles the component root only in Shadow DOM. In Light DOM, target
|
|
451
|
+
the component tag directly, for example `my-card` or `my-card[disabled]`.
|
|
452
|
+
- Light DOM preserves normal inheritance and global cascade. Parent rules can
|
|
453
|
+
reach Light descendants and matching selectors can affect other Light
|
|
454
|
+
components in the same CSS tree.
|
|
455
|
+
- `:host`, `:host-context`, and `::slotted` fail with
|
|
456
|
+
`unsupported-light-css` in effective Light components; use ordinary
|
|
457
|
+
selectors or author an open Shadow root.
|
|
458
|
+
- `data-wl` and `data-wl-*` are ordinary author attributes; WebUI no longer
|
|
459
|
+
generates or reserves them for Light CSS.
|
|
460
|
+
- Use CSS custom properties for theming. Nested fallbacks like
|
|
461
|
+
`var(--primary, var(--fallback))` are also discovered as tokens.
|
|
462
|
+
- Scoped token overrides do not replace theme defaults for other elements.
|
|
463
|
+
Use bare `:host` rules for shared Shadow component defaults or `:root` for
|
|
464
|
+
document defaults. See [design tokens](/guide/concepts/css-tokens).
|
|
465
|
+
- Malformed CSS fails the build, including unterminated `var()` calls,
|
|
466
|
+
comments, strings, and unmatched delimiters.
|
|
467
|
+
|
|
468
|
+
### Reactive styling
|
|
469
|
+
|
|
470
|
+
State drives styling through bound attributes, never through script.
|
|
471
|
+
|
|
472
|
+
```html
|
|
473
|
+
<button ?data-active="{{isActive}}" @click="{toggle()}">{{label}}</button>
|
|
474
|
+
<article ?data-compact="{{density == 'compact'}}">...</article>
|
|
475
|
+
```
|
|
476
|
+
|
|
477
|
+
```css
|
|
478
|
+
button[data-active] { background: var(--accent); color: white; }
|
|
479
|
+
button:not([data-active]) { background: transparent; }
|
|
480
|
+
article[data-compact] { --row-height: 1.5rem; }
|
|
481
|
+
```
|
|
482
|
+
|
|
483
|
+
This works during SSR, needs no synchronization code, and stays correct when the
|
|
484
|
+
server re-renders.
|
|
485
|
+
|
|
486
|
+
### Modern CSS to prefer
|
|
487
|
+
|
|
488
|
+
| Feature | Use for |
|
|
489
|
+
|---|---|
|
|
490
|
+
| `:has()` | Parent/sibling state without a JS class |
|
|
491
|
+
| `@container` / `cqi` units | Component-level responsiveness |
|
|
492
|
+
| `@starting-style` + `transition-behavior: allow-discrete` | Animating in/out of `display: none`, `popover`, `<dialog>` |
|
|
493
|
+
| `color-mix()` / `light-dark()` / `oklch()` | Derived colors, dual themes without JS |
|
|
494
|
+
| `@layer` | Predictable cascade ordering |
|
|
495
|
+
| `content-visibility: auto` | Long lists without virtualization code |
|
|
496
|
+
| `text-wrap: balance` | Headline typography |
|
|
497
|
+
| `:user-valid` / `:user-invalid` | Form feedback without validation JS |
|
|
498
|
+
|
|
499
|
+
### Modern HTML to prefer
|
|
500
|
+
|
|
501
|
+
| Element / attribute | Replaces |
|
|
502
|
+
|---|---|
|
|
503
|
+
| `<dialog>` + `showModal()` | Custom modal with overlay and focus trap |
|
|
504
|
+
| `popover` / `popovertarget` | JS dropdown, menu, tooltip, toast |
|
|
505
|
+
| `<details><summary>` | JS accordion or disclosure |
|
|
506
|
+
| `<datalist>` | JS autocomplete |
|
|
507
|
+
| `inert` | Manual `tabindex` juggling |
|
|
508
|
+
| `loading="lazy"` / `decoding="async"` | IntersectionObserver image loaders |
|
|
509
|
+
| `<progress>` / `<meter>` | Div-based bars |
|
|
510
|
+
| Native constraint validation | Hand-rolled validators |
|
|
511
|
+
|
|
512
|
+
### Progressive enhancement only
|
|
513
|
+
|
|
514
|
+
These are not Baseline across all engines. Use them as an enhancement layer that
|
|
515
|
+
degrades cleanly, never as load-bearing layout or behavior.
|
|
516
|
+
|
|
517
|
+
| Feature | Guard with |
|
|
518
|
+
|---|---|
|
|
519
|
+
| `anchor-name` / `position-area` | `@supports (anchor-name: --x)`, fall back to static placement |
|
|
520
|
+
| Scroll-driven animations | `@supports (animation-timeline: view())` |
|
|
521
|
+
| `field-sizing: content` | A sensible fixed `width` / `rows` default |
|
|
522
|
+
| `text-wrap: pretty` | Harmless when ignored |
|
|
523
|
+
| Customizable `<select>` / `<selectedcontent>` | The native `<select>` rendering |
|
|
524
|
+
|
|
525
|
+
Never polyfill these in JavaScript. If the fallback is unacceptable, use a
|
|
526
|
+
Baseline approach instead.
|
|
527
|
+
|
|
528
|
+
### Animation
|
|
529
|
+
|
|
530
|
+
Animation is CSS. There is no supported JavaScript animation path.
|
|
531
|
+
|
|
532
|
+
```css
|
|
533
|
+
/* Enter and exit for a popover or dialog */
|
|
534
|
+
.menu-panel {
|
|
535
|
+
transition: transform 200ms ease, overlay 200ms allow-discrete,
|
|
536
|
+
display 200ms allow-discrete;
|
|
537
|
+
transform: translateX(-100%);
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
.menu-panel:popover-open {
|
|
541
|
+
transform: translateX(0);
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
@starting-style {
|
|
545
|
+
.menu-panel:popover-open {
|
|
546
|
+
transform: translateX(-100%);
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
@media (prefers-reduced-motion: reduce) {
|
|
551
|
+
.menu-panel { transition: none; }
|
|
552
|
+
}
|
|
553
|
+
```
|
|
554
|
+
|
|
555
|
+
Always honor `prefers-reduced-motion`.
|
|
556
|
+
|
|
557
|
+
### View transitions
|
|
558
|
+
|
|
559
|
+
The router wraps every client-side navigation in `document.startViewTransition()`
|
|
560
|
+
automatically. **Do not** wrap `Router.navigate()` in your own
|
|
561
|
+
`startViewTransition()` - that would double-transition.
|
|
562
|
+
|
|
563
|
+
Name the transitioning element in **component CSS**:
|
|
564
|
+
|
|
565
|
+
```css
|
|
566
|
+
/* mp-app.css */
|
|
567
|
+
.route-surface {
|
|
568
|
+
view-transition-name: page-content;
|
|
569
|
+
}
|
|
570
|
+
```
|
|
571
|
+
|
|
572
|
+
Declare the animations in the **entry template's document-level `<style>`**.
|
|
573
|
+
`::view-transition-*` pseudo-elements live on the document root and cannot be
|
|
574
|
+
reached from inside a shadow root:
|
|
575
|
+
|
|
576
|
+
```html
|
|
577
|
+
<!-- index.html -->
|
|
578
|
+
<style>
|
|
579
|
+
::view-transition-old(page-content) {
|
|
580
|
+
animation: 200ms ease-out both fade-out;
|
|
581
|
+
}
|
|
582
|
+
::view-transition-new(page-content) {
|
|
583
|
+
animation: 300ms ease-in both fade-in;
|
|
584
|
+
}
|
|
585
|
+
@keyframes fade-in { from { opacity: 0; } }
|
|
586
|
+
@keyframes fade-out { to { opacity: 0; } }
|
|
587
|
+
</style>
|
|
588
|
+
```
|
|
589
|
+
|
|
590
|
+
While the router is active it installs a nonce-bearing
|
|
591
|
+
`@view-transition { navigation: none; }` override, because automatic
|
|
592
|
+
cross-document transitions conflict with intercepted routes that fall back to
|
|
593
|
+
SSR document requests. `Router.destroy()` removes the override. The router
|
|
594
|
+
awaits `updateCallbackDone` (not `.finished`) so rapid navigations supersede
|
|
595
|
+
each other without queuing. Resizing or superseding the animation does not fail
|
|
596
|
+
a committed route; route commit errors still follow normal navigation error handling
|
|
597
|
+
without duplicate unhandled transition rejections.
|
|
598
|
+
|
|
599
|
+
## Interactivity
|
|
600
|
+
|
|
601
|
+
### Start scriptless
|
|
602
|
+
|
|
603
|
+
Most components should have only `.html` and `.css`. A scriptless component
|
|
604
|
+
renders bindings, `<if>`, and `<for>` on the server and contributes no bootstrap
|
|
605
|
+
state to the client.
|
|
606
|
+
|
|
607
|
+
```html
|
|
608
|
+
<!-- user-card.html - no .ts file, nothing to add -->
|
|
609
|
+
<h2>{{user.name}}</h2>
|
|
610
|
+
<p>{{user.title}}</p>
|
|
611
|
+
<if condition="user.isAdmin">
|
|
612
|
+
<span class="badge">Admin</span>
|
|
613
|
+
</if>
|
|
614
|
+
```
|
|
615
|
+
|
|
616
|
+
### When to add a `.ts` file
|
|
617
|
+
|
|
618
|
+
Add one only when at least one of these is true:
|
|
619
|
+
|
|
620
|
+
1. The template has an `@event` handler.
|
|
621
|
+
2. The template has a `w-ref` you need for an imperative browser API.
|
|
622
|
+
3. You need `connectedCallback` / `disconnectedCallback` lifecycle work.
|
|
623
|
+
4. You need to fetch data or call a browser API.
|
|
624
|
+
5. The component exposes imperative methods or a public property API.
|
|
625
|
+
|
|
626
|
+
If none apply, do not create the file.
|
|
627
|
+
|
|
628
|
+
### When to add `@observable` or `@attr`
|
|
629
|
+
|
|
630
|
+
Same test, one level down. These decorators exist to connect a value to
|
|
631
|
+
JavaScript - not to make it render.
|
|
632
|
+
|
|
633
|
+
- **`@observable`** - only when TypeScript in this component reads or writes the
|
|
634
|
+
value after hydration. A value that is rendered once and never changed on the
|
|
635
|
+
client belongs in the server state JSON.
|
|
636
|
+
- **`@attr`** - only when the value is part of the component's public API:
|
|
637
|
+
another component, a parent template, or the router sets it as an HTML
|
|
638
|
+
attribute.
|
|
639
|
+
|
|
640
|
+
```typescript
|
|
641
|
+
// Justified: the click handler mutates it, the template renders it.
|
|
642
|
+
@observable count = 0;
|
|
643
|
+
increment(): void { this.count += 1; }
|
|
644
|
+
|
|
645
|
+
// Justified: a parent template sets label="..." on this element.
|
|
646
|
+
@attr label = '';
|
|
647
|
+
|
|
648
|
+
// NOT justified: nothing in TypeScript touches it - put it in state JSON.
|
|
649
|
+
@observable heading = 'Welcome';
|
|
650
|
+
|
|
651
|
+
// NOT justified: mirrors an expression the template can evaluate.
|
|
652
|
+
@observable hasItems = false; // use <if condition="items.length">
|
|
653
|
+
@observable prevDisabled = true; // use ?disabled="{{currentIndex == 0}}"
|
|
654
|
+
```
|
|
655
|
+
|
|
656
|
+
### The component class
|
|
657
|
+
|
|
658
|
+
```typescript
|
|
659
|
+
import { WebUIElement, attr, observable } from '@microsoft/webui-framework';
|
|
660
|
+
|
|
661
|
+
export class MyComponent extends WebUIElement {
|
|
662
|
+
@attr label = 'Default';
|
|
663
|
+
@attr({ mode: 'boolean' }) disabled = false;
|
|
664
|
+
|
|
665
|
+
@observable count = 0;
|
|
666
|
+
@observable items: Item[] = [];
|
|
667
|
+
|
|
668
|
+
// Populated by w-ref="{inputEl}" in the template
|
|
669
|
+
inputEl!: HTMLInputElement;
|
|
670
|
+
|
|
671
|
+
onSubmit(): void {
|
|
672
|
+
const text = this.inputEl.value.trim();
|
|
673
|
+
if (!text) return;
|
|
674
|
+
this.items = [...this.items, { text, price: 0 }];
|
|
675
|
+
this.inputEl.value = '';
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
onKeydown(e: KeyboardEvent): void {
|
|
679
|
+
if (e.key === 'Enter') this.onSubmit();
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
onItemDelete(e: CustomEvent<{ id: string }>): void {
|
|
683
|
+
this.items = this.items.filter(i => i.id !== e.detail.id);
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
MyComponent.define('my-component');
|
|
688
|
+
```
|
|
689
|
+
|
|
690
|
+
### Choose the render and hydration policy
|
|
691
|
+
|
|
692
|
+
Rendering and hydration are separate decisions:
|
|
693
|
+
|
|
694
|
+
- **Rendering** is browser layout/paint work for the server-rendered DOM.
|
|
695
|
+
- **Hydration** is loading JavaScript and attaching bindings/listeners.
|
|
696
|
+
|
|
697
|
+
Agents must use this table instead of treating every form of "lazy" as the same
|
|
698
|
+
behavior:
|
|
699
|
+
|
|
700
|
+
| Root template policy | Rendering before activation | Hydration trigger | Use for |
|
|
701
|
+
|---|---|---|---|
|
|
702
|
+
| No directive | Normal | Eager, when the definition loads | Visible interactive roots and first-use-critical UI |
|
|
703
|
+
| `w-hydrate="lazy"` | Normal | Viewport relevance | Offscreen UI where `content-visibility` containment is unsafe |
|
|
704
|
+
| `w-render="lazy"` + required `w-reserve-block-size` | `content-visibility: auto` skips offscreen layout/paint | Viewport relevance | Repeated or numerous offscreen components; preferred lazy-row policy |
|
|
705
|
+
| `w-hydrate="interaction"` | Normal | Pointer, focus, keyboard, or click intent | One visible app shell/island when startup JS/heap matters more than first-use latency |
|
|
706
|
+
| `w-render="lazy"` + reservation + `w-hydrate="interaction"` | `content-visibility: auto` skips offscreen layout/paint | Interaction intent | One offscreen singleton that should defer both rendering work and JavaScript |
|
|
707
|
+
|
|
708
|
+
#### Agent decision rules
|
|
709
|
+
|
|
710
|
+
1. **Default to eager hydration for the visible interactive root.** Put lazy
|
|
711
|
+
policies on offscreen descendants when request-to-interactive time matters.
|
|
712
|
+
2. **For repeated rows/cards, use `w-render="lazy"` with a realistic
|
|
713
|
+
`w-reserve-block-size`.** Do not use interaction hydration for repeated items.
|
|
714
|
+
3. **Use `w-hydrate="lazy"` only when hydration should wait for the viewport but
|
|
715
|
+
rendering containment could break layout or styling.**
|
|
716
|
+
4. **Use `w-hydrate="interaction"` only for a singleton shell/island.** It saves
|
|
717
|
+
startup JavaScript and heap but adds first-interaction module-loading latency.
|
|
718
|
+
5. **For one offscreen singleton that needs both savings, combine
|
|
719
|
+
`w-render="lazy"` with `w-hydrate="interaction"`.**
|
|
720
|
+
6. **Never combine `w-render="lazy"` with `w-hydrate="lazy"`.**
|
|
721
|
+
`w-render="lazy"` already includes viewport-deferred hydration.
|
|
722
|
+
7. **Never author `w-render="lazy"` without `w-reserve-block-size`.** The
|
|
723
|
+
reservation should approximate one instance's normal block size.
|
|
724
|
+
|
|
725
|
+
For a component with many initially offscreen SSR instances:
|
|
726
|
+
|
|
727
|
+
```html
|
|
728
|
+
<template w-render="lazy" w-reserve-block-size="72px">
|
|
729
|
+
<!-- Component content -->
|
|
730
|
+
</template>
|
|
731
|
+
```
|
|
732
|
+
|
|
733
|
+
For one offscreen SSR singleton whose module graph should remain unloaded until
|
|
734
|
+
use:
|
|
735
|
+
|
|
736
|
+
```html
|
|
737
|
+
<template
|
|
738
|
+
w-render="lazy"
|
|
739
|
+
w-reserve-block-size="18rem"
|
|
740
|
+
w-hydrate="interaction"
|
|
741
|
+
>
|
|
742
|
+
<!-- Component content -->
|
|
743
|
+
</template>
|
|
744
|
+
```
|
|
745
|
+
|
|
746
|
+
This keeps rendering containment active while interaction defers JavaScript and
|
|
747
|
+
heap. It is a singleton interaction boundary, not a repeated-item policy.
|
|
748
|
+
|
|
749
|
+
Import the optional coordinator once before component definitions:
|
|
750
|
+
|
|
751
|
+
```typescript
|
|
752
|
+
import '@microsoft/webui-framework/lazy-hydration.js';
|
|
753
|
+
import './feed-item.js';
|
|
754
|
+
```
|
|
755
|
+
|
|
756
|
+
On an instance, `w-hydrate="eager"` keeps rendering deferral but hydrates
|
|
757
|
+
immediately; `w-render="eager"` disables both. Use `hydratedCallback()` for work
|
|
758
|
+
that requires bindings or refs. Missing coordinator or browser support falls
|
|
759
|
+
back to eager hydration. Visibility-deferred hydration does not delay image
|
|
760
|
+
fetching; use native `loading="lazy"` and reconcile an already-complete `w-ref`
|
|
761
|
+
image from `hydratedCallback()` when component state depends on `@load` or
|
|
762
|
+
`@error`.
|
|
763
|
+
|
|
764
|
+
To defer a routed application until interaction, mark its root template:
|
|
765
|
+
|
|
766
|
+
```html
|
|
767
|
+
<template w-hydrate="interaction">
|
|
768
|
+
<nav>...</nav>
|
|
769
|
+
<outlet />
|
|
770
|
+
</template>
|
|
771
|
+
```
|
|
772
|
+
|
|
773
|
+
```typescript
|
|
774
|
+
import {
|
|
775
|
+
installInteractionHydration,
|
|
776
|
+
wakeInteractionHydration,
|
|
777
|
+
} from '@microsoft/webui-framework/interaction-hydration.js';
|
|
778
|
+
import { prepareRoutePreload } from '@microsoft/webui-router/preload.js';
|
|
779
|
+
|
|
780
|
+
let prepared: ReturnType<typeof prepareRoutePreload> | undefined;
|
|
781
|
+
const disposeHydration = installInteractionHydration({
|
|
782
|
+
onError: () => prepared?.destroy(),
|
|
783
|
+
load: async () => {
|
|
784
|
+
const [, { Router }] = await Promise.all([
|
|
785
|
+
import('./component-definitions.js'),
|
|
786
|
+
import('@microsoft/webui-router'),
|
|
787
|
+
]);
|
|
788
|
+
Router.start({ preload: prepared, loaders });
|
|
789
|
+
},
|
|
790
|
+
});
|
|
791
|
+
try {
|
|
792
|
+
prepared = prepareRoutePreload({
|
|
793
|
+
onIntent: () => wakeInteractionHydration(),
|
|
794
|
+
});
|
|
795
|
+
} catch (error) {
|
|
796
|
+
disposeHydration();
|
|
797
|
+
throw error;
|
|
798
|
+
}
|
|
799
|
+
```
|
|
800
|
+
|
|
801
|
+
The compiler marks the root. Hover stores one bounded raw route partial;
|
|
802
|
+
pointer/focus/keyboard/click intent imports components and router concurrently;
|
|
803
|
+
navigation adopts the response without refetching or parsing templates early.
|
|
804
|
+
Non-router apps use `installInteractionHydration({ load })`. This policy trades
|
|
805
|
+
first-interaction latency for lower startup JS/heap and cannot preserve
|
|
806
|
+
transient user activation or closed-shadow click targets.
|
|
807
|
+
|
|
808
|
+
| Decorator | Purpose | SSR? | Triggers DOM update? |
|
|
809
|
+
|---|---|---|---|
|
|
810
|
+
| `@attr` | HTML attribute reflection | Yes; an existing SSR host attribute wins | Yes |
|
|
811
|
+
| `@attr({ mode: 'boolean' })` | Boolean attribute (present/absent) | Yes; host presence wins | Yes |
|
|
812
|
+
| `@observable` | Reactive state used by TypeScript | Yes (from JSON state) | Yes |
|
|
813
|
+
|
|
814
|
+
| Method / property | Description |
|
|
815
|
+
|---|---|
|
|
816
|
+
| `this.$emit(name, detail?)` | Dispatch a bubbling CustomEvent |
|
|
817
|
+
| `this.$update()` | Force a reactive update cycle |
|
|
818
|
+
| `this.$flushUpdates()` | Synchronously flush pending updates |
|
|
819
|
+
| `protected hydratedCallback()` | Run synchronously once after the first successful hydration or client mount |
|
|
820
|
+
| `static define(tagName)` | Register as a custom element |
|
|
821
|
+
| `defineComponentAssets(manifest)` | Lazy component asset graphs from stable URLs or bundler importer callbacks, with compiler-owned Shadow Link preloading through `preload(tag)` / `create(tag)` |
|
|
822
|
+
|
|
823
|
+
### Custom events
|
|
824
|
+
|
|
825
|
+
```typescript
|
|
826
|
+
// Child
|
|
827
|
+
this.$emit('item-selected', { id: this.id, name: this.name });
|
|
828
|
+
```
|
|
829
|
+
|
|
830
|
+
```html
|
|
831
|
+
<!-- Parent template -->
|
|
832
|
+
<child-component @item-selected="{onItemSelected(e)}"></child-component>
|
|
833
|
+
```
|
|
834
|
+
|
|
835
|
+
```typescript
|
|
836
|
+
// Parent
|
|
837
|
+
onItemSelected(e: CustomEvent): void {
|
|
838
|
+
this.selectedId = e.detail.id;
|
|
839
|
+
}
|
|
840
|
+
```
|
|
841
|
+
|
|
842
|
+
### Hydration entry point
|
|
843
|
+
|
|
844
|
+
```typescript
|
|
845
|
+
// index.ts
|
|
846
|
+
import './app-shell/app-shell.js';
|
|
847
|
+
import './user-card/user-card.js';
|
|
848
|
+
```
|
|
849
|
+
|
|
850
|
+
Importing a component module registers it as a custom element, which triggers
|
|
851
|
+
hydration. Nothing else is required.
|
|
852
|
+
|
|
853
|
+
### The hydration boundary
|
|
854
|
+
|
|
855
|
+
Never write `@observable` values before hydration. During SSR hydration the
|
|
856
|
+
server-rendered DOM is trusted and not re-rendered, so a value set in a field
|
|
857
|
+
initializer, the constructor, or before `super.connectedCallback()` cannot
|
|
858
|
+
reach the DOM. The write is dropped and the runtime logs a `[WebUI] Hydration
|
|
859
|
+
mismatch` warning (development-only; stripped from production via
|
|
860
|
+
`__WEBUI_DEV__`).
|
|
861
|
+
|
|
862
|
+
If the value must appear in the first render, put it in the SSR state JSON.
|
|
863
|
+
Otherwise assign it in `hydratedCallback()`. On buffered SSR and client-created
|
|
864
|
+
mounts, `super.connectedCallback()` hydrates synchronously, but streamed hosts
|
|
865
|
+
and visibility-policy hosts (without an eager instance override) can return
|
|
866
|
+
while still deferred.
|
|
867
|
+
`hydratedCallback()` is the cross-mode signal: it runs synchronously exactly
|
|
868
|
+
once after the first successful hydration or mount, and reconnects or callback
|
|
869
|
+
exceptions do not retry it. Once a host has deferred, later state writes
|
|
870
|
+
are retained and replayed; this exception does not make constructor or
|
|
871
|
+
pre-`super.connectedCallback()` writes safe.
|
|
872
|
+
|
|
873
|
+
Load buffered definitions through a parser-inserted, non-async ES module script
|
|
874
|
+
or a classic `defer` script. Descendants must not structurally mutate a
|
|
875
|
+
containing WebUI component's SSR subtree before it hydrates - insertion,
|
|
876
|
+
removal, or reordering shifts compiled element indices.
|
|
877
|
+
|
|
878
|
+
### Progressive streaming hydration
|
|
879
|
+
|
|
880
|
+
`<boundary>` is a compile-time checkpoint directive for progressive sessions.
|
|
881
|
+
It is valid in entries and reusable components, including runtime conditions,
|
|
882
|
+
outlets, and selected route content.
|
|
883
|
+
|
|
884
|
+
```html
|
|
885
|
+
<!-- index.html -->
|
|
886
|
+
<head>
|
|
887
|
+
<script type="module" async src="/index.js"></script>
|
|
888
|
+
</head>
|
|
889
|
+
<body>
|
|
890
|
+
<ntp-page></ntp-page>
|
|
891
|
+
</body>
|
|
892
|
+
```
|
|
893
|
+
|
|
894
|
+
```html
|
|
895
|
+
<!-- ntp-page.html -->
|
|
896
|
+
<main>
|
|
897
|
+
<boundary name="search-ready">
|
|
898
|
+
<search-box query="{{query}}"></search-box>
|
|
899
|
+
</boundary>
|
|
900
|
+
<section>{{slowFeed}}</section>
|
|
901
|
+
</main>
|
|
902
|
+
```
|
|
903
|
+
|
|
904
|
+
- `name` is required, non-empty, static, and unique within its entry or
|
|
905
|
+
component owner. It
|
|
906
|
+
cannot contain a <code v-pre>{{binding}}</code>.
|
|
907
|
+
- Boundaries may appear inside reusable components, true `<if>` paths, and
|
|
908
|
+
selected route content. Authored boundaries may not contain another authored
|
|
909
|
+
boundary directly or transitively.
|
|
910
|
+
- A boundary-bearing subtree reached from a `<for>` body fails with
|
|
911
|
+
`boundary-in-repeat`, including declarations reached through a component,
|
|
912
|
+
condition, route, or outlet. A `<for>` may be wholly inside one boundary, and
|
|
913
|
+
boundaries before or after a `<for>` are valid.
|
|
914
|
+
- A component-owned declaration reached from multiple static callsites in one
|
|
915
|
+
entry traversal requires `key`; it must resolve to a unique live string or
|
|
916
|
+
finite number. Independent entries that each reach it once do not.
|
|
917
|
+
- Never author `<webui-hydrate>`. It is reserved generated runtime output.
|
|
918
|
+
- Explicitly import `@microsoft/webui-framework/streaming.js` in application
|
|
919
|
+
code. For a coordinator-only head script, put that import in a small
|
|
920
|
+
`src/streaming.ts` entry and load its output with `type="module" async`.
|
|
921
|
+
WebUI never creates the entry or injects the import. With any bundler, preserve
|
|
922
|
+
initialization, share framework modules, and use native output metadata for
|
|
923
|
+
the host's existing asset handoff. No streaming JSON file is required.
|
|
924
|
+
See
|
|
925
|
+
[Separate coordinator and application assets](/guide/concepts/hydration#separate-coordinator-and-application-assets).
|
|
926
|
+
- Deferred application scripts can use `fetchpriority="low"` to stay out of
|
|
927
|
+
automatic modulepreload hints. Components remain inert and retain pending
|
|
928
|
+
state until their definitions arrive, so load early-interactive registrations
|
|
929
|
+
when needed rather than postponing every registration.
|
|
930
|
+
- `start(state)`, `resume(instanceId, state, mode)`, and `advance()` return a
|
|
931
|
+
step with bytes, optional runtime descriptor
|
|
932
|
+
`{ instanceId, declarationId, owner, name, key }`, and `done`.
|
|
933
|
+
- Drive the step state exactly: descriptor present means `resume`; no descriptor
|
|
934
|
+
with `done == false` means `advance`; `done == true` means complete.
|
|
935
|
+
- `resume` writes only the pending occurrence through its checkpoint.
|
|
936
|
+
`advance` writes the following parent or shell bytes through the next
|
|
937
|
+
occurrence or terminal. No sibling boundary is needed to split an early
|
|
938
|
+
component child from its parent tail.
|
|
939
|
+
- `update(instanceId, patch)` accepts only a committed updatable occurrence.
|
|
940
|
+
It is valid between that occurrence's `resume` and `advance`, and calls
|
|
941
|
+
`setState()` without inserting markup, rerunning hydration, or rerunning
|
|
942
|
+
`hydratedCallback()`.
|
|
943
|
+
- State resolution across a suspension is lexical locals, resume state, then
|
|
944
|
+
the frozen projected parent state.
|
|
945
|
+
- `render_streaming` borrows one state value and keeps one prepared render
|
|
946
|
+
context for the complete response. Host-driven `stream_response` sessions use
|
|
947
|
+
each `resume` state as an overlay for newly resolved occurrence data.
|
|
948
|
+
`resume_current` skips the overlay when retained state is authoritative.
|
|
949
|
+
`start` and `resume` move freshly decoded owned `Value`s or borrow shared
|
|
950
|
+
values through the same method names.
|
|
951
|
+
- Range records may reference the exact prior range state by sequence
|
|
952
|
+
and carry only a top-level delta. Missing, stale, forward, mismatched, or
|
|
953
|
+
malformed references fail closed.
|
|
954
|
+
- A component-local boundary uses generated parent spans. Its early marked child
|
|
955
|
+
may hydrate before the opaque parent tail in light or shadow DOM.
|
|
956
|
+
- `webui:boundary-hydrated` is emitted only when
|
|
957
|
+
`window.__WEBUI_STREAMING_DEBUG__ === true`; its `detail.kind` is
|
|
958
|
+
`checkpoint`, `span`, `update`, or `terminal`. Every commit also emits an
|
|
959
|
+
unconditional `performance.mark()` (`webui:boundary:<id>`,
|
|
960
|
+
`webui:boundary:<id>:update`, `webui:span:<id>`,
|
|
961
|
+
`webui:streaming:terminal`) that tooling can read retroactively.
|
|
962
|
+
`webui:hydration-complete` fires only after the terminal record and eager
|
|
963
|
+
pending hydration work complete. Visibility-deferred lazy roots do not keep
|
|
964
|
+
this one-shot startup event open.
|
|
965
|
+
- `window.__WEBUI_STREAMING_SLICE_MS__` opts into a time-sliced drain that
|
|
966
|
+
yields between boundaries. Use it only when an intermediary coalesces the
|
|
967
|
+
response into one chunk; it costs total hydration time.
|
|
968
|
+
- A semantic flush hands bytes to the HTTP transport. Server adapters,
|
|
969
|
+
compression, proxies, and CDNs can still buffer them.
|
|
970
|
+
|
|
971
|
+
Malformed directives use stable diagnostics:
|
|
972
|
+
`missing-boundary-name`, `invalid-boundary-name`,
|
|
973
|
+
`duplicate-boundary-name`, `missing-boundary-key`,
|
|
974
|
+
`invalid-boundary-key`, `nested-boundary`, `boundary-in-repeat`,
|
|
975
|
+
`boundary-crosses-scope`, and `authored-webui-hydrate`. Malformed browser
|
|
976
|
+
records fail closed and release discoverable deferred state within fixed
|
|
977
|
+
bounds.
|
|
978
|
+
|
|
979
|
+
### Lazy component mounting
|
|
980
|
+
|
|
981
|
+
This is the **only** sanctioned place to insert an element from JavaScript,
|
|
982
|
+
because a lazily loaded component has no template representation until fetched.
|
|
983
|
+
|
|
984
|
+
Prefer the template-driven form, which needs no DOM insertion at all:
|
|
985
|
+
|
|
986
|
+
```typescript
|
|
987
|
+
await Router.ensureLoaded('settings-dialog');
|
|
988
|
+
this.showSettings = true;
|
|
989
|
+
```
|
|
990
|
+
|
|
991
|
+
With the framework loaded, `ensureLoaded()` also waits for bounded Link
|
|
992
|
+
stylesheet cache warming or a native-link fallback decision. Warmup bytes are
|
|
993
|
+
never applied; the first mounted instance remains guarded until the browser
|
|
994
|
+
validates its native link and can seed the shared constructable sheet. Redirect,
|
|
995
|
+
service-worker, authored `<style>`, or inaccessible-CSSOM cases keep the native
|
|
996
|
+
link rather than risking different response-base or cascade semantics.
|
|
997
|
+
If an authoritative native link fails, WebUI reports the error, keeps the link
|
|
998
|
+
native, releases the temporary guard, and completes hydration so the component
|
|
999
|
+
remains visible and usable even if it is unstyled.
|
|
1000
|
+
|
|
1001
|
+
```html
|
|
1002
|
+
<if condition="showSettings">
|
|
1003
|
+
<settings-dialog @close="{onCloseSettings()}"></settings-dialog>
|
|
1004
|
+
</if>
|
|
1005
|
+
```
|
|
1006
|
+
|
|
1007
|
+
Without `@microsoft/webui-router`, prebuild the asset and mount it into a
|
|
1008
|
+
`w-ref` slot:
|
|
1009
|
+
|
|
1010
|
+
```bash
|
|
1011
|
+
webui build ./src --out ./dist --plugin=webui \
|
|
1012
|
+
--emit-component-assets settings-dialog \
|
|
1013
|
+
--metafile ./dist/component-assets-meta.json
|
|
1014
|
+
```
|
|
1015
|
+
|
|
1016
|
+
```typescript
|
|
1017
|
+
import { defineComponentAssets } from '@microsoft/webui-framework/component-asset.js';
|
|
1018
|
+
|
|
1019
|
+
export const settingsAssets = defineComponentAssets({
|
|
1020
|
+
'settings-dialog': {
|
|
1021
|
+
asset: '/settings-dialog.webui.js',
|
|
1022
|
+
module: () => import('./settings-dialog/settings-dialog.js'),
|
|
1023
|
+
},
|
|
1024
|
+
});
|
|
1025
|
+
|
|
1026
|
+
async onOpenSettings(): Promise<void> {
|
|
1027
|
+
settingsAssets.preload('settings-dialog');
|
|
1028
|
+
this.panelSlot.replaceChildren(await settingsAssets.create('settings-dialog'));
|
|
1029
|
+
}
|
|
1030
|
+
```
|
|
1031
|
+
|
|
1032
|
+
The compiler stores final Link stylesheet hrefs in the protocol. Shadow builds
|
|
1033
|
+
publish them as inert head JSON that `preload(tag)` consumes automatically;
|
|
1034
|
+
Light builds emit them as document stylesheets. Authored code therefore keeps
|
|
1035
|
+
only the stable root asset URL and never invents or hardcodes a content-hashed
|
|
1036
|
+
stylesheet filename.
|
|
1037
|
+
Automatic Shadow intent preloading requires HTML rendered through the WebUI
|
|
1038
|
+
handler or `Protocol`, which emits `#webui-component-assets`. Using build
|
|
1039
|
+
artifacts without rendering the protocol preserves the guarded native mount but
|
|
1040
|
+
does not provide early compiler-owned style preloading.
|
|
1041
|
+
|
|
1042
|
+
Assets keep entry-owned templates external, inline dependencies used by one
|
|
1043
|
+
asset root, and split dependencies shared by multiple roots into deduplicated
|
|
1044
|
+
dynamic chunks. Do not copy generated chunk filenames into the manifest; each
|
|
1045
|
+
root asset carries its own dynamic imports. `create(tag)` waits for the template
|
|
1046
|
+
graph and module, then creates the element. Failed asset or authored module work
|
|
1047
|
+
is evicted so a later `preload(tag)` or `create(tag)` retries. The normal entry
|
|
1048
|
+
bundle must load first. Component assets cannot be combined with `<route>`; use
|
|
1049
|
+
the router for routed components.
|
|
1050
|
+
|
|
1051
|
+
## Routing
|
|
1052
|
+
|
|
1053
|
+
```html
|
|
1054
|
+
<route path="/" component="app-shell">
|
|
1055
|
+
<route path="" component="home-page" exact />
|
|
1056
|
+
<route path="users" component="user-list" exact />
|
|
1057
|
+
<route path="users/:id" component="user-detail" exact />
|
|
1058
|
+
</route>
|
|
1059
|
+
```
|
|
1060
|
+
|
|
1061
|
+
- Child paths are relative to the parent (no leading `/`).
|
|
1062
|
+
- Use `exact` on leaf routes; omit it on parents that have `<outlet />`.
|
|
1063
|
+
- Path params: `:id` (required), `:query?` (optional), `*path` (catch-all).
|
|
1064
|
+
- Initial SSR delivers CSS only for the matched route chain; inactive route
|
|
1065
|
+
styles remain deferred until navigation. Matched route CSS targeting the
|
|
1066
|
+
Document is applied before `</head>`. ShadowRoot-targeted Link CSS is preloaded
|
|
1067
|
+
from the head and applied inside its owning root. Static request-reachable
|
|
1068
|
+
Shadow roots are preloaded the same way.
|
|
1069
|
+
|
|
1070
|
+
| Attribute | Example | Description |
|
|
1071
|
+
|---|---|---|
|
|
1072
|
+
| `path` | `"users/:id"` | URL path template (relative to parent) |
|
|
1073
|
+
| `component` | `"user-detail"` | Component tag to mount |
|
|
1074
|
+
| `exact` | (boolean) | Require exact path match |
|
|
1075
|
+
| `query` | `"action,to,subject"` | Allowlist of query params set as attributes (deny-by-default) |
|
|
1076
|
+
| `keep-alive` | (boolean) | Preserve DOM and local state across navigations |
|
|
1077
|
+
| `cache-tags` | `"thread:{threadId},inbox"` | Cache tag templates resolved at render time |
|
|
1078
|
+
| `invalidates` | `"inbox,sent,counts"` | Tags auto-invalidated after mutation actions |
|
|
1079
|
+
| `pending` | `"loading-skeleton"` | Loading UI for slow navigations (>150ms) |
|
|
1080
|
+
| `error` | `"error-display"` | Error boundary on fetch failure |
|
|
1081
|
+
|
|
1082
|
+
All attributes are validated at build time. Referencing a non-existent `pending`
|
|
1083
|
+
or `error` component is a compile error.
|
|
1084
|
+
|
|
1085
|
+
```typescript
|
|
1086
|
+
Router.start({
|
|
1087
|
+
loaders: {
|
|
1088
|
+
'home-page': () => import('./pages/home-page.js'),
|
|
1089
|
+
'user-detail': () => import('./pages/user-detail.js'),
|
|
1090
|
+
},
|
|
1091
|
+
});
|
|
1092
|
+
```
|
|
1093
|
+
|
|
1094
|
+
Route loaders (`static loader({ params, query, signal })`) and actions
|
|
1095
|
+
(`static action({ formData, params, signal })`, enabled by
|
|
1096
|
+
`Router.start({ actions: true })`) live on the component class. Cache and
|
|
1097
|
+
preload are optional runtime tiers; a default `Router.start()` does not load the
|
|
1098
|
+
cache module.
|
|
1099
|
+
|
|
1100
|
+
Every route intended for partial navigation must register a custom element.
|
|
1101
|
+
Scriptless templates are registered by the compiler-owned host runtime. If a
|
|
1102
|
+
route remains unregistered after template publication and loader resolution, the
|
|
1103
|
+
router navigates the document so the server can render it.
|
|
1104
|
+
|
|
1105
|
+
Full detail: [Routing](/guide/concepts/routing).
|
|
1106
|
+
|
|
1107
|
+
## State JSON
|
|
1108
|
+
|
|
1109
|
+
```json
|
|
1110
|
+
{
|
|
1111
|
+
"title": "My App",
|
|
1112
|
+
"user": { "name": "Alice", "role": "admin" },
|
|
1113
|
+
"items": [
|
|
1114
|
+
{ "id": "1", "label": "First", "done": false },
|
|
1115
|
+
{ "id": "2", "label": "Second", "done": true }
|
|
1116
|
+
],
|
|
1117
|
+
"isAdmin": true,
|
|
1118
|
+
"showBanner": false
|
|
1119
|
+
}
|
|
1120
|
+
```
|
|
1121
|
+
|
|
1122
|
+
**Path resolution:** `title`, `user.name`, `items.0.label`, `items.length`
|
|
1123
|
+
|
|
1124
|
+
**Missing paths:** text bindings render empty. In conditions, a missing
|
|
1125
|
+
identifier is falsy, so `path` is false and `!path` is true. No error.
|
|
1126
|
+
|
|
1127
|
+
**Route-scoped state.** Each route handler should return only the keys that
|
|
1128
|
+
route's template binds to. Sending full app state on every route wastes
|
|
1129
|
+
bandwidth and render time.
|
|
1130
|
+
|
|
1131
|
+
### Reserved `$webui` state
|
|
1132
|
+
|
|
1133
|
+
The top-level `"$webui"` object is reserved for trusted host HTML emitted at
|
|
1134
|
+
document boundaries:
|
|
1135
|
+
|
|
1136
|
+
```json
|
|
1137
|
+
{
|
|
1138
|
+
"$webui": {
|
|
1139
|
+
"headEnd": "<link rel=\"preload\" as=\"image\" href=\"/hero.avif\">",
|
|
1140
|
+
"bodyStart": "<!-- immediately after <body> -->",
|
|
1141
|
+
"bodyEnd": "<script src=\"/livereload.js\"></script>"
|
|
1142
|
+
}
|
|
1143
|
+
}
|
|
1144
|
+
```
|
|
1145
|
+
|
|
1146
|
+
All three members are optional strings. `headEnd`, `bodyStart`, and `bodyEnd`
|
|
1147
|
+
are emitted raw immediately before `</head>`, after `<body>`, and before
|
|
1148
|
+
`</body>`, respectively. Missing, empty, `null`, or non-string members are
|
|
1149
|
+
ignored. WebUI strips the reserved object from hydration and partial-navigation
|
|
1150
|
+
state, so client-side templates and code cannot read it.
|
|
1151
|
+
|
|
1152
|
+
**Never put request-derived or otherwise untrusted content in `$webui`.** The
|
|
1153
|
+
values are not escaped and can create an XSS vulnerability. See
|
|
1154
|
+
[Integrations](/guide/integrations/) for host-specific rendering details.
|
|
1155
|
+
|
|
1156
|
+
### Truthiness
|
|
1157
|
+
|
|
1158
|
+
| Value | Truthy? |
|
|
1159
|
+
|---|---|
|
|
1160
|
+
| `true` | Yes |
|
|
1161
|
+
| `false` | No |
|
|
1162
|
+
| `0` | No |
|
|
1163
|
+
| Non-zero number | Yes |
|
|
1164
|
+
| `""` (empty string) | No |
|
|
1165
|
+
| `"false"` (string!) | **Yes** (non-empty string) |
|
|
1166
|
+
| `[]` (empty array) | No (server) / **Yes** (client) - always use `.length` |
|
|
1167
|
+
| `{}` (empty object) | No (server) / **Yes** (client) - test a real field |
|
|
1168
|
+
| `null` / missing key | No |
|
|
1169
|
+
|
|
1170
|
+
**Never use the string `"false"` for boolean state. Use real booleans.**
|
|
1171
|
+
|
|
1172
|
+
**Never test a bare array or object for truthiness.** The server evaluator treats
|
|
1173
|
+
empty collections as falsy; the compiled client condition is plain JS `!!value`,
|
|
1174
|
+
where `[]` and `{}` are truthy. Writing `<if condition="items">` means SSR and
|
|
1175
|
+
hydration can disagree. Write `<if condition="items.length">` instead - that
|
|
1176
|
+
agrees on both sides.
|
|
1177
|
+
|
|
1178
|
+
## Anti-patterns
|
|
1179
|
+
|
|
1180
|
+
### Building UI from JavaScript
|
|
1181
|
+
|
|
1182
|
+
```typescript
|
|
1183
|
+
// WRONG
|
|
1184
|
+
const row = document.createElement('div');
|
|
1185
|
+
row.textContent = item.name;
|
|
1186
|
+
this.list.appendChild(row);
|
|
1187
|
+
|
|
1188
|
+
// WRONG
|
|
1189
|
+
this.list.innerHTML = items.map(i => `<div>${i.name}</div>`).join('');
|
|
1190
|
+
```
|
|
1191
|
+
|
|
1192
|
+
```html
|
|
1193
|
+
<!-- RIGHT -->
|
|
1194
|
+
<for each="item in items">
|
|
1195
|
+
<div>{{item.name}}</div>
|
|
1196
|
+
</for>
|
|
1197
|
+
```
|
|
1198
|
+
|
|
1199
|
+
### Styling from JavaScript
|
|
1200
|
+
|
|
1201
|
+
```typescript
|
|
1202
|
+
// WRONG
|
|
1203
|
+
this.panel.style.background = this.isActive ? 'blue' : 'transparent';
|
|
1204
|
+
this.panel.classList.toggle('active', this.isActive);
|
|
1205
|
+
this.shadowRoot.adoptedStyleSheets = [sheet];
|
|
1206
|
+
```
|
|
1207
|
+
|
|
1208
|
+
```html
|
|
1209
|
+
<!-- RIGHT -->
|
|
1210
|
+
<div class="panel" ?data-active="{{isActive}}">...</div>
|
|
1211
|
+
```
|
|
1212
|
+
|
|
1213
|
+
```css
|
|
1214
|
+
.panel[data-active] { background: var(--accent); }
|
|
1215
|
+
```
|
|
1216
|
+
|
|
1217
|
+
### Animating from JavaScript
|
|
1218
|
+
|
|
1219
|
+
```typescript
|
|
1220
|
+
// WRONG
|
|
1221
|
+
el.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 200 });
|
|
1222
|
+
// WRONG
|
|
1223
|
+
let o = 0; setInterval(() => { el.style.opacity = String(o += 0.05); }, 16);
|
|
1224
|
+
```
|
|
1225
|
+
|
|
1226
|
+
```css
|
|
1227
|
+
/* RIGHT */
|
|
1228
|
+
.toast { transition: opacity 200ms ease; opacity: 1; }
|
|
1229
|
+
@starting-style { .toast { opacity: 0; } }
|
|
1230
|
+
```
|
|
1231
|
+
|
|
1232
|
+
### Unnecessary framework surface
|
|
1233
|
+
|
|
1234
|
+
```typescript
|
|
1235
|
+
// WRONG - nothing in TypeScript touches these
|
|
1236
|
+
@observable heading = 'Welcome';
|
|
1237
|
+
@observable subtitle = 'Get started below';
|
|
1238
|
+
```
|
|
1239
|
+
|
|
1240
|
+
```json
|
|
1241
|
+
// RIGHT - server state JSON
|
|
1242
|
+
{ "heading": "Welcome", "subtitle": "Get started below" }
|
|
1243
|
+
```
|
|
1244
|
+
|
|
1245
|
+
### Shadow observables that mirror an expression
|
|
1246
|
+
|
|
1247
|
+
```typescript
|
|
1248
|
+
// WRONG
|
|
1249
|
+
@observable items: Item[] = [];
|
|
1250
|
+
@observable hasItems = false;
|
|
1251
|
+
onItemsChanged(): void { this.hasItems = this.items.length > 0; }
|
|
1252
|
+
```
|
|
1253
|
+
|
|
1254
|
+
```html
|
|
1255
|
+
<!-- RIGHT -->
|
|
1256
|
+
<if condition="items.length">...</if>
|
|
1257
|
+
<button ?disabled="{{currentIndex == 0}}">Prev</button>
|
|
1258
|
+
<option ?selected="{{app.slug == currentApp.slug}}">{{app.name}}</option>
|
|
1259
|
+
```
|
|
1260
|
+
|
|
1261
|
+
Loop variables compose with outer component state in the same expression, so
|
|
1262
|
+
per-item flags like `isCurrent` in the SSR JSON are almost never needed.
|
|
1263
|
+
|
|
1264
|
+
Text bindings do path lookups only. If you need `{{currentIndex + 1}}` for a
|
|
1265
|
+
1-based display, that is a legitimate `@observable` or a precomputed state key.
|
|
1266
|
+
|
|
1267
|
+
### Reading DOM instead of state
|
|
1268
|
+
|
|
1269
|
+
```typescript
|
|
1270
|
+
// WRONG
|
|
1271
|
+
const value = this.shadowRoot.querySelector('.count').textContent;
|
|
1272
|
+
```
|
|
1273
|
+
|
|
1274
|
+
Use `@observable` for state TypeScript changes, template bindings for output,
|
|
1275
|
+
and `w-ref` only for imperative APIs.
|
|
1276
|
+
|
|
1277
|
+
### Hand-built platform primitives
|
|
1278
|
+
|
|
1279
|
+
```html
|
|
1280
|
+
<!-- WRONG -->
|
|
1281
|
+
<div class="modal-backdrop" @click="{close()}">
|
|
1282
|
+
<div class="modal" role="dialog">...</div>
|
|
1283
|
+
</div>
|
|
1284
|
+
|
|
1285
|
+
<!-- RIGHT -->
|
|
1286
|
+
<dialog w-ref="{dialogEl}" @close="{onClose()}">...</dialog>
|
|
1287
|
+
```
|
|
1288
|
+
|
|
1289
|
+
`showModal()` gives focus trapping, `inert` backdrop, Escape handling, and
|
|
1290
|
+
top-layer stacking for free.
|
|
1291
|
+
|
|
1292
|
+
### Also not supported
|
|
1293
|
+
|
|
1294
|
+
1. **No ternary in templates.** `{{x ? 'yes' : 'no'}}` does not work.
|
|
1295
|
+
2. **No function calls in bindings.** `{{formatDate(item.date)}}` does not work.
|
|
1296
|
+
Compute on the server or in an event handler.
|
|
1297
|
+
3. **No mixed `&&` and `||`** in one condition. Split into nested `<if>` blocks.
|
|
1298
|
+
4. **No parentheses in conditions.**
|
|
1299
|
+
5. **No JavaScript in HTML templates.** Templates compile to binary.
|
|
1300
|
+
6. **No JavaScript in CSS.** Use custom properties for dynamic values.
|
|
1301
|
+
7. **No computed getters for SSR state.**
|
|
1302
|
+
8. **Components inside `<for>` do NOT inherit loop variables.**
|
|
1303
|
+
9. **No `import` or `require` in templates.** Components are discovered by file
|
|
1304
|
+
naming convention.
|
|
1305
|
+
10. **Non-braced `w-ref`** fails the build. Use `w-ref="{name}"`.
|
|
1306
|
+
|
|
1307
|
+
## Pre-flight checklist
|
|
1308
|
+
|
|
1309
|
+
Before emitting WebUI code, confirm:
|
|
1310
|
+
|
|
1311
|
+
- [ ] No `createElement`, `innerHTML`, `appendChild`, or `insertAdjacentHTML`,
|
|
1312
|
+
except mounting a lazily loaded component.
|
|
1313
|
+
- [ ] No `.style.x =`, `classList`, `setAttribute('style')`, or
|
|
1314
|
+
`adoptedStyleSheets`.
|
|
1315
|
+
- [ ] No `element.animate()`, `requestAnimationFrame` tweening, or animation
|
|
1316
|
+
library. Animation is in `.css`.
|
|
1317
|
+
- [ ] Every `.ts` file exists because of an event, `w-ref`, lifecycle hook,
|
|
1318
|
+
fetch, or public API - not by default.
|
|
1319
|
+
- [ ] Every `@observable` / `@attr` is read or written by TypeScript, or is
|
|
1320
|
+
public API. Otherwise it moved to the state JSON.
|
|
1321
|
+
- [ ] No observable mirrors an expression the template can evaluate.
|
|
1322
|
+
- [ ] Every `{{binding}}`, `<if>`, and `<for>` path exists in the state JSON.
|
|
1323
|
+
- [ ] Every `w-ref` uses braces.
|
|
1324
|
+
- [ ] A built-in element was considered before a hand-built one
|
|
1325
|
+
(`<dialog>`, `popover`, `<details>`).
|
|
1326
|
+
- [ ] `::view-transition-*` rules are in the entry template, not component CSS.
|
|
1327
|
+
- [ ] `prefers-reduced-motion` is honored wherever motion is used.
|
|
1328
|
+
- [ ] No conditions mix `&&` with `||`, use parentheses, or use a ternary.
|
|
1329
|
+
- [ ] Every native `<slot>` resolves to Shadow DOM; in a `--dom light` build its
|
|
1330
|
+
component authors a sole top-level `<template shadowrootmode="open">`.
|
|
1331
|
+
- [ ] A sole bare top-level `<template>` is an explicit Light wrapper and is
|
|
1332
|
+
unwrapped even when the build fallback is Shadow.
|
|
1333
|
+
|
|
1334
|
+
## Build and run
|
|
1335
|
+
|
|
1336
|
+
```bash
|
|
1337
|
+
# Dev server with live reload
|
|
1338
|
+
webui serve ./src --state ./data/state.json --plugin=webui --watch
|
|
1339
|
+
|
|
1340
|
+
# Production build
|
|
1341
|
+
webui build ./src --out ./dist --plugin=webui
|
|
1342
|
+
|
|
1343
|
+
# Inspect the compiled protocol
|
|
1344
|
+
webui inspect ./dist/protocol.bin
|
|
1345
|
+
```
|
|
1346
|
+
|
|
1347
|
+
Common flags on both commands: `--entry`, `--css <link|style|module>`,
|
|
1348
|
+
`--dom <shadow|light>` (default `shadow`),
|
|
1349
|
+
`--css-bundle` (merge component stylesheets into shared chunks; not valid with
|
|
1350
|
+
`--css module`), `--components`, `--theme`,
|
|
1351
|
+
`--projection-manifest`, `--emit-component-assets`, `--metafile`,
|
|
1352
|
+
`--format json`.
|
|
1353
|
+
|
|
1354
|
+
On `webui serve` (with or without `--watch`) and `webui-press serve`, optionally
|
|
1355
|
+
add `--shutdown-timeout 10` for a ten-second shutdown grace period. Omit it to
|
|
1356
|
+
retain the default wait for an active rebuild with no deadline. Forced shutdown
|
|
1357
|
+
returns nonzero and may leave incomplete outputs; supervised mode reserves
|
|
1358
|
+
stdin. See [bounded shutdown](/guide/cli/#bounded-dev-server-shutdown) for
|
|
1359
|
+
platform limits.
|
|
1360
|
+
|
|
1361
|
+
Unwrapped components default to Shadow. Under `--dom light`, they use
|
|
1362
|
+
authored/global Light DOM while a sole top-level
|
|
1363
|
+
`<template shadowrootmode="open">` remains a Shadow island. A sole bare
|
|
1364
|
+
`<template>` explicitly selects Light and is unwrapped.
|
|
1365
|
+
|
|
1366
|
+
Authoring mistakes fail the build with a structured diagnostic carrying a stable
|
|
1367
|
+
code, source location, snippet, and a `help:` fix. Branch on the `code`, never
|
|
1368
|
+
the message. `--format json` emits one JSON object per error on stdout.
|
|
1369
|
+
|
|
1370
|
+
```
|
|
1371
|
+
x error: invalid <for> each expression [invalid-for-each]
|
|
1372
|
+
--> index.html:67:5
|
|
1373
|
+
each="person inpeople"
|
|
1374
|
+
help: use the form each="item in collection", e.g. each="todo in todos"
|
|
1375
|
+
```
|
|
1376
|
+
|
|
1377
|
+
Full flag tables, exit codes, and the error-code list:
|
|
1378
|
+
[CLI Reference](/guide/cli/).
|
|
1379
|
+
|
|
1380
|
+
### External component discovery
|
|
1381
|
+
|
|
1382
|
+
Native `--components` discovery derives names from `<component-name>.html`,
|
|
1383
|
+
scanning a package's `components/` directory when present or its root otherwise.
|
|
1384
|
+
Template/style exports and CEM names are not interpreted by default discovery;
|
|
1385
|
+
FAST's special metadata-based layouts remain separate.
|
|
1386
|
+
Npm collection spellings `@scope/*` and `@scope/package/*` are accepted.
|
|
1387
|
+
Package subpaths and traversal are not package identifiers; use `./components`
|
|
1388
|
+
or another explicit local path for filesystem discovery.
|
|
1389
|
+
Import browser registrations through the package's module exports separately.
|
|
1390
|
+
Catalog script ownership follows matching `.ts`/`.js` siblings per component;
|
|
1391
|
+
package exports and `.spec.ts` files do not make unrelated scriptless tags
|
|
1392
|
+
require registration imports or projection entries.
|
|
1393
|
+
|
|
1394
|
+
### WebUI Press
|
|
1395
|
+
|
|
1396
|
+
Use native `webui-press build --show=content` or `webui-press serve --show=content`
|
|
1397
|
+
to generate Markdown/examples/API panels without Press shell UI. Default mode
|
|
1398
|
+
is `all`; explicit CLI values override config `show` across live reloads.
|
|
1399
|
+
Content mode retains the complete document, themes, SSR, and hydration.
|
|
1400
|
+
Content colors follow the OS, including live preference changes, without
|
|
1401
|
+
reading the full site's saved manual theme. Full mode retains its persisted
|
|
1402
|
+
theme control and applies that choice to native theme tokens and controls.
|
|
1403
|
+
See [WebUI Press](/guide/webui-press) for layout and asset behavior.
|
|
1404
|
+
|
|
1405
|
+
In a WebUI Press template, use paired regions for fallback markup and
|
|
1406
|
+
self-closing regions for empty insertion points:
|
|
1407
|
+
|
|
1408
|
+
```html
|
|
1409
|
+
<webui-press-region name="home.afterHero" layout="home">
|
|
1410
|
+
<project-summary></project-summary>
|
|
1411
|
+
</webui-press-region>
|
|
1412
|
+
```
|
|
1413
|
+
|
|
1414
|
+
A matching `regions` entry in `.webui-press/config.json` may replace or clear
|
|
1415
|
+
the HTML, add object state beneath the dotted `regions.*` path, and add a
|
|
1416
|
+
page-scoped `scriptFile`. Omit `html`/`htmlFile` to retain the fallback. Regions
|
|
1417
|
+
resolve before component discovery and compilation; do not manually register
|
|
1418
|
+
their components elsewhere. See [WebUI Press named regions](/guide/webui-press)
|
|
1419
|
+
for the stable built-in region list and full configuration contract.
|
|
1420
|
+
|
|
1421
|
+
```json
|
|
1422
|
+
{
|
|
1423
|
+
"scripts": {
|
|
1424
|
+
"build:client": "node build-client.mjs",
|
|
1425
|
+
"build:protocol": "webui build ./src --out ./dist --plugin=webui --projection-manifest ./dist/webui-projection.json",
|
|
1426
|
+
"build": "npm run build:client && npm run build:protocol",
|
|
1427
|
+
"dev:server": "webui serve ./src --state ./data/state.json --plugin=webui --projection-manifest ./dist/webui-projection.json --watch"
|
|
1428
|
+
},
|
|
1429
|
+
"dependencies": {
|
|
1430
|
+
"@microsoft/webui": "latest",
|
|
1431
|
+
"@microsoft/webui-framework": "latest"
|
|
1432
|
+
}
|
|
1433
|
+
}
|
|
1434
|
+
```
|
|
1435
|
+
|
|
1436
|
+
Add `@microsoft/webui-router` for client-side navigation. Passing
|
|
1437
|
+
`--projection-manifest` narrows hydration state to exactly the `@observable` and
|
|
1438
|
+
`@attr` fields your bundle uses; omitting it keeps full state.
|
|
1439
|
+
|
|
1440
|
+
## Server integration
|
|
1441
|
+
|
|
1442
|
+
Any backend loads `protocol.bin` once and renders with JSON state per request.
|
|
1443
|
+
|
|
1444
|
+
```rust
|
|
1445
|
+
let protocol = Protocol::from_protobuf(&fs::read("dist/protocol.bin")?)?;
|
|
1446
|
+
let handler = WebUIHandler::new();
|
|
1447
|
+
handler.render(&protocol, &state, &options, &mut writer)?;
|
|
1448
|
+
```
|
|
1449
|
+
|
|
1450
|
+
For one Rust endpoint that serves both initial documents and router partials,
|
|
1451
|
+
pass the complete per-response options through `ServeRequest`. Always attach a
|
|
1452
|
+
fresh document CSP nonce before calling the helper:
|
|
1453
|
+
|
|
1454
|
+
```rust
|
|
1455
|
+
let options = RenderOptions::new("index.html", request_path)
|
|
1456
|
+
.with_nonce(csp_nonce);
|
|
1457
|
+
let request = ServeRequest::new(options, accepts_json, inventory_header);
|
|
1458
|
+
let response = serve_request(&protocol, &handler, state, &request)?;
|
|
1459
|
+
```
|
|
1460
|
+
|
|
1461
|
+
```javascript
|
|
1462
|
+
const protocol = new Protocol(result.protocol, { plugin: 'webui' });
|
|
1463
|
+
const html = protocol.render(state, { entry: 'index.html', requestPath: req.url });
|
|
1464
|
+
```
|
|
1465
|
+
|
|
1466
|
+
For repeated renders of one immutable Node state snapshot, call
|
|
1467
|
+
`protocol.prepareState(state)` once and pass the result to
|
|
1468
|
+
`protocol.renderPrepared(prepared, options)`. Prepare a new snapshot when state
|
|
1469
|
+
changes.
|
|
1470
|
+
|
|
1471
|
+
For Rust progressive hydration, create a `StreamingResponse` over a
|
|
1472
|
+
`FlushWriter`. Keep one bounded worker as the response owner, cap admitted
|
|
1473
|
+
renders before spawning it, and configure the transport's flush timeout.
|
|
1474
|
+
|
|
1475
|
+
```rust
|
|
1476
|
+
let mut page = handler.stream_response(&protocol, &options, &mut writer)?;
|
|
1477
|
+
let mut step = page.start(&initial_state)?;
|
|
1478
|
+
while !step.done {
|
|
1479
|
+
step = match step.boundary.as_ref() {
|
|
1480
|
+
Some(boundary) => {
|
|
1481
|
+
let state =
|
|
1482
|
+
load_state(&boundary.owner, &boundary.name, boundary.key.as_ref())?;
|
|
1483
|
+
page.resume(boundary.instance_id, &state, BoundaryMode::Final)?
|
|
1484
|
+
}
|
|
1485
|
+
None => page.advance()?,
|
|
1486
|
+
};
|
|
1487
|
+
}
|
|
1488
|
+
```
|
|
1489
|
+
|
|
1490
|
+
With `webui serve --api-port`, a Node or other HTTP backend can return
|
|
1491
|
+
newline-delimited control records instead:
|
|
1492
|
+
|
|
1493
|
+
```text
|
|
1494
|
+
{"type":"start","version":2,"state":{"query":""}}
|
|
1495
|
+
{"type":"resume","boundary":{"owner":"ntp-page","name":"search-ready"},"state":{"query":""},"mode":"updatable"}
|
|
1496
|
+
{"type":"update","boundary":{"owner":"ntp-page","name":"search-ready"},"state":{"query":"webui"}}
|
|
1497
|
+
```
|
|
1498
|
+
|
|
1499
|
+
Honor HTTP write backpressure and cap concurrent streams. The CLI uses a
|
|
1500
|
+
capacity-one command channel and matches each `boundary` target by
|
|
1501
|
+
descriptor `owner`, `name`, and optional `key` (plus optional
|
|
1502
|
+
`declarationId`). It keeps response-local instance IDs, the compiled protocol,
|
|
1503
|
+
and browser-facing bytes in Rust. A resume control commits boundary-only bytes;
|
|
1504
|
+
the CLI then calls `advance` internally for the following parent bytes. The
|
|
1505
|
+
control stream needs no advance record. After the backend sends the resume for
|
|
1506
|
+
the final descriptor and closes its body, the CLI's final `advance` completes
|
|
1507
|
+
the response. Returning JSON keeps the buffered state path.
|
|
1508
|
+
|
|
1509
|
+
If the backend refuses a stream request (non-success status such as a `503`
|
|
1510
|
+
from its own concurrency cap), no response bytes were sent, so `webui serve` logs
|
|
1511
|
+
one warning and renders the page from fallback state rather than replacing the
|
|
1512
|
+
app with the upstream error body. A failure *after* the stream is live still
|
|
1513
|
+
fails the response, because bytes already flushed cannot be rewound.
|
|
1514
|
+
|
|
1515
|
+
Equivalent APIs exist for WebAssembly, Python (native `microsoft-webui`
|
|
1516
|
+
package), Go (cgo), and C#. For `Router.ensureLoaded()`, expose
|
|
1517
|
+
`GET /_webui/templates?t=tag1,tag2` backed by
|
|
1518
|
+
`render_component_templates(&tags, &inv)`.
|
|
1519
|
+
|
|
1520
|
+
Full detail: [Integrations](/guide/integrations/).
|
|
1521
|
+
|
|
1522
|
+
## Where to read more
|
|
1523
|
+
|
|
1524
|
+
| Topic | Page |
|
|
1525
|
+
|---|---|
|
|
1526
|
+
| Directives (`if`, `for`, attributes, `route`) | [/guide/concepts/directives/](/guide/concepts/directives/) |
|
|
1527
|
+
| Component authoring and interactivity | [/guide/concepts/interactivity](/guide/concepts/interactivity) |
|
|
1528
|
+
| Lazy/interaction policy syntax and combinations | [/guide/concepts/directives/lazy](/guide/concepts/directives/lazy) |
|
|
1529
|
+
| Hydration lifecycle, projection, and streaming | [/guide/concepts/hydration](/guide/concepts/hydration) |
|
|
1530
|
+
| Best practices and React-habit pitfalls | [/guide/concepts/best-practices](/guide/concepts/best-practices) |
|
|
1531
|
+
| Performance strategy and measurement | [/guide/concepts/performance](/guide/concepts/performance) |
|
|
1532
|
+
| Routing, loaders, actions, caching | [/guide/concepts/routing](/guide/concepts/routing) |
|
|
1533
|
+
| Design tokens and theming | [/guide/concepts/css-tokens](/guide/concepts/css-tokens) |
|
|
1534
|
+
| CLI flags, diagnostics, exit codes | [/guide/cli/](/guide/cli/) |
|
|
1535
|
+
| WebUI Press named regions | [/guide/webui-press](/guide/webui-press) |
|
|
1536
|
+
| Rust, Node, Python, WASM, FFI, Electron | [/guide/integrations/](/guide/integrations/) |
|
|
1537
|
+
| Build a first app | [/tutorials/hello-world/](/tutorials/hello-world/) |
|