Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 57 additions & 3 deletions docs/_guide/anti-patterns.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ chapter: 9
subtitle: Anti Patterns
---

{% capture discouraged %}<h4 class="text-red"><svg class="octicon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24"><path fill-rule="evenodd" d="M1 12C1 5.925 5.925 1 12 1s11 4.925 11 11-4.925 11-11 11S1 18.075 1 12zm8.036-4.024a.75.75 0 00-1.06 1.06L10.939 12l-2.963 2.963a.75.75 0 101.06 1.06L12 13.06l2.963 2.964a.75.75 0 001.061-1.06L13.061 12l2.963-2.964a.75.75 0 10-1.06-1.06L12 10.939 9.036 7.976z"></path></svg> Discouraged</h4>{% endcapture %}

{% capture encouraged %}<h4 class="text-green"><svg class="octicon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24"><path fill-rule="evenodd" d="M1 12C1 5.925 5.925 1 12 1s11 4.925 11 11-4.925 11-11 11S1 18.075 1 12zm16.28-2.72a.75.75 0 00-1.06-1.06l-5.97 5.97-2.47-2.47a.75.75 0 00-1.06 1.06l3 3a.75.75 0 001.06 0l6.5-6.5z"></path></svg> Encouraged</h4>{% endcapture %}
{% capture octx %}<svg class="octicon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24"><path fill-rule="evenodd" d="M1 12C1 5.925 5.925 1 12 1s11 4.925 11 11-4.925 11-11 11S1 18.075 1 12zm8.036-4.024a.75.75 0 00-1.06 1.06L10.939 12l-2.963 2.963a.75.75 0 101.06 1.06L12 13.06l2.963 2.964a.75.75 0 001.061-1.06L13.061 12l2.963-2.964a.75.75 0 10-1.06-1.06L12 10.939 9.036 7.976z"></path></svg>{% endcapture %}
{% capture octick %}<svg class="octicon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24"><path fill-rule="evenodd" d="M1 12C1 5.925 5.925 1 12 1s11 4.925 11 11-4.925 11-11 11S1 18.075 1 12zm16.28-2.72a.75.75 0 00-1.06-1.06l-5.97 5.97-2.47-2.47a.75.75 0 00-1.06 1.06l3 3a.75.75 0 001.06 0l6.5-6.5z"></path></svg>{% endcapture %}
{% capture discouraged %}<h4 class="text-red">{{ octx }} Discouraged</h4>{% endcapture %}
{% capture encouraged %}<h4 class="text-green">{{ octick }} Encouraged</h4>{% endcapture %}

Here are a few common anti-patterns which we've discovered as developers have used Catalyst. We consider these anti-patterns as they're best avoided, because of surprising edge-cases, or simply because there are easier ways to achieve the same goals.

