nbhi 0.6.16 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,322 +1,506 @@
1
- # What?
1
+ # NBHI
2
2
 
3
- **HTML includes and reactive rendering, all without any build tools**
3
+ **Web components from plain HTML templates, without build tools**
4
4
 
5
- No-build HTML includes (NBHI) is a simple **4.3KB** library that allows you to include html files into other html files and turns them into [web components](https://developer.mozilla.org/en-US/docs/Web/API/Web_components). Lazy initialization of content (when entering the viewport) and a one line call to update/hydrate content and attributes in your html pages. No build tools required, no `package.json` needed.
5
+ NBHI (No-Build HTML Includes) turns HTML templates into [web components](https://developer.mozilla.org/en-US/docs/Web/API/Web_components). You write a component as an HTML file, or as a `<template>` in your page, and NBHI defines it. The template says which parts of the component can change, and NBHI gives the component a property for each of them. You update a component by setting its properties, the same way you set `value` on an `<input>` or `src` on an `<img>`.
6
6
 
7
- # Why?
7
+ It does four things:
8
8
 
9
- NBHI is developed to create real-time data driven web sites. It has lower complexity than typical SPA applications but still offers more interactivy and flexibility than server side rendered web sites. _It works well with serverless application and a pub/sub data model_.
9
+ - **Loads components** from HTML files or inline templates, also when they are added to the page later.
10
+ - **Gives components properties** from bindings in their template.
11
+ - **Renders lists** into tables, lists and selects with one helper, `rows()`.
12
+ - **Makes components with a form field real form controls**, so forms, `FormData` and validation work like they do for native fields.
10
13
 
11
- NBHI is designed to be composable with other packages to build web sites. It takes the Lego approach, you select the packages for your needs, no lock-in into a single framework with a potential steep learning curve. NBHI is build on standard browser supported technologies which means that you only need to read MDN as the source of knowledge.
14
+ Everything else is standard HTML, CSS and JavaScript. If you know MDN, you know NBHI.
12
15
 
13
- NBHI minimizes abstractions, just standard HTML, CSS and Javascript. Migrating from a SPA to NBHI's multi page application (MPA) approach should mean you can do this one page at the time not having to migrate your whole system at once and pray that everything keeps working.
16
+ ## Install
14
17
 
15
- # Benefits
18
+ No build step is needed. Map the package in an import map and import it in a module script:
16
19
 
17
- - No-build web applications (you can still make it a dependency via npm install) 👍
18
- - Lightweight: **~4.3KB** (minified and bundled) 👍
19
- - No dependencies 👍
20
- - Benefit from standard web component encapsulation 👍
21
- - Lazy load page content, when about to enter the viewport 👍
22
- - Just standard web technologies, little abstractions 👍
23
- - Simple single function to hydrate your html (including attributes) 👍
24
- - Support for form validation for web component based html fields 👍
25
- - Composable with other packages 👍
26
- - Multi Page Application (MPA) design
27
- - The standard method how the web communicates between server and client 👍
28
- - Normal native routing 👍
29
- - Better SEO 👍
30
- - Each page loads what it needs and no more 👍
31
- - Fast initial draw 👍
32
-
33
- # Install
34
-
35
- For no-build solutions:
20
+ ```html
21
+ <script type="importmap">
22
+ { "imports": { "nbhi": "https://cdn.jsdelivr.net/npm/nbhi@1.0.0/javascript/index.js" } }
23
+ </script>
36
24
 
37
- ```js
38
25
  <script type="module">
39
- import { initialize } from 'https://cdn.jsdelivr.net/npm/nbhi@x.x.x/+esm';
26
+ import { initialize } from 'nbhi';
40
27
  await initialize();
41
28
  </script>
42
29
  ```
43
30
 
44
- For build solutions
31
+ Or install it with `npm install nbhi`.
45
32
 
46
- ```cli
47
- npm install nbhi
48
- ```
33
+ ## Defining components
49
34
 
50
- # Examples
35
+ ### Options
51
36
 
52
- Please look in the **examples.html** for working examples.
37
+ ```js
38
+ initialize({
39
+ prefix: 'nb', // components are <nb-...> elements (the default)
40
+ source: '/components', // <nb-card> loads /components/card.html (the default)
41
+ });
42
+ ```
53
43
 
54
- # How?
44
+ With `prefix: 'app'`, the components are `<app-card>`, `<app-nav>` and so on.
55
45
 
56
- ## Templates
46
+ `source` can also be a map from the name without the prefix to a file:
57
47
 
58
- Templates let you build complex systems and reuse components accross multiple pages, you can define templates in separate files or use them inline as a one-of if you just need the benefits of web components.
48
+ ```js
49
+ initialize({
50
+ source: {
51
+ card: '/shared/components/card.html',
52
+ nav: '/components/navigation.html',
53
+ },
54
+ });
55
+ ```
59
56
 
60
- ### External templates
57
+ ### A component in its own file
61
58
 
62
- index.html
59
+ `/components/card.html`
63
60
 
64
61
  ```html
65
- <html>
66
- <body>
67
- <my-component>Overwritten text</my-component>
62
+ <article>
63
+ <h2 nb-text="heading"></h2>
64
+ <!-- A standard web component slot, NBHI doesn't touch it -->
65
+ <slot></slot>
66
+ </article>
68
67
 
69
- <script type="module">
70
- import initialize from '/nbhi.js';
71
- await initialize(); // await if external templates
72
- </script>
73
- </body>
74
- </html>
68
+ <style>
69
+ /* Scoped to the component */
70
+ h2 { margin: 0; }
71
+ </style>
72
+
73
+ <script type="module">
74
+ import { format } from 'date-fns';
75
+ import { getArticle } from 'articles';
76
+
77
+ export default async element => {
78
+ // Runs once for every instance, the first time it is added to the page.
79
+ // element is the instance.
80
+ const article = await getArticle(element.dataset.id);
81
+ element.heading = `${ article.title } (${ format(article.published, 'yyyy') })`;
82
+ };
83
+ </script>
75
84
  ```
76
85
 
77
- /components/component.html
86
+ The script's default export runs with the element. Its imports go through the page's import map, for packages and for your own modules alike:
78
87
 
79
88
  ```html
80
- <div>
81
- <slot>Default text</slot>
82
- </div>
83
-
84
- <style>/* Scoped to the web component */</style>
85
-
86
- <script>
87
- // Runs for each instance, fires on the standard connectedCallback
88
- // element is the web component instance
89
- export default await (element, importer) => {
90
- // Path needs to be from the root of your project
91
- // Use the importer to load files, it will make the path absolute in order
92
- // to load the file. As the script tag is cloned and injected it has no
93
- // sense of where it lives so it needs absolute paths
94
- const { x } = await importer('/file/toLoad.js');
95
- ...
89
+ <script type="importmap">
90
+ {
91
+ "imports": {
92
+ "nbhi": "https://cdn.jsdelivr.net/npm/nbhi@1.0.0/javascript/index.js",
93
+ "date-fns": "https://esm.sh/date-fns@4.1.0",
94
+ "articles": "/javascript/articles.js"
95
+ }
96
96
  }
97
97
  </script>
98
98
  ```
99
99
 
100
- ### Internal templates
100
+ Use names from the import map or full URLs. A relative path (`./articles.js`) or a path from the root (`/javascript/articles.js`) doesn't work in a component script: NBHI runs it from a `blob:` URL, which has no folder to resolve such a path from.
101
101
 
102
- index.html
102
+ The page uses it like any element:
103
103
 
104
104
  ```html
105
- <html>
106
- <body>
107
- <!-- id becomes the name of your web component -->
108
- <template id="my-component">
109
- <slot>Default</slot>
110
- <style>/* Scoped to the web component */</style>
111
- </template>
105
+ <nb-card heading="Getting started">A short introduction to web components.</nb-card>
106
+ ```
107
+
108
+ ### A component in the page
112
109
 
113
- <my-component>Overwrite</my-component>
110
+ A `<template>` whose id starts with the prefix is a component. Other templates are left alone, so you can still use `<template>` for your own purposes.
111
+
112
+ ```html
113
+ <template id="nb-badge">
114
+ <span nb-text="label"></span>
115
+ <style>span { font-weight: bold; }</style>
116
+ </template>
114
117
 
115
- <script type="module">
116
- import initialize from '/nbhi.js';
117
- initialize(); // No await needed for internal templates
118
- </script>
119
- </body>
120
- </html>
118
+ <nb-badge label="Draft"></nb-badge>
121
119
  ```
122
120
 
123
- ## Options
121
+ ### Components added later
122
+
123
+ NBHI watches the page and the inside of every component. A component that a script adds later, with `append()`, `innerHTML` or inside another component, is loaded and defined as soon as it appears. To use it straight away, wait until it is defined:
124
124
 
125
125
  ```js
126
- initialize({ prefix = 'my', directory = '/components' }); // Defaults
126
+ list.insertAdjacentHTML('beforeend', '<nb-card></nb-card>');
127
+ await customElements.whenDefined('nb-card');
127
128
  ```
128
129
 
129
- ```js
130
- initialize({ prefix: 'x' }); // Components are now x-component
130
+ ### Sharing page styles
131
+
132
+ A component's styles are scoped to it. To let every component use a stylesheet of the page too (a CSS framework, your typography), mark it with `data-inherit`:
133
+
134
+ ```html
135
+ <link rel="stylesheet" href="/stylesheets/pico.css" data-inherit="true">
136
+ ```
137
+
138
+ NBHI reads it once and shares it with every component.
139
+
140
+ ## Properties
141
+
142
+ The template decides what can change. Two bindings create properties:
143
+
144
+ | Binding | What the property sets |
145
+ | --- | --- |
146
+ | `nb-text="heading"` | the text of the element |
147
+ | `:href="link"` | the `href` of the element (any attribute works: `:src`, `:disabled`, `:data-state`, ...) |
148
+
149
+ Everything NBHI reads in a template starts with `nb-` or `:`. `data-*` attributes are never NBHI syntax, they stay yours.
150
+
151
+ ```html
152
+ <template id="nb-author">
153
+ <h2 nb-text="name"></h2>
154
+ <a :href="link">Open profile</a>
155
+ <img :src="photo" :alt="name">
156
+ </template>
131
157
  ```
132
158
 
133
159
  ```js
134
- initialize({ components: '/abc' }); // Fetches files in /abc/component.html
160
+ const author = document.querySelector('nb-author');
161
+ author.name = 'Jane Doe'; // the heading, and the alt of the image
162
+ author.link = '/authors/jane-doe';
163
+ author.photo = '/images/jane-doe.jpg';
164
+ ```
165
+
166
+ ### One name, every element that uses it
167
+
168
+ A property updates every element that binds it. In the example above `name` sets both the heading and the `alt` of the image.
169
+
170
+ Elements that have the same attribute with a different meaning get different names. Nothing collides, because the page never uses the native attribute name:
171
+
172
+ ```html
173
+ <template id="nb-period">
174
+ <input type="date" :value="start" :min="earliest">
175
+ <input type="date" :value="end" :min="start">
176
+ <button :disabled="locked">Apply</button>
177
+ </template>
135
178
  ```
136
179
 
137
180
  ```js
138
- // key = name of component (no prefix), value is path to file
139
- initialize({ components: {
140
- nav: '/shared/nav.html',
141
- dropdown: '/components/dropdown.html'
142
- } });
181
+ period.start = '2024-01-01'; // the first input, and the minimum of the second
182
+ period.end = '2025-12-31';
183
+ period.locked = true;
143
184
  ```
144
185
 
145
- ## Update a single component (data and attributes)
186
+ ### Values
187
+
188
+ - `true` sets an attribute without a value (`disabled`), `false`, `null` and `undefined` remove it.
189
+ - `null` and `undefined` empty the text of an `nb-text` element.
190
+ - On form fields, `:value`, `:checked` and `:selected` set the property, not the attribute. The attribute is only the starting value of a field, the property is what it shows.
191
+ - On another component, a binding sets that component's property, so values can be any type (see Nested components).
192
+ - Reading a property gives back the last value that was set.
146
193
 
147
- ### Via HTML
194
+ ### Text, not HTML
195
+
196
+ `nb-text` sets text. Markup in your data is shown as text, never run, so user input can't add elements or scripts to your page.
197
+
198
+ When you do want HTML, from a source you trust, use `nb-html`:
148
199
 
149
200
  ```html
150
- <!-- Instance -->
151
- <my-component checked data-id="1">
152
- Text here will be assigned to the default slot
153
- <span slot="title">Will be assigned to the named slot</span>
154
- </my-component>
201
+ <div nb-html="description"></div>
202
+ ```
155
203
 
156
- <!-- Component definition -->
157
- <section data-id=""> <!-- Data and custom attributes need to be defined so NBHI can resolve them -->
158
- <input type="checkbox"> <!-- NBHI automatically maps common attributes, checked will be placed on the input -->
159
- <slot>Default text</slot>
160
- <slot name="title">Default title</slot>
161
- </section>
204
+ ### Properties as attributes
205
+
206
+ Every property can also be set as an attribute in the page's HTML. A camelCase property is a kebab-case attribute:
207
+
208
+ ```html
209
+ <nb-period start="2024-01-01" end="2025-12-31" locked></nb-period>
162
210
  ```
163
211
 
164
- ### Via JS
212
+ ```js
213
+ period.setAttribute('start', '2024-06-01'); // the same as period.start = '2024-06-01'
214
+ ```
215
+
216
+ Attributes are always strings, properties keep their type. Use properties for numbers, arrays and objects.
217
+
218
+ ### Before a component is defined
219
+
220
+ A component file loads asynchronously. Properties set before that keep their value: NBHI applies them once the component is defined, so this works:
165
221
 
166
222
  ```js
167
- import { update } from 'nbhi';
223
+ const card = document.createElement('nb-card');
224
+ card.heading = 'Getting started';
225
+ document.body.append(card);
226
+ ```
227
+
228
+ ### What is not a property
229
+
230
+ A component only has the properties its template binds. Every other attribute stays on the component element itself and does what it does on any element:
168
231
 
169
- const updater = update('my-component');
232
+ - `hidden`, `class`, `id`, `style`, `title`, `slot`, `lang`, `dir`, `role`, `aria-*` and other global attributes apply to the component as a whole. `hidden` always hides it, also when its CSS sets `display`.
233
+ - `data-*` attributes stay yours, read them with `element.dataset`.
234
+ - Attributes that only change the look need no binding. Select them in the component's CSS:
170
235
 
171
- updater('Text here will be assigned to the default slot');
172
- updater({ title: 'Will be assigned to the named slot' });
173
- updater({ $checked: true, `$data-id`: 1 }); // Atributes are prefixed with $
236
+ ```css
237
+ :host([variant="danger"]) { --badge-color: crimson; }
174
238
  ```
175
239
 
176
- ## Update a list (data and attributes)
240
+ To pass one of these to an element inside, bind it: `<input :aria-label="label">`.
177
241
 
178
- ### Inline child
242
+ A binding can't use a name that every element already has as a property, like `title`, `hidden`, `id` or `style`: NBHI throws when it defines the component. Use `nb-text="heading"` instead of `nb-text="title"`. In a list row this doesn't matter, as the bindings read from the record.
179
243
 
180
- /components/component.html
244
+ ## Nested components
245
+
246
+ A binding on a component inside a template sets that component's property. That is how a component passes a value on:
181
247
 
182
248
  ```html
183
- <div>
184
- <h1><slot>Header</slot></h1>
185
- <div child> <!-- NBHI uses child attribute to make clones from -->
186
- <p data-slot="name"></p> <!-- use data-slot for inline children -->
187
- </div>
188
- </div>
249
+ <template id="nb-article-card">
250
+ <h2 nb-text="heading"></h2>
251
+ <nb-badge :label="status"></nb-badge>
252
+ </template>
189
253
  ```
190
254
 
191
- index.html
255
+ ```js
256
+ card.status = 'Draft'; // sets the label of the badge inside
257
+ ```
258
+
259
+ You set the outer property and the template passes it on. The page never reaches into a component.
260
+
261
+ ## Refs
262
+
263
+ Sometimes a page needs an element inside a component itself, for example to measure it or to hand it to a library. Name it with `nb-ref`:
192
264
 
193
265
  ```html
194
- <my-component>Header overwrite</my-component>
266
+ <template id="nb-map">
267
+ <div nb-ref="canvas"></div>
268
+ </template>
269
+ ```
195
270
 
196
- <script>
197
- import { initialize, update } from 'nbhi';
198
- await initialize();
199
- update('my-component')([
200
- { name: 'Record 1' },
201
- { name: 'Record 2' },
202
- ]);
203
- </script>
271
+ ```js
272
+ new google.maps.Map(document.querySelector('nb-map').refs.canvas, { zoom: 8 });
273
+ ```
274
+
275
+ `refs` is the way into a component. If you use it to change content or attributes, add a property instead.
276
+
277
+ ## Events
278
+
279
+ Listen to a component the way you listen to a native element: add the listener to the component itself.
280
+
281
+ ```js
282
+ const select = document.querySelector('nb-select');
283
+
284
+ select.addEventListener('change', () => {
285
+ console.log(select.value);
286
+ });
204
287
  ```
205
288
 
206
- ### Child component
289
+ ### Events from the elements inside
290
+
291
+ When a user clicks, types or presses a key on an element inside a component, the event reaches the page as if the component itself fired it. `event.target` is the component, not the element inside, so the page never needs to know how the component is built.
292
+
293
+ The browser does this for most events, like `click`, `input` and `keydown`. It doesn't for `change`: that event stays inside the component. NBHI fires it again from the component, so `change` works like the others.
207
294
 
208
- /components/component.html
295
+ ### Your own events
296
+
297
+ A component's script can fire its own events. Dispatch them on the component element, with `bubbles: true` so that a listener on a parent hears them too:
298
+
299
+ `/components/tag.html`
209
300
 
210
301
  ```html
211
- <div>
212
- <h1><slot>Header</slot></h1>
213
- <my-child child></my-child> <!-- NBHI uses child attribute to make clones from -->
214
- </div>
302
+ <span nb-text="label"></span>
303
+ <button nb-ref="remove">×</button>
304
+
305
+ <script type="module">
306
+ export default element => {
307
+ element.refs.remove.addEventListener('click', () => {
308
+ element.dispatchEvent(new CustomEvent('remove', { bubbles: true, detail: { label: element.label } }));
309
+ });
310
+ };
311
+ </script>
215
312
  ```
216
313
 
217
- /components/child.html
314
+ One listener on the parent handles every tag in it:
218
315
 
219
316
  ```html
220
- <div>
221
- <p><slot></slot></p> <!-- use regular slot for nested components -->
317
+ <div class="tags">
318
+ <nb-tag label="html"></nb-tag>
319
+ <nb-tag label="css"></nb-tag>
222
320
  </div>
223
321
  ```
224
322
 
225
- index.html
323
+ ```js
324
+ document.querySelector('.tags').addEventListener('remove', event => {
325
+ event.target.remove();
326
+ });
327
+ ```
328
+
329
+ ## Lists
330
+
331
+ `rows()` renders a list of records into an element. The first element in it is the template for a row:
226
332
 
227
333
  ```html
228
- <my-component>Header overwrite</my-component>
334
+ <table class="articles">
335
+ <thead>
336
+ <tr><th>Title</th><th>Status</th></tr>
337
+ </thead>
338
+ <tbody>
339
+ <tr>
340
+ <td><a :href="link" nb-text="title"></a></td>
341
+ <td><nb-badge :label="status"></nb-badge></td>
342
+ </tr>
343
+ </tbody>
344
+ </table>
345
+ ```
229
346
 
230
- <script>
231
- import { initialize, update } from 'nbhi';
232
- await initialize();
233
- update('my-component')(['Record 1', 'Record 2']);
234
- </script>
347
+ ```js
348
+ import { rows } from 'nbhi';
349
+
350
+ const table = document.querySelector('.articles');
351
+ const articles = await fetch('/api/articles').then(response => response.json());
352
+
353
+ rows(table, articles.map(({ id, title, status }) => ({
354
+ id,
355
+ title,
356
+ status,
357
+ link: `/articles/${ id }`,
358
+ })));
235
359
  ```
236
360
 
237
- ### List data for `<table>, <ol>, <li> and <option>`
361
+ Call `rows()` again with new data whenever it changes, for example from a polling loop, a WebSocket or a realtime database listener.
238
362
 
239
- These elements do not support web component children. So for these you can just define the following
363
+ Inside a row, the bindings read from the record. The same bindings work as in a component: `nb-text`, `nb-html`, `:attribute` and bindings on components.
240
364
 
241
- index.html
365
+ ### Where the rows go
242
366
 
243
- ```html
244
- <template id="my-table">
245
- <table>
246
- <thead>
247
- <tr>
248
- <th>Header</th>
249
- </tr>
250
- </thead>
251
- <tbody> <!-- Required -->
252
- <tr> <!-- No need for child attribute -->
253
- <td data-slot="name"></td>
254
- </tr>
255
- </tbody>
256
- </table>
257
- </template>
367
+ | Element | Rows | Template |
368
+ | --- | --- | --- |
369
+ | `<table>` | the `<tr>`s of its `<tbody>` | the first `<tr>` of the `<tbody>` |
370
+ | `<ul>`, `<ol>` | `<li>`s | the first `<li>` |
371
+ | `<select>` | `<option>`s | the first `<option>` |
372
+ | any other element | its children | its first child |
258
373
 
259
- index.html
374
+ NBHI takes the template out of the page the first time and keeps it, so you write the row once in your HTML.
260
375
 
261
- <my-table></my-table>
376
+ ### Keeping rows
262
377
 
263
- <script>
264
- import { initialize, update } from 'nbhi';
265
- await initialize();
266
- update('my-table')([
267
- { name: 'Record 1' },
268
- { name: 'Record 2' },
269
- ]);
270
- </script>
271
- ```
378
+ Rows are matched to records by `id`. A record whose `id` was already shown keeps its element, even when it is a new object (as it is every time data is loaded again). The element is updated in place and moved when the order changes, so open details, a typed value and any element a test is holding all stay. Records without an `id` are matched by position.
272
379
 
273
- Same logic for `<ol>`, `<ul>` and `<option>`
380
+ Every call renders every record again, so a record that changed in place shows its new values. A key that is missing from a record empties its binding.
274
381
 
275
- When a record has an `id` (string or number), its rendered element is reused for the next record with the same `id`, even when that is a new object (for example after reloading the data). The element stays in the DOM and is updated in place. Records without an `id` are matched by object identity.
382
+ Each element keeps its own list. Calling `rows()` again on the same element, from anywhere, continues with the rows that are already there.
276
383
 
277
- ## Lazy loading
384
+ ### Records that are strings or numbers
278
385
 
279
- ```js
280
- import { onceVisible } form 'nbhi';
386
+ A string or number is used as `{ id: value, value }`:
281
387
 
282
- onceVisible('my-component', element => ...); // Will run once when it comes into view (200px before)
388
+ ```html
389
+ <ul class="tags"><li nb-text="value"></li></ul>
283
390
  ```
284
391
 
285
- ## Validating a form field
286
-
287
392
  ```js
288
- import { validate } form 'nbhi';
393
+ rows(document.querySelector('.tags'), ['html', 'css', 'javascript']);
394
+ ```
395
+
396
+ ### Doing more per row
289
397
 
290
- const internals = validate('my-form-field'); // Returns elementInternals
398
+ For what a binding can't do, like an event listener, pass a function. It runs for every row after the bindings are applied:
291
399
 
292
- // See MDN for details
293
- internals.checkValidity();
294
- internals.validity;
400
+ ```js
401
+ rows(table, articles, (row, record) => {
402
+ row.querySelector('button').onclick = () => archive(record.id);
403
+ });
295
404
  ```
296
- ## Inherit styles
297
405
 
298
- Your components can inherit global styles. These styles are copied once and a reference to those styles are given to each web component keeping it performant.
299
- This function is handy if you have global styles that a component needs to inherit from.
406
+ ### Lists inside a component
407
+
408
+ In a template, `nb-each` makes a property that takes a list:
300
409
 
301
410
  ```html
302
- <link rel="stylesheet" data-inherit="true" href="...">
411
+ <template id="nb-select">
412
+ <label>
413
+ <span nb-text="label"></span>
414
+ <select :value="value" nb-each="options">
415
+ <option :value="value" nb-text="label"></option>
416
+ </select>
417
+ </label>
418
+ </template>
303
419
  ```
304
420
 
421
+ ```js
422
+ const select = document.querySelector('nb-select');
423
+ select.label = 'Reviewer';
424
+ select.options = users.map(({ id, name }) => ({ value: id, label: name }));
425
+ select.value = 'u-123';
426
+ ```
427
+
428
+ Inside the row (here the `<option>`), the bindings read from each record. Outside it, they read from the component.
429
+
430
+ ## Forms
305
431
 
306
- ## FAQ
432
+ A component with an `<input>`, `<select>` or `<textarea>` is a form control. It works in a `<form>` like the field itself:
307
433
 
308
- ### No build steps is nice, but I want to use TypeScript
434
+ ```html
435
+ <template id="nb-input">
436
+ <label>
437
+ <span nb-text="label"></span>
438
+ <input :value="value" :required="required" :placeholder="placeholder">
439
+ </label>
440
+ </template>
309
441
 
310
- If you want to use TS you have a couple of options. You can either add a build step, nothing is stopping you, the library supports it. If you want to stay buildless but want to add some sort of type checking and hinting you can consider using JSDoc, it is [supported](https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#author) in TS as well.
442
+ <form>
443
+ <nb-input name="title" label="Title" required></nb-input>
444
+ <button>Save</button>
445
+ </form>
446
+ ```
311
447
 
312
- ### Creating interactivity is verbose with native js DOM manipulation
448
+ ```js
449
+ const form = document.querySelector('form');
450
+ const title = form.querySelector('nb-input');
313
451
 
314
- NBHI is not designed to be a single solution for everything, if you want to make DOM manipulation for interactivity easier I would suggest using dedicated libraries for that. You can consider [Alpine.js](https://alpinejs.dev/) or [Umbrella.js](https://umbrellajs.com/) for example. NBHI is designed with composibility in mind so you decide what to add.
452
+ title.value = 'Getting started'; // shown in the input
453
+ new FormData(form).get('title'); // 'Getting started'
454
+ form.reportValidity(); // checks the input inside, shows its message
455
+ ```
315
456
 
316
- ### Anybody using web component technology?
457
+ - **The field:** the element marked `nb-ref="field"`, or else the first `input`, `select` or `textarea`.
458
+ - **`name`** on the component is the name in the form.
459
+ - **`value`** on the component reads and sets the field. For a checkbox or radio, use `checked`.
460
+ - **The form value** is updated on every `input` and `change`, so `FormData` and submitting always have the current value.
461
+ - **Validation:** the field's own validity (`required`, `min`, `pattern`, `type="email"`, ...) is the component's validity, with the browser's messages. `checkValidity()`, `reportValidity()`, `validity` and `:invalid` work on the component.
462
+ - **Reset:** resetting the form puts the field back to its starting value.
463
+ - **Disabled:** a disabled `<fieldset>` disables the field.
464
+ - **Focus:** `component.focus()` focuses the field, and clicking its label does too.
317
465
 
318
- Just check out the source code of github.com or youtube.com.
466
+ ## Reference
319
467
 
320
- ### We are a team of multiple developers, using a framework ensures we write similar code
468
+ ```js
469
+ import { initialize, rows } from 'nbhi';
470
+ ```
321
471
 
322
- You are correct, when you choose a more opinionated framework it will most likely give more cohesive code overall when you work with multiple developers. However it also gives you lock-in. It is a trade-off that you have to make, depending on the team size and how agile your codebase needs to remain.
472
+ | Export | What it does |
473
+ | --- | --- |
474
+ | `initialize({ prefix, source })` | Defines the components in the page and loads the ones added later. Resolves when the components in the page are defined. |
475
+ | `rows(element, records, each)` | Renders `records` into `element`, matched by `id`. `each(row, record)` is optional. |
476
+
477
+ In templates:
478
+
479
+ | Markup | Meaning |
480
+ | --- | --- |
481
+ | `<template id="nb-name">` | a component in the page |
482
+ | `nb-text="name"` | property `name` sets the text of this element |
483
+ | `nb-html="name"` | property `name` sets the HTML of this element |
484
+ | `:attribute="name"` | property `name` sets this attribute, or this property on form fields and components |
485
+ | `nb-each="name"` | property `name` takes a list, the first child is the row |
486
+ | `nb-ref="name"` | `component.refs.name` is this element |
487
+
488
+ ## Upgrading from 0.x
489
+
490
+ | 0.x | Now |
491
+ | --- | --- |
492
+ | Default prefix `db` | Default prefix `nb`, pass `prefix: 'db'` to keep the old names |
493
+ | `export default (element, importer) => {}` and `await importer('/path.js')` | `export default element => {}`, import your modules through the import map |
494
+ | `<template>` without an id inside a component became `<parent>-child` | Only a `<template id="<prefix>-...">` is a component |
495
+ | `update(element)('text')` on a plain element | `element.textContent = 'text'` |
496
+ | `update(link)({ $href: url })` on a plain element | `link.href = url` |
497
+ | `update(table)(records)` | `rows(table, records)` |
498
+ | `data-slot="name"` in a row | `nb-text="name"` |
499
+ | `update(component)({ heading })`, which added `<span slot="heading">` to the component | `component.heading = heading`, with `nb-text="heading"` in the template instead of `<slot name="heading">`. Slots now only take content the page writes in its HTML |
500
+ | `update(component)({ $checked: true })` | `component.checked = true`, with `:checked="checked"` in the template |
501
+ | Attributes passed inward automatically | Bind them: `<input :required="required">` |
502
+ | `validate(component)` | Not needed: validity is kept up to date. Use `component.checkValidity()` |
503
+ | `onceVisible(element, callback)` | Removed. Use an [`IntersectionObserver`](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver) |
504
+ | `component.shadowRoot.querySelector(...)` | A property, or `component.refs.name` |
505
+ | `[child]` element for lists in a component | `nb-each="name"` on the list's parent |
506
+ | Values inserted as HTML | Values are text, use `nb-html` for HTML |