Reference sections
Reference āŗ Components
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.
A connected element (an element with a
connectattribute) with attributename='update'emits anupdateevent and Kitten routes this to anonUpdate()handler.An element without a
nameattribute emits an event named after itsidattribute. If the element has neither, Kitten logs an error and drops the event.Kitten ignores everything after a colon in the name. e.g.,
name='update:first'emits an event calledupdate.A handler has three positional parameters: the eventās data, the WebSocket message event and the message headers. e.g.,
onUpdate(data, event, headers). In htmx messages,headers['HX-Trigger-Event']contains the name of the DOM event that triggered the message.
On a stateful page or component, a handler is a method. On a stateless page, a handler is an exported function. Kitten binds it to the live page, so
thisrefers to thekitten.Pageinstance. Use afunctiondeclaration or an expression, not an arrow function (arrow functions ignore the binding).Write an elementās handler in the page or component that you write the element in. Each element that sends events (one with a
connect,ws-send, ordata-ws-sendattribute) belongs to the page or component that you write it in, and Kitten calls that page or componentās handler first.When that page or component has no handler for the event, Kitten delivers the event to the component around the element (the nearest one whose root element contains it), then outward through that componentās ancestors, and last to the page. (In the list example, the page handles the Select buttons that you write in each row.) When none of them has a handler, Kitten logs a warning:
Warning: cannot route <event> event: there is no event handler method called <handler> in <classes>.So a page inside a stateful layout handles the elements that you write in the page, even though they end up in the layoutās slot, and the layout handles its own. A page canāt override a layoutās handlers: for an element that you write in the layout, Kitten calls the layoutās handler, even when the page has a handler of the same name.
Markup that your page broadcasts with the
this.everyone.send()orthis.everyoneElse.send()method belongs to each personās own page. So a button in it is handled by the page of whoever presses it.An event from the browser calls
onā¦()methods. On a stateless page, it also calls every listener on the page for the event (e.g., one added with thepage.on()method, or one that a component on the page added with theaddPageEventHandler()method). It calls no listener on a stateful page or on a component.
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.
onConnect(pageDetails)called when the page socket connects. Itās also called when a component thatās already connected is added to the page.onDisconnect(pageDetails)called when the page socket disconnects and when the component is removed.onAddToParent()called when theaddChild()method adds the component to its parent.The
pageDetailsparameter is{ page, request, response }.connect,disconnect, andaddToParentare reserved names. Donāt use them as event names.Add listeners in the
onConnect()hook, not in your constructor.
addEventHandler(target, eventName, handler)listens foreventNameon any event emitter, withthisbound to the component. Kitten removes the listener when the component disconnects.addPageEventHandler(eventName, handler),addSessionEventHandler(eventName, handler), andaddGlobalEventHandler(eventName, handler)listen on the page, on the session, or on thekitten.eventsevent emitter, withthisbound to the component. Kitten removes the listener when the component disconnects.emitPageEvent(eventName, ...args),emitSessionEvent(eventName, ...args)andemitGlobalEvent(eventName, ...args)emit an event on the page, on the session, or on thekitten.eventsevent emitter.update()renders the component again, with the props and slot content of its tag, and streams it to the page, morphing it into place. See Updating a component.sendToPage(html)streams Kitten HTML with a single root element to the page. Itās morphed in place unless its root element overrides the default behaviour by including aswap-targetattribute (syntactic sugar forhx-swap-oob) or is a<script>.remove()removes the component from the page and from its parent, disconnecting it. It deletes the componentās root element from the page, including when that element is the root element of a child component.removeChild(component)removes a child from the componentās children and, if the child is connected, disconnects it: Kitten calls itsonDisconnect()hook and removes the listeners that it added with theaddEventHandler()method and its helpers. Unlike theremove()method, it leaves the childās element on the page.
The update() method calls your componentās html() method again and sends the result to the page, where Kitten morphs it into place.
Kitten renders the component with the props that its tag passed on its last render. So a component that updates itself shows its parentās data as it was when the parent last rendered.
Pass what the parent owns on the componentās tag, and keep what the component owns in its own properties (see Stateful components).
When a componentās tag passes slot content, the
update()method asks the component whosehtml()method rendered the tag to update instead, so the slot content is up to date. This renders more than the component that calledupdate(). For example, when the stateful layout in the notes example updates itself, the page renders again.When you send a tag with slot content from outside an
html()method (e.g., from an event handler), theupdate()method uses the slot content it was sent with again. If that slot content contains another stateful component, theupdate()method sends nothing and logs an error:ā Cannot update <component>: its tag was sent from outside an html() method with other components in its slot. Render the tag in the html() method of the component that adds it.Pass markup to a component in its slot, or in a named slot (
<content for='ā¦'>). Markup in a prop is an error: rendering the tag throws an error that mentions the prop and the named slot to use.Give your component a single root element. When the
html()method returns several, theupdate()method only morphs the first into place, and logs a warning:ā ļø <component>: html() returns <number> root elements. update() only morphs the first into place. Wrap them in one root element.To preserve the text that a person has typed into a field when the component updates, give the field the
preserveattribute (see Preserving elements).Kitten doesnāt merge
update()calls: each call renders and sends. (See issue #477.)
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:
on:connecting: The pageās socket is connecting.on:connect: The pageās socket is open.on:disconnect: The pageās socket has closed.
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.