diff --git a/docs/_guide/anti-patterns-2.md b/docs/_guide/anti-patterns-2.md index f574c425..84ad3b1b 100644 --- a/docs/_guide/anti-patterns-2.md +++ b/docs/_guide/anti-patterns-2.md @@ -1,6 +1,6 @@ --- version: 2 -chapter: 13 +chapter: 15 title: Anti Patterns subtitle: Things to avoid building components permalink: /guide-v2/anti-patterns diff --git a/docs/_guide/attrs-2.md b/docs/_guide/attrs-2.md index f5384041..d1c76709 100644 --- a/docs/_guide/attrs-2.md +++ b/docs/_guide/attrs-2.md @@ -10,19 +10,70 @@ Components may sometimes manage state, or configuration. We encourage the use of 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. -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: +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: + + - 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. + - 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! + - 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! + - 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. + +This behaves similarly to existing HTML elements where the class field is synced with the html attribute, for example the `` element's `type` field: + +```ts +const input = document.createElement('input') +console.assert(input.type === 'text') // default value +console.assert(input.hasAttribute('type') === false) // no attribute to override +input.setAttribute('type', 'number') +console.assert(input.type === 'number') // overrides based on attribute +input.removeAttribute('type') +console.assert(input.type === 'text') // back to default value +``` - - 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`). - - 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! - - 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). - - 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). +{% capture callout %} +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: +{% endcapture %}{% include callout.md %} -To use the `@attr` decorator, attach it to a class field, and it will get/set the value of the matching `data-*` attribute. +
+ +To use the `@attr` decorator, attach it to a class field, and it will get/set the value of the matching dasherized HTML attribute. ### Example ```js @@ -30,51 +81,50 @@ import { controller, attr } from "@github/catalyst" @controller class HelloWorldElement extends HTMLElement { - @attr foo = 'hello' + @attr fooBar = 'hello' } ``` -This is the equivalent to: +This is somewhat equivalent to: ```js import { controller } from "@github/catalyst" @controller class HelloWorldElement extends HTMLElement { - get foo(): string { - return this.getAttribute('data-foo') || '' + get fooBar(): string { + return this.getAttribute('foo-bar') || '' } - set foo(value: string): void { - return this.setAttribute('data-foo', value) + set fooBar(value: string): void { + return this.setAttribute('foo-bar', value) } connectedCallback() { - if (!this.hasAttribute('data-foo')) this.foo = 'Hello' + if (!this.hasAttribute('foo-bar')) this.fooBar = 'Hello' } - static observedAttributes = ['data-foo'] } ``` ### Attribute Types -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. +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. Below is a handy reference for the small differences, this is all explained in more detail below that. -| Type | "Empty" value | When `get` is called | When `set` is called | -|:----------|:--------------|----------------------|:---------------------| -| `string` | `''` | `getAttribute` | `setAttribute` | -| `number` | `0` | `getAttribute` | `setAttribute` | -| `boolean` | `false` | `hasAttribute` | `toggleAttribute` | +| Type | When `get` is called | When `set` is called | +|:----------|----------------------|:---------------------| +| `string` | `getAttribute` | `setAttribute` | +| `number` | `getAttribute` | `setAttribute` | +| `boolean` | `hasAttribute` | `toggleAttribute` | #### String Attributes -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. +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. ```js @@ -82,14 +132,17 @@ import { controller, attr } from "@github/catalyst" @controller class HelloWorldElement extends HTMLElement { - @attr foo = 'Hello' + @attr fooBar = 'Hello' connectedCallback() { - console.assert(this.foo === 'Hello') - this.foo = null // TypeScript won't like this! - console.assert(this.foo === 'null') - delete this.dataset.foo // Removes the attribute - console.assert(this.foo === '') // If the attribute doesn't exist, its an empty string! + console.assert(this.fooBar === 'Hello') + this.fooBar = 'Goodbye' + console.assert(this.fooBar === 'Goodbye'') + console.assert(this.getAttribute('foo-bar') === 'Goodbye') + + this.removeAttribute('foo-bar') + // If the attribute doesn't exist, it'll output the initial value! + console.assert(this.fooBar === 'Hello') } } ``` @@ -107,24 +160,24 @@ import { controller, attr } from "@github/catalyst" @controller class HelloWorldElement extends HTMLElement { - @attr foo = false + @attr fooBar = false connectedCallback() { - console.assert(this.hasAttribute('data-foo') === false) - this.foo = true - console.assert(this.hasAttribute('data-foo') === true) - this.setAttribute('data-foo', 'this value doesnt matter!') - console.assert(this.foo === true) + console.assert(this.hasAttribute('foo-bar') === false) + this.fooBar = true + console.assert(this.hasAttribute('foo-bar') === true) + this.setAttribute('foo-bar', 'this value doesnt matter!') + console.assert(this.fooBar === true) } } ``` #### Number Attributes -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. +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. ```js @@ -132,14 +185,15 @@ import { controller, attr } from "@github/catalyst" @controller class HelloWorldElement extends HTMLElement { - @attr foo = 1 + @attr fooBar = 1 connectedCallback() { - console.assert(this.getAttribute('data-foo') === '1') - this.setAttribute('data-foo', 'not a number') - console.assert(Number.isNaN(this.foo)) - this.foo = -3.14 - console.assert(this.getAttribute('data-foo') === '-3.14') + this.fooBar = 2 + console.assert(this.getAttribute('foo-bar') === '2') + this.setAttribute('foo-bar', 'not a number') + console.assert(Number.isNaN(this.fooBar)) + this.fooBar = -3.14 + console.assert(this.getAttribute('foo-bar') === '-3.14') } } ``` @@ -149,7 +203,7 @@ class HelloWorldElement extends HTMLElement { 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: - If the class property has a value, that is the _default_ - - When connected, if the element _does not_ have a matching attribute, the default _is_ applied. + - When connected, if the element _does not_ have a matching attribute, the _default is_ applied. - 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. {% capture callout %} @@ -166,9 +220,9 @@ attr name: Maps to get/setAttribute('data-name') import { controller, attr } from "@github/catalyst" @controller class HelloWorldElement extends HTMLElement { - @attr name = 'World' + @attr dataName = 'World' connectedCallback() { - this.textContent = `Hello ${this.name}` + this.textContent = `Hello ${this.dataName}` } } ``` @@ -188,24 +242,45 @@ data-name ".*": Will set the value of `name` // This will render `Hello ` ``` -### What about without Decorators? +### Advanced usage -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. +#### Determining when an @attr changes value -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: - -```js -import {initializeAttrs, defineObservedAttributes} from '@github/catalyst' +To be notified when an `@attr` changes value, you can use the decorator over +"setter" method instead, and the method will be called with the new value +whenever it is re-assigned, either through HTML or JavaScript: +```typescript +import { controller, attr } from "@github/catalyst" +@controller class HelloWorldElement extends HTMLElement { - foo = 1 - connectedCallback() { - initializeAttrs(this, ['foo']) + @attr get dataName() { + return 'World' // Used to get the intial value } + // Called whenever `name` changes + set dataName(newValue: string) { + this.textContent = `Hello ${newValue}` + } +} +``` + +### What about without Decorators? + +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: + +```js +import {controller, attr} from '@github/catalyst' +controller( +class HelloWorldElement extends HTMLElement { + // Same as @attr fooBar + [attr.static] = ['fooBar'] + + // Field can still be defined + fooBar = 1 } -defineObservedAttributes(HelloWorldElement, ['foo']) +) ``` This example is functionally identical to: @@ -215,6 +290,7 @@ import {controller, attr} from '@github/catalyst' @controller class HelloWorldElement extends HTMLElement { - @attr foo = 1 + @attr fooBar = 1 } ``` + diff --git a/docs/_guide/conventions-2.md b/docs/_guide/conventions-2.md new file mode 100644 index 00000000..3ad6b25b --- /dev/null +++ b/docs/_guide/conventions-2.md @@ -0,0 +1,49 @@ +--- +version: 2 +chapter: 13 +title: Conventions +subtitle: Common naming and patterns +--- + +Catalyst strives for convention over code. Here are a few conventions we recommend when writing Catalyst code: + +### Suffix your controllers consistently, for symmetry + +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. + +```typescript +@controller +class UserListElement extends HTMLElement {} // `Hello World
@@ -44,12 +44,34 @@ class HelloWorldElement extends HTMLElement { } ``` -Providing the `` element as a direct child of the `hello-world` element tells Catalyst to render the templates contents automatically, and so all `HelloWorldElements` with this template will be rendered with the contents. - {% capture callout %} -Remember that _all_ instances of your controller _must_ add the `` HTML. If an instance does not have the `` as a direct child, then the shadow DOM won't be rendered for it! +Remember that _all_ instances of your controller _must_ add the `` HTML. If an instance does not have the `` as a direct child, then the shadow DOM won't be rendered for it! {% endcapture %}{% include callout.md %} + +It is also possible to attach a shadowRoot to your element during the `connectedCallback`, like so: + +```typescript +import { controller, target } from "@github/catalyst" + +@controller +class HelloWorldElement extends HTMLElement { + @target nameEl: HTMLElement + get name() { + return this.nameEl.textContent + } + set name(value: string) { + this.nameEl.textContent = value + } + + connectedCallback() { + this.attachShadow({ mode: 'open' }).innerHTML = `+ Hello World +
` + } +} +``` + ### Updating a Template element using JS templates Sometimes you wont have a template that is server rendered, and instead want to make a template using JS. Catalyst does not support this out of the box, but it is possible to use another library: `@github/jtml`. This library can be used to write declarative templates using JS. Let's re-work the above example using `@github/jtml`: @@ -111,3 +133,4 @@ class HelloWorldElement extends HTMLElement { } } ``` + diff --git a/docs/_guide/targets-2.md b/docs/_guide/targets-2.md index 7176c680..5433c6ca 100644 --- a/docs/_guide/targets-2.md +++ b/docs/_guide/targets-2.md @@ -139,21 +139,32 @@ Important to note here is that nodes from the `shadowRoot` get returned _first_. ### What about without Decorators? -If you're using decorators, then the `@target` and `@targets` decorators will turn the decorated properties into getters. +If you're not using decorators, then the `@target` and `@targets` decorators have an escape hatch: you can define a static class field using the `[target.static]` computed property, as an array of key names. Like so: -If you're not using decorators, then you'll need to make a `getter`, and call `findTarget(this, key)` or `findTargets(this, key)` in the getter, for example: +```js +import {controller, target, targets} from '@github/catalyst' + +controller(class HelloWorldElement extends HTMLElement { + // The same as `@target output` + [target.static] = ['output'] + + // The same as `@targets pages; @targets links` + [targets.static] = ['pages', 'links'] + +}) +``` + +This is functionally identical to: ```js -import {findTarget, findTargets} from '@github/catalyst' -class HelloWorldElement extends HTMLElement { +import {controller} from '@github/catalyst' - get output() { - return findTarget(this, 'output') - } +@controller +class HelloWorldElement extends HTMLElement { + @target output - get pages() { - return findTargets(this, 'pages') - } + @targets pages + @targets links } ``` diff --git a/docs/_guide/testing-2.md b/docs/_guide/testing-2.md index 0f23f840..5619fe4f 100644 --- a/docs/_guide/testing-2.md +++ b/docs/_guide/testing-2.md @@ -3,6 +3,7 @@ version: 2 chapter: 13 title: Testing subtitle: Tips for automated testing +permalink: /guide-v2/testing --- Catalyst controllers are based on Web Components, and as such need the Web Platform environment to run in, including in tests. It's possible to run these tests in "browser like" environments such as NodeJS or Deno with libraries like jsdom, but it's best to run tests directly in the browser. diff --git a/docs/_guide/your-first-component-2.md b/docs/_guide/your-first-component-2.md index 6df16d10..233ca1b9 100644 --- a/docs/_guide/your-first-component-2.md +++ b/docs/_guide/your-first-component-2.md @@ -28,12 +28,12 @@ class HelloWorldElement extends HTMLElement { ```