Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add docs for useDefault #1396

Open
wants to merge 11 commits into
base: main
Choose a base branch
from
Original file line number Diff line number Diff line change
@@ -1,24 +1,44 @@
import {LitElement, html, css} from 'lit';
import {LitElement, html, css, PropertyDeclaration} from 'lit';
import {customElement, property} from 'lit/decorators.js';

@customElement('my-element')
class MyElement extends LitElement {
@property({type: Boolean, reflect: true})
active: boolean = false;

/* playground-fold */
static styles = css`
:host {
display: inline-block;
display: inline-block;
padding: 4px;
}

:host([active]) {
border: 1px solid red;
font-weight: 800;
}
:host([variant]) {
outline: 4px solid green;
}
:host([variant="special"]) {
border-radius: 8px; border: 4px solid red;
}`;
/* playground-fold-end */
@property({type: Boolean, reflect: true})
active: boolean = false;

@property({reflect: true, useDefault: true} as PropertyDeclaration)
variant = 'normal';

render() {
return html`
<span>Active: ${this.active}</span>
<button @click="${() => this.active = !this.active}">Toggle active</button>
<div><label>active: <input type="checkbox"
.value="${this.active}"
@change="${(e: {target: HTMLInputElement}) =>
this.active = e.target.checked}">
${this.active}
</label></div>
<div><label>variant: <input type="checkbox"
.value="${this.variant === 'special'}"
@change="${(e: {target: HTMLInputElement}) =>
this.variant = e.target.checked ? 'special' : 'normal'}">
${this.variant}
</label></div>
`;
}
}
40 changes: 34 additions & 6 deletions packages/lit-dev-content/site/docs/v3/components/properties.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,9 @@ class MyElement extends LitElement {
In **JavaScript**, you **must not use class fields** when declaring reactive properties. Instead, properties must be initialized in the element constructor:
```js
class MyElement extends LitElement {
static properties = {foo: {type: String}}
static properties = {
foo: {type: String}
}
constructor() {
super();
this.foo = 'Default';
Expand Down Expand Up @@ -269,6 +271,17 @@ When converting a string-valued attribute into a property, Lit's default attribu

When using TypeScript, this field should generally match the TypeScript type declared for the field. However, the `type` option is used by the Lit's _runtime_ for string serialization/deserialization, and should not be confused with a _type-checking_ mechanism.

</dd>
<dt id="use-default">

`useDefault`

</dt>
<dd>

Set to true to prevent initial attribute reflection for the default value when `reflect` is set to true, and to reset the property to its default value when its corresponding attribute is removed. For more information, see [Enabling attribute reflection](#reflected-attributes).
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we want a specific note here that the initial value is used as the default, and that it's retained in memory?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added



</dd>

Omitting the options object or specifying an empty options object is equivalent to specifying the default value for all options.
Expand Down Expand Up @@ -551,29 +564,44 @@ If this behavior doesn't fit your use case, there are a couple of options:

### Enabling attribute reflection {#reflected-attributes}

You can configure a property so that whenever it changes, its value is reflected to its [corresponding attribute](#observed-attributes). Reflected attributes are useful because attributes are visible to CSS, and to DOM APIs like `querySelector`.
Setting `reflect` to true configures a property so that whenever it changes, its value is reflected to its [corresponding attribute](#observed-attributes). Reflected attributes are useful for serializing element state and because they are visible to CSS and DOM APIs like `querySelector`.

Setting `useDefault` to true prevents the property's default value from initially reflecting to its [corresponding attribute](#observed-attributes). All subsequent changes are reflected; and if the attribute is removed, the property is reset to its default value.

This matches web platform behavior for attributes like `id`. The default value of an element's `id` property is `''` (an empty string) and initially it does not have an `id` attribute, but if the `id` property is set (even to an empty string), the appropirate `id` attribute is reflected. If the `id` attribute is removed, the element's `id` property is set back to its initial value of `''`.

For example:

```js
// Value of property "active" will reflect to attribute "active"
active: {reflect: true}
// Value of property "variant" will reflect except that the "variant"
// attribute will not be iniitally set to the property's default value.
variant: {reflect: true, useDefault: true}
```

When the property changes, Lit sets the corresponding attribute value as described in [Using the default converter](#conversion-type) or [Providing a custom converter](#conversion-converter).

{% playground-example "properties/attributereflect" "my-element.ts" %}

Attributes should generally be considered input to the element from its owner, rather than under control of the element itself, so reflecting properties to attributes should be done sparingly. It's necessary today for cases like styling and accessibility, but this is likely to change as the platform adds features like the [`:state` pseudo selector](https://wicg.github.io/custom-state-pseudo-class/) and the [Accessibility Object Model](https://wicg.github.io/aom/spec/), which fill these gaps.

Reflecting properties of type object or array is not recommended. This can cause large objects to serialize to the DOM which can result in poor performance.

<div class="alert alert-info">

**Lit tracks reflection state during updates.** You may have realized that if property changes are reflected to an attribute and attribute changes update the property, it has the potential to create an infinite loop. However, Lit tracks when properties and attributes are set specifically to prevent this from happening

</div>

### Best practices when reflecting attributes

To ensure elements behave as expected and perform well, try to follow these best practices when reflecting attributes:

* Attributes should generally be considered input to the element from its owner, rather than under control of the element itself, so reflecting properties to attributes should be done sparingly. Consider instead using the [`:state` pseudo selector](https://wicg.github.io/custom-state-pseudo-class/) and the [Accessibility Object Model](https://wicg.github.io/aom/spec/) where possible.

* Reflecting properties should typically also set `useDefault: true` since this keeps the element from spontaneously spawning attributes that the user didn't set, and helps match expected platform behavior.

* Reflecting properties of type object or array is not recommended. This can cause large objects to serialize to the DOM which can result in poor performance and consume excess memory when `useDefault` is used.

* The property decorator does not alter any values assigned to the reactive property, which is considered a best practice for custom accessors. Sometimes native elements restrict properties to certain valid values, for instance, and if an invalid value is assigned to a property, the property will be set to a default instead. `useDefault: true` does not do this - it only restores the default when the attribute is removed. If you'd like to alter the property value on property assignments, define and decorate a custom property setter.

## Custom property accessors {#accessors}

By default, LitElement generates a getter/setter pair for all reactive properties. The setter is invoked whenever you set the property:
Expand Down
Loading