Skip to content

Commit 3f4dad6

Browse files
committed
add new attr docs
1 parent b1bc50e commit 3f4dad6

1 file changed

Lines changed: 132 additions & 57 deletions

File tree

docs/_guide/attrs.md

Lines changed: 132 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -7,86 +7,139 @@ Components may sometimes manage state, or configuration. We encourage the use of
77

88
As Catalyst elements are really just Web Components, they have the `hasAttribute`, `getAttribute`, `setAttribute`, `toggleAttribute`, and `removeAttribute` set of methods available, as well as [`dataset`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLOrForeignElement/dataset), but these can be a little tedious to use; requiring null checking code with each call.
99

10-
Catalyst includes the `@attr` decorator, which provides nice syntax sugar to simplify, standardise, and encourage use of attributes. `@attr` has the following benefits over the basic `*Attribute` methods:
10+
Catalyst includes the `@attr` decorator which provides nice syntax sugar to simplify, standardise, and encourage use of attributes. `@attr` has the following benefits over the basic `*Attribute` methods:
11+
12+
- It dasherizes a property name, making it safe for HTML serialization without conflicting with [built-in global attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes). This works the same as the class name, so for example `@attr pathName` will be `path-name` in HTML, `@attr srcURL` will be `src-url` in HTML.
13+
- An `@attr` property automatically casts based on the initial value - if the initial value is a `string`, `boolean`, or `number` - it will never be `null` or `undefined`. No more null checking!
14+
- It is automatically synced with the HTML attribute. This means setting the class property will update the HTML attribute, and setting the HTML attribute will update the class property!
15+
- Assigning a value in the class description will make that value the _default_ value so if the HTML attribute isn't set, or is set but later removed the _default_ value will apply.
16+
17+
This behaves similarly to existing HTML elements where the class field is synced with the html attribute, for example the `<input>` element's `type` field:
18+
19+
```ts
20+
const input = document.createElement('input')
21+
console.assert(input.type === 'text') // default value
22+
console.assert(input.hasAttribute('type') === false) // no attribute to override
23+
input.setAttribute('type', 'number')
24+
console.assert(input.type === 'number') // overrides based on attribute
25+
input.removeAttribute('type')
26+
console.assert(input.type === 'text') // back to default value
27+
```
1128

