Enhancements

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 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:

// 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.

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' }),
    ),
  )

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():

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:

// 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
})

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:

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' }),
    ),
  )

The module gets the form itself:

// 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:

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:

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

Good to know