# Enhancements

> Hand server-rendered markup to a small browser module, loaded only on pages that use it.

Some interactivity has to run in the browser: a counter, a copy button, a form that checks itself as you type. `enhance()` marks the markup a module should take over. The server renders the HTML as usual, so it works before any JavaScript arrives, and the browser loads the module only on pages that use it. The module adds behaviour to the DOM it finds. There is no hydration and no framework runtime.

A [server island](https://sitelo.dev/docs/islands) renders a region on a server when the page is viewed. An enhancement runs code for a region in the browser. The two take the same arguments and work together.

## Write the module

An enhancement is a plain module, anywhere under `src/`. Its default export receives the element and the props. Read what you need from the markup, which the server already rendered:

`src/client/counter.js`

```javascript
// Read what the markup already says.
export default (element) => {
  const output = element.querySelector('output')
  let count = Number(output.value)

  element.querySelector('button').addEventListener('click', () => {
    output.value = String(++count)
  })
}
```

TypeScript works too. Type the function with `Enhancer<Props>` from `sitelo/enhance/client`.

## Place it in a page

Import `enhance()` from `sitelo/enhance`. It takes the same arguments as `island()`: a name, props, the HTML, and options. The HTML goes inside a `<div>` that the module receives.

`src/index.ht.js — Template literal`

```javascript
import { enhance } from 'sitelo/enhance'

export default () => `
  <html>
    <body>
      ${enhance('counter', {}, '<button type="button">Add one</button> <output>0</output>')}
      <script type="module" src="/enhance.js"></script>
    </body>
  </html>
`
```

`src/index.ht.js — ht.js (recommended)`

```javascript
import { html, body, button, fragment, output, script } from 'javascript-to-html'
import { enhance } from 'sitelo/enhance'

export default () =>
  html(
    body(
      enhance(
        'counter',
        {},
        fragment(button({ type: 'button' }, 'Add one'), ' ', output('0')),
      ),
      script({ type: 'module', src: '/enhance.js' }),
    ),
  )
```

`src/index.ht.jsx — JSX`

```jsx
import { enhanceAttributes } from 'sitelo/enhance'

export default function Home() {
  return (
    <html>
      <body>
        <div {...enhanceAttributes('counter')}>
          <button type="button">Add one</button> <output>0</output>
        </div>
        <script type="module" src="/enhance.js" />
      </body>
    </html>
  )
}
```

JSX escapes a string returned by a function, so the JSX tab spreads `enhanceAttributes()` onto the element instead. More on that below.

## Register the modules

The script the page links passes a map of names to modules to `mountEnhancements()`:

`src/enhance.js`

```javascript
import { mountEnhancements } from 'sitelo/enhance/client'

// Every module, listed by hand.
mountEnhancements({
  counter: () => import('./client/counter.js'),
  search: () => import('./client/search.js'),
})
```

You write the map out by hand, on purpose. Each `import()` is an ordinary dynamic import, so the build gives every module its own chunk, and a page downloads only the ones its elements name. In dev, Vite serves them as they are. Because it is plain code, TypeScript checks it and knip follows it.

Pass `when` to decide when a module is imported. It takes the same values as an island:

`enhance-when`

```js
// Load as soon as the page does — the default.
enhance('counter', {}, '…')

// Wait for an idle callback.
enhance('share', {}, '…', { when: 'idle' })

// Wait until it scrolls into view.
enhance('chart', {}, '…', {
  when: 'visible',
  rootMargin: '400px',   // start loading 400px early
})
```

- `'load'` (default) — as soon as the page loads
- `'idle'` — on `requestIdleCallback` (falls back to a timeout)
- `'visible'` — when the element scrolls into view, via IntersectionObserver. `rootMargin` starts it early and defaults to `'200px'`

## Your own element

`enhance()` puts a `<div>` around the markup. When the element itself matters, like a `<form>` with its own `action`, put the attributes on it with `enhanceAttributes(name, props, options)`. It is an object of attributes, so javascript-to-html and JSX take it as attributes, and inside a template literal it becomes the attribute text:

`src/search.ht.js — Template literal`

```javascript
import { enhanceAttributes } from 'sitelo/enhance'

export default () => `
  <html>
    <body>
      <form action="/search" ${enhanceAttributes('search', { minLength: 2 })}>
        <input name="q" type="search">
      </form>
      <script type="module" src="/enhance.js"></script>
    </body>
  </html>
`
```

`src/search.ht.js — ht.js (recommended)`

```javascript
import { html, body, form, input, script } from 'javascript-to-html'
import { enhanceAttributes } from 'sitelo/enhance'

export default () =>
  html(
    body(
      form(
        { action: '/search' },
        enhanceAttributes('search', { minLength: 2 }),
        input({ name: 'q', type: 'search' }),
      ),
      script({ type: 'module', src: '/enhance.js' }),
    ),
  )
```

`src/search.ht.jsx — JSX`

```jsx
import { enhanceAttributes } from 'sitelo/enhance'

export default function Search() {
  return (
    <html>
      <body>
        <form action="/search" {...enhanceAttributes('search', { minLength: 2 })}>
          <input name="q" type="search" />
        </form>
        <script type="module" src="/enhance.js" />
      </body>
    </html>
  )
}
```

The module gets the form itself:

`src/client/search.js`

```javascript
// minLength comes from the page; the element is the form.
export default (form, { minLength }) => {
  const input = form.querySelector('input')

  form.addEventListener('submit', (event) => {
    if (input.value.trim().length < minLength) event.preventDefault()
  })
}
```

## What to pass as props

Props are JSON written into the page and handed to the module as its second argument. Every element on the page carries its own copy, so pass only what the markup does not already say: a setting with no natural place in the HTML, like `minLength` above. A value the page shows, like the counter’s starting number, is better read from the DOM, so the two cannot disagree. Large data belongs in the HTML itself, or in a file the module fetches.

Unlike island props, these never go back to a server, so there is nothing to sign. They are in the page source, though, so keep secrets out of them.

## Checked when you build

The build reads the map out of your `mountEnhancements()` calls and fails on a page that names an enhancement the map does not have:

`sitelo build`

```text
index.html uses enhancement "countr", which no mountEnhancements() call
registers. Did you mean "counter"? Registered: counter, search.
```

`missingAssets: 'warn'` turns that into a warning, as it does for a missing script, and `sitelo` (dev) warns as each page renders. The build has to be able to read the map, so write it as an object literal in the call, or as a `const` in the same file. A map put together at runtime, with a spread or imported from another module, cannot be read, and then nothing is checked. Enhancements inside server islands are rendered at request time, so the build never sees them either.

## State and errors

Each element’s `data-sitelo-enhance-state` moves through `pending` (waiting for its moment), `loading` and `ready`. If the module fails to load or throws, the state is `error`, the server’s markup stays as it was, and the error goes to `mountEnhancements(modules, { onError })`, or to the console. Use the state in CSS when the page should change once the module is in:

`styles.css`

```css
[data-sitelo-enhance-state="ready"] .no-js-hint { display: none; }
```

## Good to know

- The same enhancement can be on a page any number of times. The module is downloaded once and runs once per element, so keep per-element state inside the function, and look things up with `element.querySelector()` rather than across the whole document.
- An enhancement inside a server island is mounted when the island’s HTML arrives: the islands loader dispatches `sitelo:island-load`, and `mountEnhancements()` listens for it. Load both loaders from the same script.
- `mountEnhancements()` never runs a module twice on one element, so it is safe to call again after adding markup yourself.
- Want a framework in one box? Mount it from the module, as in `createRoot(element).render(<Chart {...props} />)`. Only pages with that box download it.
