@microsoft/fast-element 2.10.1 → 2.10.3

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.
Files changed (41) hide show
  1. package/ARCHITECTURE_FASTELEMENT.md +1 -1
  2. package/ARCHITECTURE_HTML_TAGGED_TEMPLATE_LITERAL.md +3 -1
  3. package/ARCHITECTURE_INTRO.md +1 -1
  4. package/ARCHITECTURE_OVERVIEW.md +1 -1
  5. package/CHANGELOG.json +153 -1
  6. package/CHANGELOG.md +18 -2
  7. package/DESIGN.md +506 -0
  8. package/biome.json +4 -0
  9. package/dist/context/context.api.json +17 -1
  10. package/dist/di/di.api.json +17 -1
  11. package/dist/dts/hydration/target-builder.d.ts +17 -1
  12. package/dist/dts/templating/html-binding-directive.d.ts +39 -4
  13. package/dist/dts/templating/html-directive.d.ts +7 -1
  14. package/dist/dts/templating/template.d.ts +19 -1
  15. package/dist/dts/templating/view.d.ts +11 -0
  16. package/dist/dts/testing/models.d.ts +20 -0
  17. package/dist/dts/tsdoc-metadata.json +1 -1
  18. package/dist/esm/components/element-controller.js +3 -0
  19. package/dist/esm/components/hydration.js +17 -0
  20. package/dist/esm/hydration/target-builder.js +22 -1
  21. package/dist/esm/templating/compiler.js +29 -11
  22. package/dist/esm/templating/html-binding-directive.js +59 -4
  23. package/dist/esm/templating/html-directive.js +7 -1
  24. package/dist/esm/templating/install-hydratable-view-templates.js +6 -0
  25. package/dist/esm/templating/markup.js +8 -0
  26. package/dist/esm/templating/template.js +19 -1
  27. package/dist/esm/templating/view.js +13 -0
  28. package/dist/esm/testing/models.js +58 -0
  29. package/dist/fast-element.api.json +20 -4
  30. package/dist/fast-element.debug.js +179 -227
  31. package/dist/fast-element.debug.min.js +2 -2
  32. package/dist/fast-element.js +179 -227
  33. package/dist/fast-element.min.js +2 -2
  34. package/dist/fast-element.untrimmed.d.ts +76 -6
  35. package/docs/api-report.api.md +3 -3
  36. package/package.json +7 -19
  37. package/playwright.config.ts +8 -0
  38. package/test/main.ts +95 -1
  39. package/tsconfig.api-extractor.json +6 -0
  40. package/.eslintrc.json +0 -19
  41. package/karma.conf.cjs +0 -148
