You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/_guide/attrs-2.md
+133-57
Original file line number
Diff line number
Diff line change
@@ -10,86 +10,139 @@ Components may sometimes manage state, or configuration. We encourage the use of
10
10
11
11
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.
12
12
13
-
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:
13
+
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:
14
+
15
+
- 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.
16
+
- 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!
17
+
- 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!
18
+
- 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.
19
+
20
+
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:
21
+
22
+
```ts
23
+
const input =document.createElement('input')
24
+
console.assert(input.type==='text') // default value
25
+
console.assert(input.hasAttribute('type') ===false) // no attribute to override
26
+
input.setAttribute('type', 'number')
27
+
console.assert(input.type==='number') // overrides based on attribute
28
+
input.removeAttribute('type')
29
+
console.assert(input.type==='text') // back to default value
30
+
```
14
31
15
-
- 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`).
16
-
- 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!
17
-
- 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).
18
-
- 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).
32
+
{% capture callout %}
33
+
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:
34
+
{% endcapture %}{% include callout.md %}
19
35
20
-
To use the `@attr` decorator, attach it to a class field, and it will get/set the value of the matching `data-*` attribute.
36
+
<form>
37
+
<label>
38
+
<h4>I want my `@attr` to be named...</h4>
39
+
<input class="js-attr-dasherize-test mb-4">
40
+
</label>
41
+
<divhiddenclass="js-attr-dasherize-bad text-red">
42
+
{{ octx }} An attr name must be two words, so that the HTML version includes a dash!
if (!this.hasAttribute('data-foo')) this.foo='Hello'
104
+
if (!this.hasAttribute('foo-bar')) this.fooBar='Hello'
54
105
}
55
106
56
-
static observedAttributes = ['data-foo']
57
107
}
58
108
```
59
109
60
110
### Attribute Types
61
111
62
-
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.
112
+
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.
63
113
64
114
Below is a handy reference for the small differences, this is all explained in more detail below that.
65
115
66
-
| Type |"Empty" value |When `get` is called | When `set` is called |
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.
124
+
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.
this.setAttribute('foo-bar', 'this value doesnt matter!')
170
+
console.assert(this.fooBar === true)
118
171
}
119
172
}
120
173
```
121
174
122
175
#### Number Attributes
123
176
124
-
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.
177
+
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.
125
178
126
179
<!-- annotations
127
-
attr foo: Maps to get/setAttribute('data-foo')
180
+
attr foo: Maps to get/setAttribute('foo-bar')
128
181
-->
129
182
130
183
```js
131
184
import { controller, attr } from "@github/catalyst"
@@ -149,7 +203,7 @@ class HelloWorldElement extends HTMLElement {
149
203
When an element gets connected to the DOM, the attr is initialized. Duringthis phase Catalyst will determine if the default value should be applied. The default value is defined in the classproperty. The basic rules are as such:
150
204
151
205
- If the classproperty has a value, that is the _default_
152
-
- When connected, if the element _does not_ have a matching attribute, the default _is_ applied.
206
+
- When connected, if the element _does not_ have a matching attribute, the _default is_ applied.
153
207
- 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.
154
208
155
209
{% capture callout %}
@@ -166,9 +220,9 @@ attr name: Maps to get/setAttribute('data-name')
166
220
import { controller, attr } from "@github/catalyst"
167
221
@controller
168
222
class HelloWorldElement extends HTMLElement {
169
-
@attr name='World'
223
+
@attr dataName = 'World'
170
224
connectedCallback() {
171
-
this.textContent=`Hello ${this.name}`
225
+
this.textContent = `Hello ${this.dataName}`
172
226
}
173
227
}
174
228
```
@@ -188,24 +242,45 @@ data-name ".*": Will set the value of `name`
188
242
// This will render `Hello `
189
243
```
190
244
191
-
### What about without Decorators?
245
+
### Advanced usage
192
246
193
-
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.
247
+
#### Determining when an @attr changes value
194
248
195
-
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:
To be notified when an `@attr` changes value, you can use the decorator over
250
+
"setter" method instead, and the method will be called with the new value
251
+
whenever it is re-assigned, either through HTML or JavaScript:
199
252
253
+
```typescript
254
+
import { controller, attr } from "@github/catalyst"
255
+
@controller
200
256
class HelloWorldElement extends HTMLElement {
201
-
foo =1
202
257
203
-
connectedCallback() {
204
-
initializeAttrs(this, ['foo'])
258
+
@attr get dataName() {
259
+
return 'World' // Used to get the intial value
205
260
}
261
+
// Called whenever `name` changes
262
+
set dataName(newValue: string) {
263
+
this.textContent = `Hello ${newValue}`
264
+
}
265
+
}
266
+
```
267
+
268
+
### What about without Decorators?
269
+
270
+
If you're not using decorators, then the `@attr` decorator has an escape hatch: You can define a staticclassfield using the `[attr.static]` computed property, as an array of key names. Like so:
Catalyst strives for convention over code. Here are a few conventions we recommend when writing Catalyst code:
9
+
10
+
### Suffix your controllers consistently, for symmetry
11
+
12
+
Catalyst components can be suffixed with `Element`, `Component` or `Controller`. We think elements should behave as closely to the built-ins as possible, so we like to use `Element` (existing elements do this, for example `HTMLDivElement`, `SVGElement`). If you're using a server side comoponent framework such as [ViewComponent](https://viewcomponent.org/), it's probably better to suffix `Component` for symmetry with that framework.
### The best class-names are two word descriptions
25
+
26
+
Custom elements are required to have a `-` inside the tag name. Catalyst's `@controller` will derive the tag name from the class name - and so as such the class name needs to have at least two capital letters, or to put it another way, it needs to consist of at least two CamelCased words. The element name should describe what it does succinctly in two words. Some examples:
If you're struggling to come up with two words, think about one word being the "what" (what does it do?) and another being the "how" (how does it do it?).
35
+
36
+
### Keep class-names short (but not too short)
37
+
38
+
Brevity is good, element names are likely to be typed out a lot, especially throughout HTML in as tag names, and `data-target`, `data-action` attributes. A good rule of thumb is to try to keep element names down to less than 15 characters (excluding the `Element` suffix), and ideally less than 10. Also, longer words are generally harder to spell, which means mistakes might creep into your code.
39
+
40
+
Be careful not to go too short! We'd recommend avoiding contracting words such as using `Img` to mean `Image`. It can create confusion, especially if there are inconsistencies across your code!
41
+
42
+
### Method names should describe what they do
43
+
44
+
A good method name, much like a good class name, describes what it does, not how it was invoked. While methods can be given most names, you should avoid names that conflict with existing methods on the `HTMLElement` prototype (more on that in [anti-patterns]({{ site.baseurl }}/guide/anti-patterns#avoid-shadowing-method-names)). Names like `onClick` are best avoided, overly generic names like `toggle` should also be avoided. Just like class names it is a good idea to ask "how" and "what", so for example `showAdmins`, `filterUsers`, `updateURL`.
45
+
46
+
### `@target` should use singular naming, while `@targets` should use plural
47
+
48
+
To help differentiate the two `@target`/`@targets` decorators, the properties should be named with respective to their cardinality. That is to say, if you're using an `@target` decorator, then the name should be singular (e.g. `user`, `field`) while the `@targets` decorator should be coupled with plural property names (e.g. `users`, `fields`).
Copy file name to clipboardExpand all lines: docs/_guide/create-ability.md
+1
Original file line number
Diff line number
Diff line change
@@ -3,6 +3,7 @@ version: 2
3
3
chapter: 9
4
4
title: Create Ability
5
5
subtitle: Create your own abilities
6
+
permalink: /guide-v2/create-ability
6
7
---
7
8
8
9
Catalyst provides the functionality to create your own abilities, with a few helper methods and a `controllable` base-level ability. These are explained in detail below, but for a quick summary they are:
Copy file name to clipboardExpand all lines: docs/_guide/lazy-elements-2.md
+2-1
Original file line number
Diff line number
Diff line change
@@ -1,8 +1,9 @@
1
1
---
2
2
version: 2
3
-
chapter: 15
3
+
chapter: 16
4
4
title: Lazy Elements
5
5
subtitle: Dynamically load elements just in time
6
+
permalink: /guide-v2/lazy-elements
6
7
---
7
8
8
9
A common practice in modern web development is to combine all JavaScript code into JS "bundles". By bundling the code together we avoid the network overhead of fetching each file. However the trade-off of bundling is that we might deliver JS code that will never run in the browser.
0 commit comments