Expand Down Expand Up @@ -111,6 +112,59 @@ class UserSettingsElement extends HTMLElement {
</div>
</div>

### Avoid shadowing method names

When naming a method, you should avoid naming it something that already exists on the `HTMLElement` prototype; as doing so can lead to surprising behaviors. Test out the form below to see what method names are allowed or not:

<form>
<label>
<h4>I want my method to be called...</h4>
<input class="js-methodname-shadow-test mb-4">
</label>
<div hidden class="js-methodname-shadow-bad-input text-red">
{{ octx }} This name would shadow <code></code>, you'll need to pick a different name
</div>
<div hidden class="js-methodname-shadow-warn-input text-orange-light">
{{ octx }} While this name is allowed, it's not ideal because <span></span>. You should consider a different name.
</div>
<div hidden class="js-methodname-shadow-good-input text-green">
{{ octick }} This is a good name for a method!
</div>
<script>
const warnings = {
'new': 'it has a special meaning in JS',
'super': 'it has a special meaning in JS',
'prototype': 'it has a special meaning in JS',
'requestSubmit': 'it is a proposed new feature',
}
document.querySelector('.js-methodname-shadow-test').addEventListener('input', () => {
const name = event.target.value
const goodEl = document.querySelector('.js-methodname-shadow-good-input')
const badEl = document.querySelector('.js-methodname-shadow-bad-input')
const warnEl = document.querySelector('.js-methodname-shadow-warn-input')
let warning = warnings[name]
if (name !== name.toLowerCase() && name.toLowerCase() in HTMLElement.prototype) {
warning = `it is too similar to \`${name.toLowerCase()}\` which already exists`
} else if (name.startsWith('on') && !(name in HTMLElement.prototype)) {
warning = 'starting with `on` suggests a coupling between the event and the method (see below)'
}
goodEl.hidden = warning || (name in HTMLElement.prototype)
warnEl.hidden = !warning
badEl.hidden = warning || !(name in HTMLElement.prototype)
if (warning) {
warnEl.querySelector('span').textContent = warning
} else if (name in HTMLElement.prototype) {
let proto = HTMLElement.prototype
while(proto !== null) {
if (proto.hasOwnProperty(name)) break
proto = Object.getPrototypeOf(proto)
}
badEl.querySelector('code').textContent = `${proto.constructor.name}.prototype.${name}`
}
})
</script>
</form>

### Avoid naming methods after events, e.g. `onClick`

When you have a method which is only called as an event, it is tempting to name that method based off of the event, e.g. `onClick`, `onInputFocus`, and so on. This name implies a coupling between the event and method, which later refactorings may break. Also names like `onClick` are very close to `onclick` which is already [part of the Element's API](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onclick). Instead we recommend naming the method after what it does, not how it is called, for example `resetForm`:
Expand Down
6 changes: 3 additions & 3 deletions docs/_guide/conventions.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ class UserListElement extends HTMLElement {}

### The best class-names are two word descriptions

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 two words. The element name should describe what it does succinctly in two words. Some examples:
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:

- `theme-picker` (`class ThemePickerElement`)
- `markdown-toolbar` (`class MarkdownToolbarElement`)
Expand All @@ -34,8 +34,8 @@ Be careful not to go too short! We'd recommend avoiding contracting words such a

### Method names should describe what they do

A good method name, much like a good class name, describes what it does, not how it was invoked. While methods can be given any name, 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`.
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](/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`.

### `@target` should use singular naming, while `@targets` should use plural

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`).
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`).
57 changes: 35 additions & 22 deletions docs/_guide/your-first-component.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,51 +3,64 @@ subtitle: Building an HTMLElement
chapter: 2
---

Custom Elements allow you to create reusable components that you can declare in HTML, and [progressively enhance](https://en.wikipedia.org/wiki/Progressive_enhancement) within JavaScript. Custom Elements must named with a `-` in the HTML name, and the JS class must `extend HTMLElement`. When the browser connects each element class instance to the DOM node, `connectedCallback` is fired - this is where you can change parts of the element. Here's a basic example:
### Catalyst's `@controller` decorator

```html
<hello-world></hello-world>
<script>
Catalyst's `@controller` decorator lets you create Custom Elements with virtually no boilerplate, by automatically calling `customElements.register`, and by adding ["Actions"](/guide/actions) and ["Targets"](/guide/targets) features described later. Using TypeScript (with `decorators` support enabled), simply add `@controller` to the top of your class:

```js
@controller
class HelloWorldElement extends HTMLElement {
connectedCallback() {
this.innerHTML = 'Hello World!'
}
}
window.customElements.register('hello-world', HelloWorldElement)
</script>
// This happens automatically within `@controller`
// window.customElements.register('hello-world', HelloWorldElement)
```
<br>

Catalyst will automatically convert the classes name; removing the trailing `Element` suffix and lowercasing all capital letters, separating them with a dash.

Here are the three key elements to remember:
By convention, Catalyst controllers end in `Element`, and Catalyst will strip this for the tag name, but the `Element` suffix is not required - just convention. All examples in this guide use `Element` suffixed names.

- Custom Elements must have a dash in the name.
- The JS class must `extend HTMLElement`
- `connectedCallback` can be used as a life-cycle hook for when the element and class are connected.
<div class="d-flex border rounded-1 my-3 box-shadow-medium">
<span class="d-flex bg-blue text-white rounded-left-1 p-3">
<svg width="24" viewBox="0 0 14 16" class="octicon octicon-info" aria-hidden="true">
<path
fill-rule="evenodd"
d="M6.3 5.69a.942.942 0 0 1-.28-.7c0-.28.09-.52.28-.7.19-.18.42-.28.7-.28.28 0 .52.09.7.28.18.19.28.42.28.7 0 .28-.09.52-.28.7a1 1 0 0 1-.7.3c-.28 0-.52-.11-.7-.3zM8 7.99c-.02-.25-.11-.48-.31-.69-.2-.19-.42-.3-.69-.31H6c-.27.02-.48.13-.69.31-.2.2-.3.44-.31.69h1v3c.02.27.11.5.31.69.2.2.42.31.69.31h1c.27 0 .48-.11.69-.31.2-.19.3-.42.31-.69H8V7.98v.01zM7 2.3c-3.14 0-5.7 2.54-5.7 5.68 0 3.14 2.56 5.7 5.7 5.7s5.7-2.55 5.7-5.7c0-3.15-2.56-5.69-5.7-5.69v.01zM7 .98c3.86 0 7 3.14 7 7s-3.14 7-7 7-7-3.12-7-7 3.14-7 7-7z"
/>
</svg>
</span>
<div class="p-3">

Remember! A class name _must_ include at least two CamelCased words (not including the `Element` suffix). One-word elements will raise exceptions. Example of good names: `UserListElement`, `SubTaskElement`, `PagerContainerElement`

### Catalyst
</div>
</div>

Catalyst saves you writing some of this boilerplate, by automatically calling the `customElements.register` code, and by adding ["Actions"](/guide/actions) and ["Targets"](/guide/targets) features described later. If you're using TypeScript with `decorators` support, simply add `@controller` to the top of your class:

```js
@controller
### What does `@controller` do?

Catalyst components are really just "Custom Elements", they're doing all the heavy lifting. Custom Elements allow you to create reusable components that you can declare in HTML, and [progressively enhance](https://en.wikipedia.org/wiki/Progressive_enhancement) within JavaScript. Custom Elements must named with a `-` in the HTML name, and the JS class must `extend HTMLElement`. When the browser connects each element class instance to the DOM node, `connectedCallback` is fired - this is where you can change parts of the element. Here's a basic example:

```html
<hello-world></hello-world>
<script>
class HelloWorldElement extends HTMLElement {
connectedCallback() {
this.innerHTML = 'Hello World!'
}
}
// No longer need this:
// window.customElements.register('hello-world', HelloWorldElement)
window.customElements.register('hello-world', HelloWorldElement)
</script>
```
<br>

Catalyst will automatically convert the classes name; removing the trailing `Element` suffix and lowercasing all capital letters, separating them with a dash.

By convention, Catalyst controllers end in `Element`, and Catalyst will strip this for the tag name, but suffixing `Element` is not required. All examples in this guide use `Element` suffixed names.
The Catalyst version isn't all that different, it's just that we have the `@controller` decorator to save on some of the boilerplate.

#### What about without Decorators?
### What about without TypeScript Decorators?

If you don't want to use decorators, you can simply wrap the class in a call to `controller`:
If you don't want to use TypeScript decorators, you can use `controller` as a regular function, and just pass it your class:

```js
controller(
Expand Down