Kitten

Reference sections

The simplest Kitten component is any function that returns kitten.html.

We call this a stateless component and it’s essentially a render function.

A stateless component can be as simple as:

const sayHello = () => kitten.html`
  <h1>Hello</h1>
`

Of course, components without props are not very useful, so component functions usually take a parameter object with properties (or ā€œpropsā€, for short):

const sayAnything = ({ thingToSay = 'Hello' } = {}) => kitten.html`
  <h1>${thingToSay}</h1>
`

console.log(kitten.html`<${sayAnything} thingToSay='Goodbye' />`)

The above example outputs:

<h1>Goodbye</h1>

To learn more about Kitten components, see the following tutorials:

Stateful components are KittenComponent subclasses. Idiomatically, you author your components to extend kitten.Component (which is a reference to the KittenComponent class on the global kitten object).

While stateless components are simple to use, lightweight, and perform well, Kitten’s unique Small Web design means that there are certain routes in your apps that will only ever be hit by one person: the person who owns the web site or app you’re building. This is an amazing simplification compared to Big Web apps that means that you can simplify your authoring experience by maintaining state throughout the render hierarchy of your interfaces (as you would when building a desktop or mobile interface).

Stateful components are far more ergonomic when authoring using Kitten’s Streaming HTML workflow. They make it more ergonomic to listen for events from live pages and carry out precise updates, morphing small bits of your interface in response to events and doing so in a maintainable manner by breaking up your interface up into small, well-encapsulated components.

While stateful components are designed for use in your authenticated routes for the person who owns the Small Web site or app you’re authoring, this shouldn’t put you off of using them for public routes, especially given the ease of authoring they provide. Remember, we’re working with Small Web numbers. If you build a public route in your app using stateful components and then notice performance issues, you can always refactor them using stateless ones. (It’s usually a bad idea to prematurely optimise and doubly so when speaking about a Small Web context.)

Here’s an example of a stateful Kitten component that has a child component (not shown; but inferred to also be a stateful component).

import Child from './Child.component.js'

export default class ParentComponent extends kitten.Component {
  // Child will be strongly-typed via inference.
  child

  constructor () {
    super()
    this.child = this.addChild(new Child())
  }

  override html () {
    return kitten.html`
      <div id='parent'>
        <${this.child} />
      </div>
    `
  }
}

When adding child components, you call the component’s addChild() method from your component’s constructor or later on in your component’s lifecycle. The addChild method handles creating the parent/child relationship as well as firing necessary lifecycle handlers on the child at the right time.

In the constructor of the page that a page route creates, the page’s request, response, and session properties are already set once super() returns, so you can use the request and the session to set up its state and its children.

Every component has a _page property, the page it’s on, and a _parent property, the component you added it to. They’re yours to use inside your component: through this._page, you can reach the page’s session, its request, and its own methods. (The helpers cover the common cases: sendToPage(), toast(), and the page, session, and global event methods. For example, emitPageEvent(name) is this._page.emit(name).) You can read the _page property in the html() method on the first render, including in a component that you added to its parent in the parent’s constructor.

If the html() render function looks familiar, it’s because it’s basically the entirety of a stateless component. In a stateful component, your render function should simply be rendering the current state of your component as reflected in its instance state and/or in the persisted state of your application in its database.

A stateful component renders two kinds of data: its state, which belongs to the component, and its props, which belong to its parent. Keep the component’s state in its properties, and set it up in its constructor. Pass what the parent owns on the component’s tag, as you would to a stateless component. When the component calls its update() method, Kitten renders it again with the props that its tag passed on its last render (see Updating a component).

For example, in this list the page owns the selection and each row owns its name. So the page passes the selected prop on each row’s tag, and each row stores its name in the this.name property:

export default class KittensPage extends kitten.Page {
  constructor () {
    super()
    this.rows = ['Oskar', 'Huppi', 'Tuna'].map(name => this.addChild(new Row(name)))
    this.selectedId = this.rows[0].id
  }

  html () {
    return kitten.html`
      <main>
        <h1>Kittens</h1>
        <ul>${this.rows.map(row => kitten.html`<${row} selected=${row.id === this.selectedId} />`)}</ul>
      </main>
    `
  }

  onSelect ({ id }) {
    this.selectedId = id
    this.update()
  }
}

class Row extends kitten.Component {
  constructor (name) {
    super()
    this.name = name
  }

  html ({ selected = false }) {
    return kitten.html`
      <li aria-current=${selected ? 'true' : 'false'}>
        <form name='rename' connect>
          <label for='name-${this.id}'>New name for ${this.name}</label>
          <input id='name-${this.id}' type='text' name='name' value=${this.name}>
          <button type='submit' aria-label='Rename ${this.name}'>Rename</button>
        </form>
        <button name='select' connect data=${{ id: this.id }} aria-label='${selected ? 'Selected' : 'Select'} ${this.name}'>${selected ? 'Selected' : 'Select'}</button>
      </li>
    `
  }

  onRename ({ name }) {
    this.name = name
    this.update()
  }
}

When a row renames itself and calls its update() method, Kitten renders the row again with the selected prop that the page last passed, so the selected row is still shown as selected. (The Select button is in the row, but the row has no onSelect() handler, so the page handles it. See Where handlers live.)

This is the props example in the Kitten source.

Note that although you are passing a reference to your KittenComponent subclass in the kitten.html, it still works as Kitten knows to use its component property to get a reference to its html() render method. You can, of course, manually pass a reference to it and that will also work. So this is also valid, and equivalent in result to the code above, but more verbose and unnecessary:

