From 7f669cde8dc56740b796afe443c018ba812d6210 Mon Sep 17 00:00:00 2001 From: Jane Chu <7559015+janechu@users.noreply.github.com> Date: Thu, 26 Feb 2026 15:30:51 -0800 Subject: [PATCH 1/3] Add doc on reactivity, previously observables and state, and add in content binding docs in the html templates in 2.x docs --- .../src/docs/2.x/advanced/reactivity.md | 224 ++++++++++++++++++ .../2.x/getting-started/html-templates.md | 29 +++ 2 files changed, 253 insertions(+) create mode 100644 sites/website/src/docs/2.x/advanced/reactivity.md diff --git a/sites/website/src/docs/2.x/advanced/reactivity.md b/sites/website/src/docs/2.x/advanced/reactivity.md new file mode 100644 index 00000000000..e57f8fb968f --- /dev/null +++ b/sites/website/src/docs/2.x/advanced/reactivity.md @@ -0,0 +1,224 @@ +--- +id: reactivity +title: Reactivity +layout: 2x +eleventyNavigation: + key: reactivity2x + parent: advanced2x + title: Reactivity +navigationOptions: + activeKey: reactivity2x +description: Advanced observable features including access tracking, observation, arrays, and volatile properties. +keywords: + - observables + - state + - reactivity + - arrays + - volatile +--- + +# Reactivity + +The arrow function bindings and directives used in templates allow the `fast-element` templating engine to intelligently react by only updating the parts of the DOM that actually change, with no need for a virtual DOM, VDOM diffing, or DOM reconciliation algorithms. This approach enables top-tier initial render time, industry-leading incremental DOM updates, and ultra-low memory allocation. + +When a binding is used within a template, the underlying engine uses a technique to capture which properties are accessed in that expression. With the list of properties captured, it then subscribes to changes in their values. Any time a value changes, a task is scheduled on the DOM update queue. When the queue is processed, all updates run as a batch, updating precisely the aspects of the DOM that have changed. + +## Observables + +To enable binding tracking and change notification, properties must be decorated with either `@attr` or `@observable`. Use `@attr` for primitive properties (string, bool, number) that are intended to be surfaced on your element as HTML attributes. Use `@observable` for all other properties. In addition to observing properties, the templating system can also observe arrays. The `repeat` directive is able to efficiently respond to array change records, updating the DOM based on changes in the collection. + +These decorators are a means of meta-programming the properties on your class, such that they include all the implementation needed to support state tracking, observation, and reactivity. You can access any property within your template, but if it hasn't been decorated with one of these two decorators, its value will not update after the initial render. + +:::important +The `@attr` decorator can only be used in a `FASTElement` but the `@observable` decorator can be used in any class. +::: + +:::important +Properties with only a getter, that function as a computed property over other observables, should not be decorated with `@attr` or `@observable`. However, they may need to be decorated with `@volatile`, depending on the internal logic. +::: + +## Observable Features + +### Access tracking + +When `@attr` and `@observable` decorated properties are accessed during template rendering, they are tracked, allowing the engine to deeply understand the relationship between your model and view. These decorators serves to meta-program the property for you, injecting code to enable the observation system. However, if you do not like this approach, for `@observable`, you can always implement notification manually. Here's what that would look like: + +**Example: Manual Observer Implementation** + +```ts +import { Observable } from '@microsoft/fast-element'; + +export class Person { + private _firstName: string; + private _lastName: string; + + get firstName() { + Observable.track(this, 'firstName'); + return this._firstName; + } + + set firstName(value: string) { + this._firstName = value; + Observable.notify(this, 'firstName'); + } + + get lastName() { + Observable.track(this, 'lastName'); + return this._lastName; + } + + set lastName(value: string) { + this._lastName = value; + Observable.notify(this, 'lastName'); + } + + get fullName() { + return `${this.firstName} ${this.lastName}`; + } +} +``` + +Notice that the `fullName` property does not need any special code, since it's computing based on properties that are already observable. There is one special exception to this: if you have a computed property with branching code paths, such as ternary operators, if/else conditions, etc, then you must tell the observation system that your computed property has *volatile* dependencies. In other words, which properties need to be observed may change from invocation to invocation based on which code path executes. + +Here's how you would do that with a decorator: + +```ts +import { observable, volatile } from '@microsoft/fast-element'; + +export class MyClass { + @observable someBoolean = false; + @observable valueA = 0; + @observable valueB = 42; + + @volatile + get computedValue() { + return this.someBoolean ? this.valueA : this.valueB; + } +} +``` + +Here's how you would do it without a decorator: + +```ts +import { Observable, observable } from '@microsoft/fast-element'; + +export class MyClass { + @observable someBoolean = false; + @observable valueA = 0; + @observable valueB = 42; + + get computedValue() { + Observable.trackVolatile(); + return this.someBoolean ? this.valueA : this.valueB; + } +} +``` + +### Internal observation + +On the class where the `@attr` or `@observable` is defined, you can optionally implement a *propertyName*Changed method to easily respond to changes in your own state. + +**Example: Property Change Callbacks** + +```ts +import { observable } from '@microsoft/fast-element'; + +export class Person { + @observable name: string; + + nameChanged(oldValue: string, newValue: string) { + + } +} +``` + +### External observation + +Decorated properties can be subscribed to, to receive notification of changes in the property value. The templating engine uses this, but you can also directly subscribe. Here's how you would subscribe to changes in the `name` property of a `Person` class: + +**Example: Subscribing to an Observable** + +```ts +import { Observable } from '@microsoft/fast-element'; + +const person = new Person(); +const notifier = Observable.getNotifier(person); +const handler = { + handleChange(source: any, propertyName: string) { + // respond to the change here + // source will be the person instance + // propertyName will be "name" + } +}; + +notifier.subscribe(handler, 'firstName') +notifier.unsubscribe(handler, 'lastName'); +``` + +## Observing Arrays + +So far, we've only seen how to observe properties on objects, but it's also possible to observe arrays for changes. Given an instance of an array, it can be observed like this: + +**Example: Observing an Array** + +```ts +const arr = []; +const notifier = Observable.getNotifier(arr); +const handler = { + handleChange(source: any, splices: Splice[]) { + // respond to the change here + // source will be the array instance + // splices will be an array of change records + // describing the mutations in the array in + // terms of splice operations + } +}; + +notifier.subscribe(handler); +``` + +There are a couple of important details to note with array observation: + +* The `fast-element` library's ability to observe arrays is opt-in, in order that the functionality remain tree-shakeable. If you use a `repeat` directive anywhere in your code, you will be automatically opted in. However, if you wish to use the above APIs and are not using `repeat`, you will need to enable array observation by importing and calling the `enableArrayObservation()` function. +* The observation system cannot track changes made directly through an index update. e.g. `arr[3] = 'new value';`. This is due to a limitation in JavaScript. To work around this, update arrays with the equivalent `splice` code e.g. `arr.splice(3, 1, 'new value');` +* If the array is a property of an object, you will often want to observe both the property and the array. Observing the property will allow you to detect when the array instance is completely replaced on the object, while observing the array will allow you to detect changes in the array instance itself. When the property changes, be sure to unsubscribe to the old array and set up a subscription to the new array instance. +* Observing an array only notifies on changes to the array itself. It does not notify on changes to properties on objects held within the array. Separate observers would need to be set up for those individual properties. These could be set up and torn down in response to changes in the array though. + +## Observing Volatile Properties + +In addition to watching properties and arrays, you can also watch volatile properties. + +**Example: Subscribing to a Volatile Property** + +```ts +import { Observable, defaultExecutionContext } from '@microsoft/fast-element'; + +const myObject = new MyClass(); +const handler = { + handleChange(source: any) { + // respond to the change here + // the source is the volatile binding itself + } +}; +const bindingObserver = Observable.binding(myObject.computedValue, handler); +bindingObserver.observe(myObject, defaultExecutionContext); + +// Call this to dismantle the observer +bindingObserver.disconnect(); +``` + +### Records + +To inspect which observable objects and properties were accessed from a `BindingObserver`, you can get the observation records from `BindingObserver.records()` after observing the binding. + +**Example: Getting observation records** +```ts +const binding = (x: MyClass) => x.someBoolean ? x.valueA : x.valueB; +const bindingObserver = Observable.binding(binding); +const value = bindingObserver.observe({}, defaultExecutionContext); + +for (const record of bindingObserver.records()) { + // Do something with the binding's observable dependencies + console.log(record.propertySource, record.propertyName) +} +``` diff --git a/sites/website/src/docs/2.x/getting-started/html-templates.md b/sites/website/src/docs/2.x/getting-started/html-templates.md index 6d6970e3025..95fd01d335b 100644 --- a/sites/website/src/docs/2.x/getting-started/html-templates.md +++ b/sites/website/src/docs/2.x/getting-started/html-templates.md @@ -52,6 +52,35 @@ NameTag.define({ When the greeting attribute is updated, so will the template. +### Content + +To bind the content of an element, simply provide the expression within the start and end tags of the element. It can be the sole content of the element or interwoven with other elements and text. + +**Example: Basic Text Content** + +```html +

