Skip to content
This repository was archived by the owner on Jan 9, 2025. It is now read-only.

Commit 6ee2e64

Browse files
authored
Merge pull request #6 from github/docs-readme-add-documentation
docs(readme): add documentation
2 parents 532e115 + 30f8891 commit 6ee2e64

File tree

1 file changed

+238
-0
lines changed

1 file changed

+238
-0
lines changed

README.md

Lines changed: 238 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,241 @@ This library is heavily inspired by [`lit-html`](https://github.com/Polymer/lit-
77
- To re-use code we're using with [@github/template-parts](https://github.com/github/template-parts/) which is in production at GitHub.
88
- To align closer to the `Template Parts` whatwg proposal. By using [@github/template-parts](https://github.com/github/template-parts/) we aim to closely align to the Template Parts proposal, hopefully one day dropping the dependency on [@github/template-parts](https://github.com/github/template-parts/).
99

10+
### Basic Usage
11+
12+
This library comes with a set of exports, the main two being `html` and `render`.
13+
14+
`html` is a ["tagged template" function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates). Rather than calling it, you "tag" a template string with `html` and it will return a `TemplateResult` which can be used to render HTML safely, on the client side.
15+
16+
```js
17+
import {html, render} from '@github/jtml'
18+
19+
const greeting = 'Hello'
20+
render(html`<h1>${greeting} World</h1>`, document.body)
21+
```
22+
23+
The benefit of this over, say, setting `innerHTML` is that the tagged template can be re-used efficiently, causing less mutations in the DOM:
24+
25+
```js
26+
import {html, render} from '@github/jtml'
27+
28+
const theTime = date => html`<p>The time is ${date.toString()}</p>`
29+
setInterval(() => render(theTime(new Date()), document.body), 1000)
30+
```
31+
32+
### Expressions
33+
34+
jtml interpolates placeholder expressions in special ways across the template. Depending on where you put a placeholder expression (the `${}` syntax is a placeholder expression) depends on what it does. _Importantly_ "Attributes" behave differently to "Nodes". Here is a comprehensive list:
35+
36+
#### Attributes
37+
38+
HTML Attributes can contain placeholder expressions, but these _must_ be inside the quoted part of the attribute. The name of an Attribute cannot use placeholder expressions, only the value.
39+
40+
```js
41+
import {html, render} from '@github/jtml'
42+
43+
const className = `red-box`
44+
45+
html`<p class="${className}"></p>` // This is valid
46+
47+
html`<p class=${className}></p>` // !! This is INVALID!
48+
html`<p ${attr}="test"></p>` // !! This is INVALID!
49+
```
50+
51+
##### Boolean Values
52+
53+
If an attribute maps to a ["boolean attribute"](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes#boolean_attributes), and the attribute value consists _solely_ of a placeholder expression which evaluates to a boolean, then this can be used to toggle the attribute on or off. For example:
54+
55+
```js
56+
import {html, render} from '@github/jtml'
57+
58+
const input = (required = false) => html`<input required="${required}" />`
59+
const div = (hidden = false) => html`<div hidden="${hidden}"></div>`
60+
61+
render(input(false), document.body) // Will render `<input />`
62+
render(input(true), document.body) // Will render `<input required />`
63+
64+
render(div(true), document.body) // Will render `<div></div>`
65+
render(div(false), document.body) // Will render `<div></div>`
66+
```
67+
68+
##### Multiple values, whitespace
69+
70+
If an attribute consists of multiple placeholder expressions, these will all be mapped to strings. Any included whitespace is also rendered as you might expect. Here's an example:
71+
72+
```js
73+
import {html, render} from '@github/jtml'
74+
75+
const p = ({classOne, classTwo, classThree}) => html`<p class="${classOne} ${classTwo} ${classThree}"></p>`
76+
77+
render(p({classOne: 'red', classTwo: 'box', classThree: ''}), document.body)
78+
// ^ Renders `<p class="red box "></p>`
79+
80+
const i = ({classOne, classTwo}) => html`<p class="${classOne}-${classTwo}"></p>`
81+
82+
render(p({classOne: 'red', classTwo: 'box'}), document.body)
83+
// ^ Renders `<i class="red-box"></i>`
84+
```
85+
86+
##### Iterables (like Arrays)
87+
88+
Any placeholder expression which evaluates to an Array/Iterable is joined with spaces (`Array.from(value).join(' ')`). This means you can pass in an Array of strings and it'll be rendered as a space separated list. These can still be mixed with other placeholder expressions or static values. An example:
89+
90+
```js
91+
import {html, render} from '@github/jtml'
92+
93+
const p = ({classes, hidden = false}) => html`<p class="bold ${classes} ${hidden ? 'd-none' : ''}"></p>
94+
95+
render(p({classes: ['red', 'box'], hidden: true}), document.body)
96+
// ^ Renders `<p class="bold red box d-none"></p>`
97+
98+
render(p({classes: ['red', 'box'], hidden: false}), document.body)
99+
// ^ Renders `<p class="bold red box "></p>`
100+
```
101+
102+
##### Events
103+
104+
If an attributes name begins with `on`, and the value consists of a single placeholder expression that evaluates to a function, then this will become an Event Listener, where the event name is the attribute name without the `on`, so for example:
105+
106+
```js
107+
import {html, render} from '@github/jtml'
108+
109+
const handleClick = e => console.log('User clicked!')
110+
111+
render(html`<button onclick="${handleClick}"></button>`, document.body)
112+
// ^ Renders `<button></button>`
113+
// Effectively calls `button.addEventListener('click', handleClick)`
114+
```
115+
116+
The event name can be any event name that is also possible as an attribute, for example `onloaded` will listen for the `loaded` event, `onwill-load` will bind to the `will-load` event. Special characters such as `:`s are not allowed as attribute names, and as such you cannot bind to an event name with these special characters using this pattern.
117+
118+
#### Nodes
119+
120+
Placeholder expressions can also be put where an HTML node might be - in other words inside a tag, rather than inside an attribute. These behave differently to placeholder expressions inside attribute values:
121+
122+
##### HTML Escaping
123+
124+
Any HTML inside a string is automatically escaped. Values get added as `Text` nodes, meaning it is impossible to inject HTML unless you explicitly want to, making them safe for XSS. This is not manually handled by the library, but is core to the design - meaning the browser handles this escaping! An example:
125+
126+
```js
127+
import {html, render} from '@github/jtml'
128+
129+
const unsafe = '<script>alert(1)</script>'
130+
131+
render(html`<div>${unsafe}</div>`, document.body)
132+
// ^ Renders `<div>&lt;script&gt;alert(1)&lt;/script&gt;</div>`
133+
```
134+
135+
##### Sub Templates
136+
137+
If a placeholder expression evaluates to a sub template, then that sub template will be rendered and added to as a child to the node, in the position you'd expect:
138+
139+
```js
140+
import {html, render} from '@github/jtml'
141+
142+
const embolden = word => html`<strong>${word}</strong>`
143+
144+
render(html`<div>Hello ${embolden('world')}!</div>`, document.body)
145+
// ^ Renders `<div>Hello <strong>world</strong>!</div>`
146+
```
147+
148+
#### Document Fragments
149+
150+
You can also pass document fragments in, and they will be rendered as you might expect. This is useful for mixing-and-matching template libraries:
151+
152+
```js
153+
import {html, render} from '@github/jtml'
154+
155+
const vanillaEmbolden = word => {
156+
const frag = document.createDocumentFragment()
157+
const strong = document.createElement('strong')
158+
strong.append(String(word))
159+
frag.append(strong)
160+
return frag
161+
}
162+
163+
render(html`<div>Hello ${embolden('world')}!</div>`, document.body)
164+
// ^ Renders `<div>Hello <strong>world</strong>!</div>`
165+
```
166+
167+
##### Iterables (like Arrays)
168+
169+
Any placeholder expression which evaluates to an Array/Iterable is evaluated per-item. If a single item is a Document Fragment or Sub Template then it will be rendered as you might expect, otherwise it is treated as a String and gets added as a `Text` node. All of the contents of the Array will be rendered as one. Some examples:
170+
171+
```js
172+
import {html, render} from '@github/jtml'
173+
174+
const data = [ { name: 'Spanner', value: 5 }, { name: 'Wrench', value: 5 } ]
175+
176+
const row = ({name, value}) => html`<tr><td>${name}</td><td>${value}</td></td>`
177+
const table = rows => html`<table>${rows.map(row)}</table>`
178+
179+
render(table(data), document.body)
180+
// ^ Renders
181+
// <table>
182+
// <tr><td>Spanner</td><td>5</td></tr>
183+
// <tr><td>Wrench</td><td>5</td></tr>
184+
// </table>
185+
```
186+
187+
### Directives
188+
189+
For more advanced behaviours, a function can be wrapped with the `directive` function to create a `Directive` which gets to customize the rendering flow. jtml also includes some built in directives (see below).
190+
191+
A directive must follow the following signature. It can take any number of arguments (which are ignored) and must return a function which receives the TemplatePart:
192+
193+
```typescript
194+
type Directive = (...values: unknown[]) => (part: TemplatePart) => void
195+
```
196+
197+
Here's an example of how a directive might work:
198+
199+
```js
200+
import {html, render, directive} from '@github/jtml'
201+
202+
// A directive can take any number of arguments, and must return a function that takes a `TemplatePart`.
203+
const renderLater = directive((text, ms) => part => {
204+
// A parts value can be set using `.value`
205+
part.value = 'Loading...'
206+
setTimeout(() => part.value = text, ms)
207+
})
208+
209+
render(html`<div>${renderLater('Hello world', 1000)}`, document.body)
210+
// ^ Renders <div>Loading...</div>
211+
// After 1000ms, changes to `<div>Hello world</div>`
212+
```
213+
214+
### Built in Directives
215+
216+
### until
217+
218+
jtml ships with a built-in directive for handling Promise values, called `until`. `until` takes any number of Promises, and will render them, right to left, as they resolve. This is useful for passing in asynchronous values as the first arguments, timeout messages as the middle value, and synchronous values for the placeholder values, like so:
219+
220+
221+
```js
222+
import {html, render, until} from '@github/jtml'
223+
224+
const delay = (ms, value) => new Promise(resolve => setTimeout(resolve, ms, value))
225+
226+
const request = delay(1000, 'Hello World')
227+
const loading = 'Loading...'
228+
const timeout = delay(2000, 'Failed to load')
229+
230+
render(html`<div>${until(request, timeout, loading)}</div>`)
231+
// ^ renders <div>Loading...</div>
232+
// After 1000ms will render <div>Hello World</div>
233+
```
234+
235+
```js
236+
import {html, render, until} from '@github/jtml'
237+
238+
const delay = (ms, value) => new Promise(resolve => setTimeout(resolve, ms, value))
239+
240+
const request = delay(3000, 'Hello World') // Request takes longer than the timeout
241+
const loading = 'Loading...'
242+
const timeout = delay(2000, 'Failed to load')
243+
244+
render(html`<div>${until(request, timeout, loading)}</div>`)
245+
// ^ renders <div>Loading...</div>
246+
// After 2000ms will render <div>Failed to load</div>
247+
```

0 commit comments

Comments
 (0)