override html () {
  return kitten.html`
    <div id='parent'>
      <${this.child.component} />
    </div>
  `
}

See the type safety section for how to get autocompletion when referencing the kitten global.

For a real-world example of the use of the kitten.Component class – and its page-level equivalent, kitten.Page – see the code for the Internal Database page of Kitten’s own Settings app.

Pages and stateful components handle events from the browser in on… handlers.

export default class NotesPage extends kitten.Page {
  notes = []

  constructor () {
    super()
    this.layout = this.addChild(new Layout())
  }

  html () {
    return kitten.html`
      <${this.layout} title='Notes'>
        <form name='addNote' connect>
          <label for='note'>Note</label>
          <input id='note' type='text' name='note'>
          <button type='submit'>Add note</button>
        </form>
        <ul id='notes'>${this.notes.map(note => kitten.html`<li>${note}</li>`)}</ul>
      </>
    `
  }

  onAddNote ({ note }) {
    if (note.trim() === '') return
    this.notes.push(note)
    this.update()
  }
}

class Layout extends kitten.Component {
  isCompact = false

  html ({ SLOT, title }) {
    return kitten.html`
      <page css>
      <main class=${this.isCompact ? 'compact' : 'comfortable'}>
        <header>
          <h1>${title}</h1>
          <button name='toggleDensity' connect>${this.isCompact ? 'Comfortable' : 'Compact'}</button>
        </header>
        ${SLOT}
        <style inline>
          @scope {
            :scope.comfortable { line-height: 2; padding: 2em; }
            :scope.compact { line-height: 1.2; padding: 0.5em; }
            header {
              margin-bottom: 1em;
              h1 { margin: 0; }
              button { max-width: 16ch; padding: 0.3em; }
            }
          }
        </style>
      </main>
    `
  }

  onToggleDensity () {
    this.isCompact = !this.isCompact
    this.update()
  }
}

Here, the form is written in the page (in the slot of its stateful layout), so the page’s onAddNote() handler handles it, even though the form ends up inside the layout. The button is written in the layout, so the layout’s onToggleDensity() handler handles that. When the layout updates itself, it asks the page to update, as the content of the layout’s slot is written in the page (see Updating a component).

This is the stateful layout example in the Kitten source.

A good smell for when to refactor a stateless page into a stateful page is if your page exports lots of on… event handlers and they start to become unmanageable or unsightly, or if each handler has to work out which part of the page its event came from. In a stateful page, you can split the page into stateful components, and each component handles the events of the elements that you write in it.

The update() method calls your component’s html() method again and sends the result to the page, where Kitten morphs it into place.

The kitten.trigger(this, 'eventName', data) method emits an event from your own client-side JavaScript. The first argument is the element the event originates from (its event target). Kitten routes the event as it routes an event from a connected element (see Where handlers live).

In the method signature shown above, this refers to the element itself in an inline event handler. You can also use a reference to any other element when calling it, say, from a global script.

kitten.ready is a promise that resolves when the page is active: when the page’s socket is open on a live page, and at the DOMContentLoaded event otherwise. See Client-side scripts.

A live page loses its connection to the server from time to time (e.g., when a person’s Internet connection drops or when the server restarts), and htmx’s WebSocket extension automatically reconnects when it can. To react to this in the browser (e.g., to show whether the page is online), define the following attributes as event handlers on any element in your kitten.html:

The value of each attribute is a client-side event handler, where this refers to the element itself:

<p>Status: <span on:connect='this.textContent = "Online"'>Connecting…</span></p>

The on:connecting attribute doesn’t run its handler the first time a page connects. It only runs when the page connects again (e.g., after the server restarts). The Alpine.js form (@on:connecting) is not affected. We’re tracking this in issue #500.

In Alpine.js, prefix the attributes with @ (@on:connecting, @on:connect, and @on:disconnect). e.g., Here’s the status indicator of the Kitten Chat example:

export default function statusIndicator () {
  return kitten.html`
    <p>Status: <span
      id='status'
      x-data='${kitten.js`{ status: "Initialising…" }`}'
      @on:connecting='status = "Connecting…"'
      @on:connect='status = "Online"'
      @on:disconnect='status = "Offline"'
      x-text='status'
      :class='${kitten.js`
        status === "Online" ? "online" : status === "Offline" ? "offline" : ""
      `}'>
      Initialising…
    </span></p>

    <style>
      .online {color: green}
      .offline {color: red}
    </style>
  `
}

Note that only live pages have a socket, so these events never happen on any other page.

Kitten also emits all events on the kitten.events event emitter as kittenPageEvent and kittenPageEvent-<pageId>, with the following data: { page, name, handler, id, target, data, headers, event }.

A counter component that changes a persisted count when you press its buttons:

// Initialise the persisted counter object, if necessary.
kitten.db.counter ??= { count: 0 }

class Counter extends kitten.Component {
  override html () {
    return kitten.html`
      <div>
        <div aria-live='assertive'>${kitten.db.counter.count}</div>
        <button name='update' connect data='{value: -1}' aria-label='decrement'>-</button>
        <button name='update' connect data='{value: 1}' aria-label='increment'>+</button>
      </div>
    `
  }

  onUpdate (data: { value: number }) {
    kitten.db.counter.count += data.value
    this.update()
  }
}

See stateful pages and components in the Streaming HTML tutorial for a walkthrough.

Like this? Fund us!

Small Technology Foundation is a tiny, independent not-for-profit.

We exist in part thanks to patronage by people like you. If you share our vision and want to support our work, please become a patron or donate to us today and help us continue to exist.