package/DESIGN.md ADDED
@@ -0,0 +1,506 @@
1
+ # FAST Element – Design Overview
2
+
3
+ This document is a contributor-oriented guide to the architecture of `@microsoft/fast-element`. It synthesises the individual architecture documents into a single entry point and explains how all the pieces fit together.
4
+
5
+ For deep dives into specific areas, see the linked detailed documents.
6
+
7
+ ---
8
+
9
+ ## Table of Contents
10
+
11
+ 1. [High-Level Overview](#high-level-overview)
12
+ 2. [Core Concepts](#core-concepts)
13
+ - [FAST Global](#fast-global)
14
+ - [FASTElement & ElementController](#fastelement--elementcontroller)
15
+ - [Observables & Notifiers](#observables--notifiers)
16
+ - [Bindings](#bindings)
17
+ - [html Tagged Template Literal](#html-tagged-template-literal)
18
+ - [ViewTemplate & Compiler](#viewtemplate--compiler)
19
+ - [Views & Behaviors](#views--behaviors)
20
+ - [Updates Queue](#updates-queue)
21
+ - [Styles](#styles)
22
+ - [Dependency Injection (DI)](#dependency-injection-di)
23
+ - [Context Protocol](#context-protocol)
24
+ - [State Helpers](#state-helpers)
25
+ 3. [Data Flow Diagrams](#data-flow-diagrams)
26
+ - [Module Load & Registration](#module-load--registration)
27
+ - [FASTElement Lifecycle](#fastelement-lifecycle)
28
+ - [Template Pipeline](#template-pipeline)
29
+ - [Observable Change Propagation](#observable-change-propagation)
30
+ 4. [How the Pieces Fit Together](#how-the-pieces-fit-together)
31
+ 5. [Package Layout](#package-layout)
32
+ 6. [Detailed Architecture Documents](#detailed-architecture-documents)
33
+
34
+ ---
35
+
36
+ ## High-Level Overview
37
+
38
+ `@microsoft/fast-element` is a lightweight library for building standards-based Custom Elements (Web Components). Its key responsibilities are:
39
+
40
+ | Concern | What FAST provides |
41
+ |---|---|
42
+ | Element authoring | `FASTElement` base class + `@customElement`, `@attr`, `@observable` decorators |
43
+ | Reactive data binding | `Observable`, `ExpressionNotifier`, `oneWay`/`oneTime`/`listener` bindings |
44
+ | Declarative templating | `html` tagged template literal → `ViewTemplate` → compiled `HTMLView` |
45
+ | Async DOM updates | `Updates` queue (batched, `requestAnimationFrame`-aligned) |
46
+ | Scoped styles | `css` tagged template literal → `ElementStyles` → `adoptedStylesheets` / `<style>` |
47
+ | Dependency injection | `DI` container, `@inject`, `@singleton`, `@transient`, resolvers |
48
+ | Context protocol | W3C community Context protocol (`Context.create`, `Context.for`) |
49
+ | Reactive state helpers | `state()`, `watch()` (beta) |
50
+
51
+ The library's kernel (the `FAST` global, the `Updates` queue, and the `Observable` system) is stored on `globalThis.FAST` and can be shared across multiple versions of the library loaded on the same page.
52
+
53
+ ---
54
+
55
+ ## Core Concepts
56
+
57
+ ### FAST Global
58
+
59
+ **File**: `src/platform.ts`, `src/interfaces.ts`
60
+
61
+ `FAST` is a singleton object attached to `globalThis`. It provides:
62
+
63
+ - `FAST.getById(id, initializer)` – shared kernel slot registry (used to share the update queue and observable system across FAST instances)
64
+ - `FAST.warn(code, values)` / `FAST.error(code, values)` – structured diagnostic messages
65
+ - `FAST.addMessages(dict)` – registers human-readable debug messages (imported by `src/debug.ts`)
66
+
67
+ The `KernelServiceId` object controls which numeric/string keys are used for shared services. Three modes are supported via a `fast-kernel` attribute on the current `<script>` tag:
68
+
69
+ | Mode | Behaviour |
70
+ |---|---|
71
+ | `share` | Share the kernel across any FAST version |
72
+ | `share-v2` | Share only with other v2 instances |
73
+ | *(default)* | Fully isolated instance with a random postfix |
74
+
75
+ ---
76
+
77
+ ### FASTElement & ElementController
78
+
79
+ **Files**: `src/components/fast-element.ts`, `src/components/element-controller.ts`, `src/components/fast-definitions.ts`
80
+
81
+ `FASTElement` is a thin mixin applied on top of `HTMLElement`. It:
82
+
83
+ 1. Calls `ElementController.forCustomElement(this)` in its `constructor` to create or locate the element's controller.
84
+ 2. Delegates all lifecycle hooks to the controller:
85
+ - `connectedCallback` → `$fastController.connect()`
86
+ - `disconnectedCallback` → `$fastController.disconnect()`
87
+ - `attributeChangedCallback` → `$fastController.onAttributeChangedCallback()`
88
+
89
+ `ElementController` is the real workhorse. It:
90
+
91
+ - Extends `PropertyChangeNotifier` so the element itself participates in the observable system.
92
+ - Holds the element's `FASTElementDefinition` (name, template, styles, observed attributes).
93
+ - Manages a `Stages` state machine: `disconnected → connecting → connected → disconnecting → disconnected`.
94
+ - On `connect()`: restores pre-upgrade observable values, calls `connectedCallback` on all `HostBehavior`s, renders the template into the shadow root, and applies styles.
95
+ - On `disconnect()`: calls `disconnectedCallback` on behaviors, unbinds the view.
96
+ - Exposes `addBehavior` / `removeBehavior` for dynamic `HostBehavior` management (used by `ElementStyles`).
97
+
98
+ `FASTElementDefinition` wraps all the metadata for a custom element class: its tag name, template, styles, and observed attribute list. It is created by `FASTElement.compose()` and registered globally via `fastElementRegistry`.
99
+
100
+ ---
101
+
102
+ ### Observables & Notifiers
103
+
104
+ **Files**: `src/observation/observable.ts`, `src/observation/notifier.ts`, `src/observation/arrays.ts`
105
+
106
+ #### Property observability
107
+
108
+ `Observable.defineProperty(target, name)` (or the `@observable` decorator) replaces a plain property with a getter/setter pair via `Reflect.defineProperty`. The setter:
109
+
110
+ 1. Stores the new value in a backing slot.
111
+ 2. Calls `Observable.getNotifier(this).notify(name)` to fan out to subscribers.
112
+
113
+ `Observable.getNotifier(object)` returns the `PropertyChangeNotifier` for an object, creating one on demand. Notifiers are stored in a `WeakMap` so they don't prevent GC.
114
+
115
+ #### SubscriberSet / PropertyChangeNotifier
116
+
117
+ `SubscriberSet` is an optimised set that stores the first two subscribers inline (avoiding heap allocations for the common 1–2 subscriber case) and falls back to an array. `PropertyChangeNotifier` extends `SubscriberSet` to support per-property subscriptions.
118
+
119
+ #### ExpressionNotifier (binding observer)
120
+
121
+ `Observable.binding(expression, subscriber)` creates an `ExpressionNotifier`. When `observe(source, context)` is called it:
122
+
123
+ 1. Pushes itself as the _current watcher_ onto a thread-local stack.
124
+ 2. Evaluates the expression (e.g., `x => x.name`).
125
+ 3. Any `Observable`-tracked property get encountered during evaluation subscribes the notifier to that property's notifier automatically.
126
+ 4. Pops itself. Future changes to any accessed property trigger `handleChange` on the subscriber.
127
+
128
+ This gives FAST automatic, fine-grained dependency tracking without explicit declarations.
129
+
130
+ ---
131
+
132
+ ### Bindings
133
+
134
+ **Files**: `src/binding/binding.ts`, `src/binding/one-way.ts`, `src/binding/one-time.ts`, `src/binding/normalize.ts`
135
+
136
+ `Binding` is an abstract class that pairs an `Expression` (arrow function) with a `DOMPolicy` and a volatility flag. Concrete subclasses implement `createObserver(subscriber, directive)`:
137
+
138
+ | Binding | Observer behaviour |
139
+ |---|---|
140
+ | `oneWay` | Creates an `ExpressionNotifier`; tracks dependencies; re-evaluates on change |
141
+ | `oneTime` | Evaluates once during `bind()`, returns immediately |
142
+ | `listener` | Same as `oneWay` but attaches as a DOM event handler |
143
+
144
+ `normalizeBinding(value)` converts raw arrow functions or static values into a `Binding` object.
145
+
146
+ ---
147
+
148
+ ### html Tagged Template Literal
149
+
150
+ **File**: `src/templating/template.ts`
151
+
152
+ The `html` tag is the primary authoring API:
153
+
154
+ ```typescript
155
+ const template = html<MyElement>`
156
+ <div>${x => x.label}</div>
157
+ <button @click="${x => x.handleClick}">OK</button>
158
+ `;
159
+ ```
160
+
161
+ When the tag function is called it invokes `ViewTemplate.create(strings, values)` (static method) which:
162
+
163
+ 1. Iterates the template string fragments (`strings`) paired with interpolated values.
164
+ 2. For each value:
165
+ - A plain function → wrapped in `HTMLBindingDirective(oneWay(fn))`
166
+ - A `Binding` instance → wrapped in `HTMLBindingDirective(binding)`
167
+ - A registered `HTMLDirective` instance → used directly
168
+ - Anything else → wrapped as a `oneTime` static binding
169
+ 3. Calls `directive.createHTML(add)` which returns a **placeholder string** (a special attribute or marker containing the factory's unique ID).
170
+ 4. Concatenates all static strings and placeholders into a single HTML string.
171
+ 5. Returns a `ViewTemplate(html, factories)` – the factories dictionary maps IDs to `ViewBehaviorFactory` instances.
172
+
173
+ No DOM nodes are created at this point; compilation is deferred.
174
+
175
+ See [ARCHITECTURE_HTML_TAGGED_TEMPLATE_LITERAL.md](./ARCHITECTURE_HTML_TAGGED_TEMPLATE_LITERAL.md) for more detail on directives and the `Markup`/`Parser` helpers.
176
+
177
+ ---
178
+
179
+ ### ViewTemplate & Compiler
180
+
181
+ **Files**: `src/templating/template.ts`, `src/templating/compiler.ts`, `src/templating/markup.ts`
182
+
183
+ `ViewTemplate.compile()` is called lazily the first time the template is rendered. It delegates to `Compiler.compile(html, factories, policy)`:
184
+
185
+ 1. Sets the HTML string as the `innerHTML` of a `<template>` element (letting the browser parse the DOM once).
186
+ 2. Traverses the resulting `DocumentFragment` depth-first.
187
+ 3. For each node, calls `compileAttributes()` which scans attributes for factory placeholder IDs.
188
+ 4. When a placeholder is found, it associates the matching `ViewBehaviorFactory` with the node's structural ID (a dot-separated path like `"r.2.0"` meaning "third child of the root's second child").
189
+ 5. Lazily-resolved descriptors (using `Object.defineProperty` on a prototype) allow `HTMLView` to look up any target node via a chain of `childNodes` accesses without pre-walking the tree for every view instance.
190
+ 6. Returns a `CompilationContext` that implements `HTMLTemplateCompilationResult`.
191
+
192
+ `CompilationContext.createView(hostBindingTarget?)` clones the compiled `DocumentFragment`, instantiates behaviors from factories, and returns an `HTMLView`.
193
+
194
+ ---
195
+
196
+ ### Views & Behaviors
197
+
198
+ **Files**: `src/templating/view.ts`, `src/templating/html-directive.ts`
199
+
200
+ `HTMLView` implements `ElementView` / `SyntheticView`. It:
201
+
202
+ - Holds the cloned `DocumentFragment` nodes.
203
+ - Has a `targets` map (resolved lazily) from structural node IDs to live `Node` references.
204
+ - `bind(source, context)` iterates all `ViewBehavior` instances and calls `behavior.bind(controller)`.
205
+ - `unbind()` calls `behavior.unbind()` on each behavior and clears the source.
206
+ - `appendTo(node)` / `insertBefore(node)` / `remove()` move its DOM nodes in the tree.
207
+
208
+ `ViewBehavior` is the runtime unit of work attached to a specific DOM node. Examples:
209
+
210
+ | Directive | Created `ViewBehavior` | Effect |
211
+ |---|---|---|
212
+ | `HTMLBindingDirective` | `BindingBehavior` | Evaluates the binding; updates the DOM aspect (attribute / property / event / content / tokenList) |
213
+ | `when` | `WhenBehavior` | Conditionally inserts a child view |
214
+ | `repeat` | `RepeatBehavior` | Renders a list of child views |
215
+ | `ref` | `RefDirective` | Writes the element reference onto the source |
216
+ | `children` / `slotted` | `ChildrenDirective` / `SlottedDirective` | Observes DOM mutations |
217
+
218
+ `ViewBehaviorFactory` (created at template-authoring time) is the blueprint; `ViewBehavior` (created per `HTMLView` instance) is the live runtime object.
219
+
220
+ See [src/templating/TEMPLATE-BINDINGS.md](./src/templating/TEMPLATE-BINDINGS.md) for the full binding pipeline including `DOMAspect` routing and two-way binding.
221
+
222
+ ---
223
+
224
+ ### Updates Queue
225
+
226
+ **File**: `src/observation/update-queue.ts`
227
+
228
+ **Exported as**: `Updates`
229
+
230
+ `Updates` is a shared, batched task queue used to synchronise writes to the DOM. It is stored on the `FAST` global (under `KernelServiceId.updateQueue`) so multiple FAST instances on the same page share a single flush cycle.
231
+
232
+ - `Updates.enqueue(callable)` – schedules a task for the next batch.
233
+ - `Updates.process()` – forces immediate synchronous flush (useful in tests).
234
+ - `Updates.next()` – returns a `Promise` that resolves after the next flush.
235
+ - `Updates.setMode(isAsync)` – toggle async (default) vs. synchronous mode.
236
+
237
+ In async mode, the first `enqueue` call schedules a `requestAnimationFrame` callback that drains up to 1024 tasks per frame. Errors in tasks are deferred via `setTimeout` so they don't abort the remaining tasks.
238
+
239
+ Observable setters and `attributeChangedCallback` enqueue their DOM mutations through `Updates`, ensuring that multiple synchronous property changes result in only one DOM update per frame.
240
+
241
+ See [ARCHITECTURE_UPDATES.md](./ARCHITECTURE_UPDATES.md) for more detail.
242
+
243
+ ---
244
+
245
+ ### Styles
246
+
247
+ **Files**: `src/styles/css.ts`, `src/styles/element-styles.ts`, `src/styles/css-directive.ts`
248
+
249
+ The `css` tag (analogous to `html`) builds `ElementStyles` objects. During `ElementController.connect()`, styles are applied to the element's shadow root either via `adoptedStylesheets` (preferred) or an appended `<style>` node, depending on platform support. Styles can also contain dynamic `CSSDirective`s (e.g., CSS custom property bindings) that register as `HostBehavior`s and connect/disconnect alongside the element.
250
+
251
+ ---
252
+
253
+ ### Dependency Injection (DI)
254
+
255
+ **File**: `src/di/di.ts`
256
+
257
+ FAST ships a full hierarchical DI container inspired by Aurelia. Key types:
258
+
259
+ | Type | Role |
260
+ |---|---|
261
+ | `Container` | Resolves dependencies; parent containers are queried if a key is not found locally |
262
+ | `Resolver` | Maps a key to a creation strategy (singleton, transient, callback, …) |
263
+ | `Registration` | Produces a `Resolver` when registered in a container |
264
+ | `Factory` | Constructs instances; supports `Transformer`s for post-construction mutation |
265
+
266
+ Containers are typically attached to DOM elements and walk the DOM hierarchy. DI keys are classes, interfaces, or `Context`-like tokens. Constructor parameters are annotated with the `@inject(key)` decorator (or use `@singleton` / `@transient` to declare the class's own registration).
267
+
268
+ See `docs/di/api-report.api.md` for the full public API surface.
269
+
270
+ ---
271
+
272
+ ### Context Protocol
273
+
274
+ **File**: `src/context.ts`
275
+
276
+ `Context` implements the [W3C Community Context Protocol](https://github.com/webcomponents-cg/community-protocols/blob/main/proposals/context.md). A `FASTContext<T>` object is both a DI key and a decorator:
277
+
278
+ - `Context.create<T>(name, initialValue?)` – creates a named context token.
279
+ - `Context.for<T>(name)` – gets or creates a globally-registered context token.
280
+ - `context.provide(target, value)` – registers a provider on a DOM element.
281
+ - `context.get(target)` – dispatches a `context-request` event and returns the synchronously provided value (or `initialValue`).
282
+ - `context.request(target, callback, multiple?)` – async / multi-provider variant.
283
+ - Used as a `@decorator` on class properties or constructor parameters to declare a context dependency.
284
+
285
+ ---
286
+
287
+ ### State Helpers
288
+
289
+ **Files**: `src/state/state.ts`, `src/state/watch.ts`
290
+
291
+ > **Status**: beta
292
+
293
+ `state<T>(initialValue, options?)` creates a reactive `State<T>` object – a callable that returns the current value. The state's `.current` property is a FAST observable, so templates or `ExpressionNotifier`s that read it will automatically re-evaluate when it changes.
294
+
295
+ `watch(object, subscriber)` deeply subscribes to all observable properties and array mutations on an object graph, returning a `Disposable`.
296
+
297
+ ---
298
+
299
+ ## Data Flow Diagrams
300
+
301
+ ### Module Load & Registration
302
+
303
+ ```mermaid
304
+ flowchart TD
305
+ A([Browser loads script]) --> B[FAST global created on globalThis]
306
+ B --> C[FASTElement subclass executes FASTElement.compose]
307
+ C --> D[Observable decorators register accessors on the prototype]
308
+ C --> E[Attribute decorators push AttributeDefinition to the class]
309
+ C --> F[html tag is evaluated – ViewTemplate created with factories]
310
+ D & E & F --> G[FASTElement.define registers with the Custom Element Registry]
311
+ G --> H[Browser detects element in DOM]
312
+ H --> I([FASTElement lifecycle begins])
313
+ ```
314
+
315
+ ### FASTElement Lifecycle
316
+
317
+ ```mermaid
318
+ flowchart TD
319
+ CTOR[constructor] --> EC[ElementController.forCustomElement creates or locates the controller]
320
+ EC --> ATTACH[Controller captures element + definition, sets $fastController]
321
+
322
+ CONN[connectedCallback] --> STAGE[stage = connecting]
323
+ STAGE --> OBS[Restore pre-upgrade observable values]
324
+ OBS --> BEHAV[Connect HostBehaviors]
325
+ BEHAV --> RENDER[renderTemplate → ViewTemplate.render → HTMLView.appendTo shadow root]
326
+ RENDER --> STYLES[Apply ElementStyles to shadow root]
327
+ STYLES --> DONE[stage = connected]
328
+
329
+ ATTR[attributeChangedCallback] --> ACD[AttributeDefinition.onAttributeChangedCallback]
330
+ ACD --> ENQ[Updates.enqueue – reflect new value via Observable accessor]
331
+
332
+ DISC[disconnectedCallback] --> DBEHAV[Disconnect HostBehaviors]
333
+ DBEHAV --> UNBIND[HTMLView.unbind]
334
+ UNBIND --> DSTAGE[stage = disconnected]
335
+ ```
336
+
337
+ ### Template Pipeline
338
+
339
+ ```mermaid
340
+ flowchart LR
341
+ TAG["html\`...\` tag call"]
342
+ CREATE["ViewTemplate.create() (static)\nBuilds HTML string with\nfactory placeholder IDs\nand factories dictionary"]
343
+ LAZY["First render call\nViewTemplate.create() / render()"]
344
+ COMPILE["ViewTemplate.compile()\n→ Compiler.compile()\nParses <template> innerHTML\nBuilds CompilationContext\nwith node ID descriptors"]
345
+ CLONE["CompilationContext.createView()\nClones DocumentFragment\nInstantiates ViewBehaviors"]
346
+ VIEW["HTMLView\nDOM nodes + behaviors"]
347
+ BIND["HTMLView.bind(source, context)\nEach ViewBehavior.bind(controller)\nEvaluates expressions\nWrites to DOM"]
348
+
349
+ TAG --> CREATE
350
+ CREATE --> LAZY
351
+ LAZY --> COMPILE
352
+ COMPILE --> CLONE
353
+ CLONE --> VIEW
354
+ VIEW --> BIND
355
+ ```
356
+
357
+ ### Observable Change Propagation
358
+
359
+ ```mermaid
360
+ flowchart TD
361
+ SET["element.property = newValue\n(Observable setter)"]
362
+ NOTIFY["PropertyChangeNotifier.notify(propertyName)"]
363
+ SUBS["For each Subscriber in SubscriberSet\nsubscriber.handleChange(subject, propertyName)"]
364
+ ENQ["Updates.enqueue(binding task)"]
365
+ RAF["requestAnimationFrame fires\nUpdates.process()"]
366
+ EVAL["ExpressionNotifier re-evaluates expression"]
367
+ DOM["DOM aspect updated\n(attribute / property / content / event)"]
368
+
369
+ SET --> NOTIFY
370
+ NOTIFY --> SUBS
371
+ SUBS --> ENQ
372
+ ENQ --> RAF
373
+ RAF --> EVAL
374
+ EVAL --> DOM
375
+ ```
376
+
377
+ ---
378
+
379
+ ## How the Pieces Fit Together
380
+
381
+ Below is a conceptual map of the major subsystems and their relationships:
382
+
383
+ ```
384
+ ┌──────────────────────────────────────────────────────────────────────────────┐
385
+ │ FAST Global (globalThis.FAST) │
386
+ │ KernelServiceIds → Updates queue, Observable system, Element registry │
387
+ └────────────────────┬─────────────────────────────────────────────────────────┘
388
+ │ shared kernel slots
389
+ ┌───────────┴───────────┐
390
+ │ │
391
+ ┌────────▼──────────┐ ┌────────▼────────────────────┐
392
+ │ Observable / │ │ Updates queue │
393
+ │ ExpressionNotifier│ │ (rAF-batched task runner) │
394
+ │ SubscriberSet │ └────────────────────────────-─┘
395
+ └────────┬──────────┘ ▲
396
+ │ dependency tracking │ enqueue
397
+ ▼ │
398
+ ┌────────────────────────────────┴──────────────────────────────┐
399
+ │ Binding system │
400
+ │ oneWay / oneTime / listener → Binding → ExpressionObserver │
401
+ └────────────────────────┬──────────────────────────────────────┘
402
+ │ drives
403
+ ┌────────────────────────▼──────────────────────────────────────┐
404
+ │ Templating pipeline │
405
+ │ html tag → ViewTemplate → Compiler → CompilationContext │
406
+ │ createView → HTMLView → ViewBehaviors (bind/update DOM) │
407
+ └────────────────────────┬──────────────────────────────────────┘
408
+ │ owned by
409
+ ┌────────────────────────▼──────────────────────────────────────┐
410
+ │ ElementController │
411
+ │ Lifecycle (connect/disconnect/attr) • Styles • Behaviors │
412
+ └────────────────────────┬──────────────────────────────────────┘
413
+ │ wraps
414
+ ┌────────────────────────▼──────────────────────────────────────┐
415
+ │ FASTElement (HTMLElement subclass) │
416
+ │ + FASTElementDefinition (metadata: name, template, styles) │
417
+ └───────────────────────────────────────────────────────────────┘
418
+ │ optional higher-level services
419
+ ├──────────────────────────────────────────────┐
420
+ ┌────────▼──────────┐ ┌──────────▼──────────┐
421
+ │ DI container │ │ Context protocol │
422
+ │ (di/di.ts) │ │ (context.ts) │
423
+ └───────────────────┘ └─────────────────────┘
424
+ ```
425
+
426
+ **Authoring flow summary**:
427
+
428
+ 1. Developer writes a class extending `FASTElement`, decorates properties with `@observable` / `@attr`, and calls `FASTElement.define({ name, template, styles })`.
429
+ 2. `FASTElement.define` → `FASTElementDefinition.compose(...).define()` registers the element with the Custom Element Registry.
430
+ 3. When the browser upgrades the element, `ElementController.forCustomElement(element)` is called in the constructor.
431
+ 4. On `connectedCallback`, the controller renders the template (`ViewTemplate.render`) into the shadow root. Compilation is lazy: the first render call triggers `Compiler.compile()`, subsequent calls clone the already-compiled `DocumentFragment`.
432
+ 5. `HTMLView.bind(source)` wires up each `ViewBehavior`. `oneWay` bindings create `ExpressionNotifier`s that track observable dependencies automatically.
433
+ 6. When an observed property changes, its notifier fans out to all subscribers. Each binding enqueues a DOM update via `Updates`. The next animation frame drains the queue and applies the mutations.
434
+ 7. On `disconnectedCallback`, `HTMLView.unbind()` tears down all bindings; behaviors disconnect; styles are removed.
435
+
436
+ ---
437
+
438
+ ## Package Layout
439
+
440
+ ```
441
+ src/
442
+ ├── interfaces.ts # Core types: Callable, Constructable, FASTGlobal, Message codes
443
+ ├── platform.ts # FAST global initialisation, KernelServiceId, TypeRegistry
444
+ ├── dom.ts # DOMAspect enum, DOMPolicy, DOMSink
445
+ ├── dom-policy.ts # Default DOM security policy (TrustedTypes integration)
446
+ ├── metadata.ts # Reflect-based metadata helpers
447
+ ├── utilities.ts # UnobservableMutationObserver and other helpers
448
+ ├── debug.ts # Adds human-readable error messages to FAST global
449
+ ├── observation/
450
+ │ ├── observable.ts # Observable, @observable, ExpressionNotifier, ExecutionContext
451
+ │ ├── notifier.ts # Subscriber, Notifier, SubscriberSet, PropertyChangeNotifier
452
+ │ ├── arrays.ts # ArrayObserver, Splice, SpliceStrategy
453
+ │ └── update-queue.ts # Updates (UpdateQueue)
454
+ ├── binding/
455
+ │ ├── binding.ts # Binding abstract base class, BindingDirective
456
+ │ ├── one-way.ts # oneWay, listener
457
+ │ ├── one-time.ts # oneTime
458
+ │ └── normalize.ts # normalizeBinding helper
459
+ ├── templating/
460
+ │ ├── template.ts # ViewTemplate, html tag, InlineTemplateDirective
461
+ │ ├── compiler.ts # Compiler, CompilationContext
462
+ │ ├── view.ts # HTMLView, ElementView, SyntheticView
463
+ │ ├── html-directive.ts # HTMLDirective, ViewBehavior, ViewBehaviorFactory
464
+ │ ├── html-binding-directive.ts # HTMLBindingDirective
465
+ │ ├── markup.ts # Markup placeholders, Parser
466
+ │ ├── when.ts # when directive
467
+ │ ├── repeat.ts # repeat directive
468
+ │ ├── ref.ts # ref directive
469
+ │ ├── render.ts # render directive
470
+ │ ├── children.ts # children directive
471
+ │ ├── slotted.ts # slotted directive
472
+ │ └── TEMPLATE-BINDINGS.md
473
+ ├── styles/
474
+ │ ├── css.ts # css tag
475
+ │ ├── element-styles.ts # ElementStyles
476
+ │ ├── css-directive.ts # CSSDirective, @cssDirective
477
+ │ └── host.ts # HostBehavior, HostController
478
+ ├── components/
479
+ │ ├── fast-element.ts # FASTElement, @customElement
480
+ │ ├── element-controller.ts # ElementController, Stages
481
+ │ ├── fast-definitions.ts # FASTElementDefinition, TemplateOptions
482
+ │ ├── attributes.ts # AttributeDefinition, @attr, converters
483
+ │ └── hydration.ts # SSR hydration helpers
484
+ ├── di/
485
+ │ └── di.ts # DI container, decorators, resolvers, Registration
486
+ ├── context.ts # Context, FASTContext, Context protocol
487
+ ├── state/
488
+ │ ├── state.ts # state() helper (beta)
489
+ │ └── watch.ts # watch() helper (beta)
490
+ └── hydration/
491
+ └── target-builder.ts # Hydration target resolution
492
+ ```
493
+
494
+ ---
495
+
496
+ ## Detailed Architecture Documents
497
+
498
+ | Document | What it covers |
499
+ |---|---|
500
+ | [ARCHITECTURE_INTRO.md](./ARCHITECTURE_INTRO.md) | Glossary / index for all architecture docs |
501
+ | [ARCHITECTURE_OVERVIEW.md](./ARCHITECTURE_OVERVIEW.md) | General FAST usage, compose/define flow, module load sequence |
502
+ | [ARCHITECTURE_FASTELEMENT.md](./ARCHITECTURE_FASTELEMENT.md) | FASTElement & ElementController lifecycle in detail |
503
+ | [ARCHITECTURE_HTML_TAGGED_TEMPLATE_LITERAL.md](./ARCHITECTURE_HTML_TAGGED_TEMPLATE_LITERAL.md) | `html` tag, directives, binding pre-processing |
504
+ | [ARCHITECTURE_UPDATES.md](./ARCHITECTURE_UPDATES.md) | Updates queue, attribute and observable change batching |
505
+ | [src/templating/TEMPLATE-BINDINGS.md](./src/templating/TEMPLATE-BINDINGS.md) | Full template binding pipeline: authoring → compilation → binding → DOM updates |
506
+ | [docs/fast-element-2-changes.md](./docs/fast-element-2-changes.md) | Breaking changes from v1 to v2 |
package/biome.json ADDED
@@ -0,0 +1,4 @@
1
+ {
2
+ "root": false,
3
+ "extends": "//"
4
+ }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "metadata": {
3
3
  "toolPackage": "@microsoft/api-extractor",
4
- "toolVersion": "7.47.0",
4
+ "toolVersion": "7.57.7",
5
5
  "schemaVersion": 1011,
6
6
  "oldestForwardsCompatibleVersion": 1001,
7
7
  "tsdocConfig": {
@@ -114,6 +114,22 @@
114
114
  "tagName": "@virtual",
115
115
  "syntaxKind": "modifier"
116
116
  },
117
+ {
118
+ "tagName": "@jsx",
119
+ "syntaxKind": "block"
120
+ },
121
+ {
122
+ "tagName": "@jsxRuntime",
123
+ "syntaxKind": "block"
124
+ },
125
+ {
126
+ "tagName": "@jsxFrag",
127
+ "syntaxKind": "block"
128
+ },
129
+ {
130
+ "tagName": "@jsxImportSource",
131
+ "syntaxKind": "block"
132
+ },
117
133
  {
118
134
  "tagName": "@betaDocumentation",
119
135
  "syntaxKind": "modifier"
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "metadata": {
3
3
  "toolPackage": "@microsoft/api-extractor",
4
- "toolVersion": "7.47.0",
4
+ "toolVersion": "7.57.7",
5
5
  "schemaVersion": 1011,
6
6
  "oldestForwardsCompatibleVersion": 1001,
7
7
  "tsdocConfig": {
@@ -114,6 +114,22 @@
114
114
  "tagName": "@virtual",
115
115
  "syntaxKind": "modifier"
116
116
  },
117
+ {
118
+ "tagName": "@jsx",
119
+ "syntaxKind": "block"
120
+ },
121
+ {
122
+ "tagName": "@jsxRuntime",
123
+ "syntaxKind": "block"
124
+ },
125
+ {
126
+ "tagName": "@jsxFrag",
127
+ "syntaxKind": "block"
128
+ },
129
+ {
130
+ "tagName": "@jsxImportSource",
131
+ "syntaxKind": "block"
132
+ },
117
133
  {
118
134
  "tagName": "@betaDocumentation",
119
135
  "syntaxKind": "modifier"
@@ -50,7 +50,23 @@ export interface ViewBehaviorBoundaries {
50
50
  */
51
51
  export declare function createRangeForNodes(first: Node, last: Node): Range;
52
52
  /**
53
- * Maps {@link CompiledViewBehaviorFactory} ids to the corresponding node targets for the view.
53
+ * Maps compiled ViewBehaviorFactory IDs to their corresponding DOM nodes in the
54
+ * server-rendered shadow root. Uses a TreeWalker to scan the existing DOM between
55
+ * firstNode and lastNode, parsing hydration markers to build the targets map.
56
+ *
57
+ * For element nodes: parses `data-fe-b` (or variant) attributes to identify which
58
+ * factories target each element, then removes the marker attribute.
59
+ *
60
+ * For comment nodes: parses content binding markers (`fe-b$$start/end$$`) to find
61
+ * the DOM range controlled by each content binding. Single text nodes become the
62
+ * direct target; multi-node ranges are stored in boundaries for structural directives.
63
+ * Element boundary markers (`fe-eb$$start/end$$`) cause the walker to skip over
64
+ * nested custom elements that handle their own hydration.
65
+ *
66
+ * Host bindings (targetNodeId='h') appear at the start of the factories array but
67
+ * have no SSR markers — getHydrationIndexOffset() computes how many to skip so that
68
+ * marker indices align with the correct non-host factories.
69
+ *
54
70
  * @param firstNode - The first node of the view.
55
71
  * @param lastNode - The last node of the view.
56
72
  * @param factories - The Compiled View Behavior Factories that belong to the view.
@@ -46,7 +46,18 @@ export interface HydratableContentTemplate extends ContentTemplate {
46
46
  hydrate(first: Node, last: Node): ContentView;
47
47
  }
48
48
  /**
49
- * A directive that applies bindings.
49
+ * The central binding directive that bridges data expressions and DOM updates.
50
+ *
51
+ * HTMLBindingDirective fulfills three roles simultaneously:
52
+ * - **HTMLDirective**: Produces placeholder HTML via createHTML() during template authoring.
53
+ * - **ViewBehaviorFactory**: Creates behaviors (returns itself) during view creation.
54
+ * - **ViewBehavior / EventListener**: Attaches to a DOM node during bind, manages
55
+ * expression observers for reactive updates, and handles DOM events directly.
56
+ *
57
+ * The aspectType (set by HTMLDirective.assignAspect during template processing)
58
+ * determines which DOM "sink" function is used to apply values — e.g.,
59
+ * setAttribute for attributes, addEventListener for events, textContent for content.
60
+ *
50
61
  * @public
51
62
  */
52
63
  export declare class HTMLBindingDirective implements HTMLDirective, ViewBehaviorFactory, ViewBehavior, Aspected, BindingDirective {
@@ -95,12 +106,36 @@ export declare class HTMLBindingDirective implements HTMLDirective, ViewBehavior
95
106
  * Creates a behavior.
96
107
  */
97
108
  createBehavior(): ViewBehavior;
98
- /** @internal */
109
+ /**
110
+ * Attaches this binding to its target DOM node.
111
+ * - For events: stores the controller reference on the target element and registers
112
+ * this directive as the EventListener via addEventListener. The directive's
113
+ * handleEvent() method will be called when the event fires.
114
+ * - For content bindings: registers an unbind handler, then falls through to the
115
+ * default path.
116
+ * - For all non-event bindings: creates (or reuses) an ExpressionObserver, evaluates
117
+ * the binding expression, and applies the result to the DOM via the updateTarget
118
+ * sink function. The observer will call handleChange() on future data changes.
119
+ * @internal
120
+ */
99
121
  bind(controller: ViewController): void;
100
122
  /** @internal */
101
123
  unbind(controller: ViewController): void;
102
- /** @internal */
124
+ /**
125
+ * Implements the EventListener interface. When a DOM event fires on the target
126
+ * element, this method retrieves the ViewController stored on the element,
127
+ * sets the event on the ExecutionContext so `c.event` is available to the
128
+ * binding expression, and evaluates the expression. If the expression returns
129
+ * anything other than `true`, the event's default action is prevented.
130
+ * @internal
131
+ */
103
132
  handleEvent(event: Event): void;
104
- /** @internal */
133
+ /**
134
+ * Called by the ExpressionObserver when a tracked dependency changes.
135
+ * Re-evaluates the binding expression via observer.bind() and pushes
136
+ * the new value to the DOM through the updateTarget sink function.
137
+ * This is the reactive update path that keeps the DOM in sync with data.
138
+ * @internal
139
+ */
105
140
  handleChange(binding: Expression, observer: ExpressionObserver): void;
106
141
  }