12-
- It maps whatever the property name is to `data-*`, [similar to how `dataset` does](https://developer.mozilla.org/en-US/docs/Web/API/HTMLOrForeignElement/dataset#name_conversion), but with more intuitive naming (e.g. `URL` maps to `data-url` not `data--u-r-l`).
13-
- An `@attr` property is limited to `string`, `boolean`, or `number`, it will never be `null` or `undefined` - instead it has an "empty" value. No more null checking!
14-
- The attribute name is automatically [observed, meaning `attributeChangedCallback` will fire when it changes](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements#using_the_lifecycle_callbacks).
15-
- Assigning a value in the class description will make that value the _default_ value, so when the element is connected that value is set (unless the element has the attribute defined already).
29+
{% capture callout %}
30+
An important part of `@attr`s is that they _must_ comprise of two words, so that they get a dash when serialised to HTML. This is intentional, to avoid conflicting with [built-in global attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes). To see how JavaScript property names convert to HTML dasherized names, try typing the name of an `@attr` below:
31+
{% endcapture %}{% include callout.md %}
1632

17-
To use the `@attr` decorator, attach it to a class field, and it will get/set the value of the matching `data-*` attribute.
33+
<form>
34+
<label>
35+
<h4>I want my `@attr` to be named...</h4>
36+
<input class="js-attr-dasherize-test mb-4">
37+
</label>
38+
<div hidden class="js-attr-dasherize-bad text-red">
39+
{{ octx }} An attr name must be two words, so that the HTML version includes a dash!
40+
</div>
41+
<div hidden class="js-attr-dasherize-good text-green">
42+
{{ octick }} This will be <code></code> in HTML.
43+
</div>
44+
<script type="module">
45+
import {mustDasherize} from 'https://unpkg.com/@github/catalyst/lib/index.js'
46+
document.querySelector('.js-attr-dasherize-test').addEventListener('input', () => {
47+
let name = event.target.value
48+
const goodEl = document.querySelector('.js-attr-dasherize-good')
49+
const badEl = document.querySelector('.js-attr-dasherize-bad')
50+
if (name === '') {
51+
goodEl.hidden = true
52+
badEl.hidden = true
53+
return
54+
}
55+
let pass = true
56+
try {
57+
name = mustDasherize(name)
58+
} catch (e) {
59+
pass = false
60+
}
61+
goodEl.querySelector('code').textContent = name
62+
goodEl.hidden = !pass
63+
badEl.hidden = pass
64+
})
65+
</script>
66+
</form>
67+
68+
To use the `@attr` decorator, attach it to a class field, and it will get/set the value of the matching dasherized HTML attribute.
1869

1970
### Example
2071

2172
<!-- annotations
22-
attr foo: Maps to get/setAttribute('datafoo')
73+
attr fooBar: Maps to get/setAttribute('foo-bar')
2374
-->
2475

2576
```js
2677
import { controller, attr } from "@github/catalyst"
2778

2879
@controller
2980
class HelloWorldElement extends HTMLElement {
30-
@attr foo = 'hello'
81+
@attr fooBar = 'hello'
3182
}
3283
```
3384

34-
This is the equivalent to:
85+
This is somewhat equivalent to:
3586

3687
```js
3788
import { controller } from "@github/catalyst"
3889

3990
@controller
4091
class HelloWorldElement extends HTMLElement {
41-
get foo(): string {
42-
return this.getAttribute('data-foo') || ''
92+
get fooBar(): string {
93+
return this.getAttribute('foo-bar') || ''
4394
}
4495

45-
set foo(value: string): void {
46-
return this.setAttribute('data-foo', value)
96+
set fooBar(value: string): void {
97+
return this.setAttribute('foo-bar', value)
4798
}
4899

49100
connectedCallback() {
50-
if (!this.hasAttribute('data-foo')) this.foo = 'Hello'
101+
if (!this.hasAttribute('foo-bar')) this.fooBar = 'Hello'
51102
}
52103

53-
static observedAttributes = ['data-foo']
54104
}
55105
```
56106

57107
### Attribute Types
58108

59-
The _type_ of an attribute is automatically inferred based on the type it is first set to. This means once a value is set it cannot change type; if it is set a `string` it will never be anything but a `string`. An attribute can only be one of either a `string`, `number`, or `boolean`. The types have small differences in how they behave in the DOM.
109+
The _type_ of an attribute is automatically inferred based on the type it is first set to. This means once a value is initially set it cannot change type; if it is set a `string` it will never be anything but a `string`. An attribute can only be one of either a `string`, `number`, or `boolean`. The types have small differences in how they behave in the DOM.
60110

61111
Below is a handy reference for the small differences, this is all explained in more detail below that.
62112

63-
| Type | "Empty" value | When `get` is called | When `set` is called |
64-
|:----------|:--------------|----------------------|:---------------------|
65-
| `string` | `''` | `getAttribute` | `setAttribute` |
66-
| `number` | `0` | `getAttribute` | `setAttribute` |
67-
| `boolean` | `false` | `hasAttribute` | `toggleAttribute` |
113+
| Type | When `get` is called | When `set` is called |
114+
|:----------|----------------------|:---------------------|
115+
| `string` | `getAttribute` | `setAttribute` |
116+
| `number` | `getAttribute` | `setAttribute` |
117+
| `boolean` | `hasAttribute` | `toggleAttribute` |
68118

69119
#### String Attributes
70120

71-
If an attribute is first set to a `string`, then it can only ever be a `string` during the lifetime of an element. The property will return an empty string (`''`) if the attribute doesn't exist, and trying to set it to something that isn't a string will turn it into one before assignment.
121+
If an attribute is first set to a `string`, then it can only ever be a `string` during the lifetime of an element. The property will revert to the initial value if the attribute doesn't exist, and trying to set it to something that isn't a string will turn it into one before assignment.
72122

73123
<!-- annotations
74-
attr foo: Maps to get/setAttribute('data-foo')
124+
attr foo: Maps to get/setAttribute('foo-bar')
75125
-->
76126

77127
```js
78128
import { controller, attr } from "@github/catalyst"
79129

80130
@controller
81131
class HelloWorldElement extends HTMLElement {
82-
@attr foo = 'Hello'
132+
@attr fooBar = 'Hello'
83133

84134
connectedCallback() {
85-
console.assert(this.foo === 'Hello')
86-
this.foo = null // TypeScript won't like this!
87-
console.assert(this.foo === 'null')
88-
delete this.dataset.foo // Removes the attribute
89-
console.assert(this.foo === '') // If the attribute doesn't exist, its an empty string!
135+
console.assert(this.fooBar === 'Hello')
136+
this.fooBar = 'Goodbye'
137+
console.assert(this.fooBar === 'Goodbye'')
138+
console.assert(this.getAttribute('foo-bar') === 'Goodbye')
139+
140+
this.removeAttribute('foo-bar')
141+
// If the attribute doesn't exist, it'll output the initial value!
142+
console.assert(this.fooBar === 'Hello')
90143
}
91144
}
92145
```
@@ -104,39 +157,40 @@ import { controller, attr } from "@github/catalyst"
104157
105158
@controller
106159
class HelloWorldElement extends HTMLElement {
107-
@attr foo = false
160+
@attr fooBar = false
108161
109162
connectedCallback() {
110-
console.assert(this.hasAttribute('data-foo') === false)
111-
this.foo = true
112-
console.assert(this.hasAttribute('data-foo') === true)
113-
this.setAttribute('data-foo', 'this value doesnt matter!')
114-
console.assert(this.foo === true)
163+
console.assert(this.hasAttribute('foo-bar') === false)
164+
this.fooBar = true
165+
console.assert(this.hasAttribute('foo-bar') === true)
166+
this.setAttribute('foo-bar', 'this value doesnt matter!')
167+
console.assert(this.fooBar === true)
115168
}
116169
}
117170
```
118171

119172
#### Number Attributes
120173

121-
If an attribute is first set to a number, then it can only ever be a number during the lifetime of an element. This is sort of like the [`maxlength` attribute on inputs](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/maxlength). The property will return `0` if the attribute doesn't exist, and will be coerced to `Number` if it does - this means it is _possible_ to get back `NaN`. Negative numbers and floats are also valid.
174+
If an attribute is first set to a number, then it can only ever be a number during the lifetime of an element. This is sort of like the [`maxlength` attribute on inputs](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/maxlength). The property will return the initial value if the attribute doesn't exist, and will be coerced to `Number` if it does - this means it is _possible_ to get back `NaN`. Negative numbers and floats are also valid.
122175

123176
<!-- annotations
124-
attr foo: Maps to get/setAttribute('data-foo')
177+
attr foo: Maps to get/setAttribute('foo-bar')
125178
-->
126179

127180
```js
128181
import { controller, attr } from "@github/catalyst"
129182
130183
@controller
131184
class HelloWorldElement extends HTMLElement {
132-
@attr foo = 1
185+
@attr fooBar = 1
133186
134187
connectedCallback() {
135-
console.assert(this.getAttribute('data-foo') === '1')
136-
this.setAttribute('data-foo', 'not a number')
137-
console.assert(Number.isNaN(this.foo))
138-
this.foo = -3.14
139-
console.assert(this.getAttribute('data-foo') === '-3.14')
188+
this.fooBar = 2
189+
console.assert(this.getAttribute('foo-bar') === '2')
190+
this.setAttribute('foo-bar', 'not a number')
191+
console.assert(Number.isNaN(this.fooBar))
192+
this.fooBar = -3.14
193+
console.assert(this.getAttribute('foo-bar') === '-3.14')
140194
}
141195
}
142196
```
@@ -146,7 +200,7 @@ class HelloWorldElement extends HTMLElement {
146200
When an element gets connected to the DOM, the attr is initialized. During this phase Catalyst will determine if the default value should be applied. The default value is defined in the class property. The basic rules are as such:
147201

148202
- If the class property has a value, that is the _default_
149-
- When connected, if the element _does not_ have a matching attribute, the default _is_ applied.
203+
- When connected, if the element _does not_ have a matching attribute, the _default is_ applied.
150204
- When connected, if the element _does_ have a matching attribute, the default _is not_ applied, the property will be assigned to the value of the attribute instead.
151205

152206
{% capture callout %}
@@ -163,9 +217,9 @@ attr name: Maps to get/setAttribute('data-name')
163217
import { controller, attr } from "@github/catalyst"
164218
@controller
165219
class HelloWorldElement extends HTMLElement {
166-
@attr name = 'World'
220+
@attr dataName = 'World'
167221
connectedCallback() {
168-
this.textContent = `Hello ${this.name}`
222+
this.textContent = `Hello ${this.dataName}`
169223
}
170224
}
171225
```
@@ -185,24 +239,45 @@ data-name ".*": Will set the value of `name`
185239
// This will render `Hello `
186240
```
187241
188-
### What about without Decorators?
242+
### Advanced usage
189243
190-
If you're not using decorators, then you won't be able to use the `@attr` decorator, but there is still a way to achieve the same result. Under the hood `@attr` simply tags a field, but `initializeAttrs` and `defineObservedAttributes` do all of the logic.
244+
#### Determining when an @attr changes value
191245
192-
Calling `initializeAttrs` in your connected callback, with the list of properties you'd like to initialize, and calling `defineObservedAttributes` with the class, can achieve the same result as `@attr`. The class fields can still be defined in your class, and they'll be overridden as described above. For example:
193-
194-
```js
195-
import {initializeAttrs, defineObservedAttributes} from '@github/catalyst'
246+
To be notified when an `@attr` changes value, you can use the decorator over
247+
"setter" method instead, and the method will be called with the new value
248+
whenever it is re-assigned, either through HTML or JavaScript:
196249
250+
```typescript
251+
import { controller, attr } from "@github/catalyst"
252+
@controller
197253
class HelloWorldElement extends HTMLElement {
198-
foo = 1
199254
200-
connectedCallback() {
201-
initializeAttrs(this, ['foo'])
255+
@attr get dataName() {
256+
return 'World' // Used to get the intial value
202257
}
258+
// Called whenever `name` changes
259+
@attr set dataName(newValue: string) {
260+
this.textContent = `Hello ${newValue}`
261+
}
262+
}
263+
```
264+
265+
### What about without Decorators?
266+
267+
If you're not using decorators, then the `@attr` decorator has an escape hatch: You can define a static class field using the `[attr.static]` computed property, as an array of key names. Like so:
268+
269+
```js
270+
import {controller, attr} from '@github/catalyst'
271+
272+
controller(
273+
class HelloWorldElement extends HTMLElement {
274+
// Same as @attr fooBar
275+
[attr.static] = ['fooBar']
203276
277+
// Field can still be defined
278+
fooBar = 1
204279
}
205-
defineObservedAttributes(HelloWorldElement, ['foo'])
280+
)
206281
```
207282

208283
This example is functionally identical to:
@@ -212,6 +287,6 @@ import {controller, attr} from '@github/catalyst'
212287
213288
@controller
214289
class HelloWorldElement extends HTMLElement {
215-
@attr foo = 1
290+
@attr fooBar = 1
216291
}
217292
```

0 commit comments

Comments
 (0)