${x => x.greeting.toUpperCase()}

+``` + +**Example: Interpolated Text Content** + +```html +

${x => x.greeting}, my name is ${x => x.name}.

+``` + +**Example: Heterogeneous Content** + +```html +

+ ${x => x.greeting}, my name is + ${x => x.name}. +

+``` + +:::note +Dynamic content is set via the `textContent` HTML property for security reasons. You *cannot* set HTML content this way. See the Properties binding section for the explicit, opt-in mechanism for setting HTML via `:innerHTML`. +::: + ### Booleans Boolean bindings use the `?` symbol, use these for Boolean attributes. From 977db5bd5ce66d05e022510318c77909ba9f19ea Mon Sep 17 00:00:00 2001 From: Jane Chu <7559015+janechu@users.noreply.github.com> Date: Fri, 27 Feb 2026 10:29:52 -0800 Subject: [PATCH 2/3] Add host directives documentation --- .../2.x/getting-started/html-directives.md | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/sites/website/src/docs/2.x/getting-started/html-directives.md b/sites/website/src/docs/2.x/getting-started/html-directives.md index 43c6a9ca9f8..5f2e0fdc983 100644 --- a/sites/website/src/docs/2.x/getting-started/html-directives.md +++ b/sites/website/src/docs/2.x/getting-started/html-directives.md @@ -319,3 +319,39 @@ const template = html` ``` In addition to providing a template to render the items with, you can also provide an expression that evaluates to a template. This enables you to dynamically change what you are using to render the items. + +## Host directives + +So far, our bindings and directives have only affected elements within the Shadow DOM of the component. However, sometimes you want to affect the host element itself, based on property state. For example, a progress component might want to write various `aria` attributes to the host, based on the progress state. In order to facilitate scenarios like this, you can use a `template` element as the root of your template, and it will represent the host element. Any attribute or directive you place on the `template` element will be applied to the host itself. + +**Example: Host Directive Template** + +```ts +const template = html` + +`; +``` + +**Example: DOM with Host Directive Output** + +```html + + +``` + +:::tip +Using the `children` directive on the `template` element will provide you with references to all Light DOM child nodes of your custom element, regardless of if or where they are slotted. +::: From 9a0d4c6a2a600ff7f59a0989efd5753b0125caa1 Mon Sep 17 00:00:00 2001 From: Jane Chu <7559015+janechu@users.noreply.github.com> Date: Mon, 16 Mar 2026 15:23:49 -0700 Subject: [PATCH 3/3] Added a note on attribute setting precedence and a link to properties binding --- sites/website/src/docs/2.x/getting-started/html-directives.md | 4 ++++ sites/website/src/docs/2.x/getting-started/html-templates.md | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/sites/website/src/docs/2.x/getting-started/html-directives.md b/sites/website/src/docs/2.x/getting-started/html-directives.md index 5f2e0fdc983..a133271960d 100644 --- a/sites/website/src/docs/2.x/getting-started/html-directives.md +++ b/sites/website/src/docs/2.x/getting-started/html-directives.md @@ -355,3 +355,7 @@ const template = html` :::tip Using the `children` directive on the `template` element will provide you with references to all Light DOM child nodes of your custom element, regardless of if or where they are slotted. ::: + +:::note +If the same attributes are defined by the host directive and the user (in the above example role="progressbar"), then the attribute set by the user will take precedence. +::: diff --git a/sites/website/src/docs/2.x/getting-started/html-templates.md b/sites/website/src/docs/2.x/getting-started/html-templates.md index 95fd01d335b..aeb54a3a5da 100644 --- a/sites/website/src/docs/2.x/getting-started/html-templates.md +++ b/sites/website/src/docs/2.x/getting-started/html-templates.md @@ -78,7 +78,7 @@ To bind the content of an element, simply provide the expression within the star ``` :::note -Dynamic content is set via the `textContent` HTML property for security reasons. You *cannot* set HTML content this way. See the Properties binding section for the explicit, opt-in mechanism for setting HTML via `:innerHTML`. +Dynamic content is set via the `textContent` HTML property for security reasons. You *cannot* set HTML content this way. See the [Properties binding](#properties) section for the explicit, opt-in mechanism for setting HTML via `:innerHTML`. ::: ### Booleans