Technical Manual sections
Reference āŗ Technical Manual āŗ Live pages and components
Page routes are identified by their .page.js, .page.ts, and .page.md extensions (the last for Markdown pages) and result in the creation of PageRoute instances. Each page also has a page socket route.
Alongside Kitten Server and the html parser, page routes are the most complex parts of Kitten as they abstract away a lot of functionality to make authoring easier.
Page routes work in tandem with page socket routes and the KittenPage class (kitten.Page on the global kitten object) to implement Kittenās Streaming HTML workflow. This manual describes how they work. For how to use them, see Streaming HTML, Stateful components, and Event handlers in the reference.
There are two kinds of dynamic page:
Stateless pages, which you write as functions.
Stateful pages, which you write as classes.
A stateless (function-based) page exports a function as its default export. A stateful (class-based) page exports a kitten.Page subclass. (If the default export is a class that doesnāt extend kitten.Page, or there is no default export, the page route throws an error that shows you an example. A stateful page that also exports on⦠functions fails to load with an error that explains that a class page defines its event handlers as methods, and so does any page that exports authorise.) A Markdown page compiles to one or the other: to a kitten.Page subclass if its front matter has a constructor section or stateful: true, and to a function otherwise.
Each kind has its strengths and weaknesses and is useful for different use cases.
Youāll notice that many of the introductory examples and tutorials use stateless pages. This is because writing pages as functions is both more familiar from other JavaScript frameworks and easier to get started with. Itās perfect for quickly prototyping things and for quick experiments.
Stateful pages, on the other hand, involve a bit more overhead but afford better maintainability. You export a kitten.Page subclass as your page and compose it from stateful components (kitten.Component subclasses) that you add with the addChild() method. This enables you to work in a fully object-oriented manner, composing your pages from a DOM-like hierarchy of components, where each component handles the events of the elements it writes. So you can encapsulate event handling and streaming HTML responses within components themselves.
Since you can easily refactor a stateless page into a stateful one, itās always possible to start with the former and refactor to use the latter only if you find that you are going to be maintaining the app/site youāre building long term or if you start hitting the point where refactoring becomes a chore.
Source code:
Sequence Diagram: The live page lifecycle
Live pages are dynamic pages that automatically create a WebSocket connection to their page socket route and use this connection to enable a Streaming HTML workflow, where you respond to events emitted on the client with interface updates generated on the server that you stream to the client.
A page is a live page if its default export is a kitten.Page subclass, or if its default export is a function and the page module also exports at least one event handler. The PageRoute.initialise() method checks every export name against /^on[A-Z]/, so any export whose name starts with on followed by a capital letter makes a stateless page live. Event handlers are written in camelCase and start with on, followed by the name of the event youāre handling (e.g., onUpdate() handles the update event).
By convention, the name of the event is set using the name attribute of the client-side DOM element that the event originates from.
If the element that triggers an event does not have a name attribute, Kitten falls back to using its id attribute instead.
If neither the name nor id attributes exist on a triggering element, Kitten logs an error and drops the event.
Kitten ignores everything after a colon in the name (e.g., name='update:first' emits an update event). It drops an event whose handler would be a lifecycle hook (onConnect, onDisconnect, or onAddToParent) and logs a warning.
If both name and id attributes are present, the name attribute takes precedence. The name attribute is chosen as the recommended attribute for event mapping as more than one element can have the same name, which means that you can have events on multiple elements all result in the same event handler getting called. This is useful, for example, when there are multiple buttons that submit the same form but are meant to result in a different action being performed. Another use case is radio button groups.
Kitten handles the transport of the event from the client, via the pageās WebSocket, to the Kitten page (and any Kitten components on it) on the server.
You add stateful components to a Kitten page, and to other components, using the addChild() method. When kitten.html renders a stateful component, it marks the componentās root element with a data-kitten-component attribute that has the componentās id (and adds the id as the elementās id attribute if it has none). A page route does the same for the pageās root element. Both use one function, markRoot() in src/lib/rootMarking.ts, which takes the first element after any whitespace, comments, <page> tags, <content> tags for page slots, and <style> tags that arenāt inline as the root. The component stores the mark that its root element has as _rootMark, and the remove() method deletes the element with that mark. (When a componentās root element is the root element of a child component, the mark is the childās id.)
The update() method of a component renders the component again and sends the result to the page with the pageās send() method, which morphs it into place. When kitten.html renders a componentās tag for another component or for a page, it saves the props that the tag passes as the componentās _tagProps, and the update() method renders with them. If the tag also passes slot content, what happens next depends on where the tag was written. If it was written during a render (i.e., in an html() method), kitten.html saves the component that wrote it as _tagOwner, and the update() method calls that componentās update() method instead. This ensures that the slot content is rendered again too. If it was written anywhere else (e.g., in an event handler that sends it to the page), kitten.html saves the slot content as _tagSlot, and the update() method renders with it. Note that this canāt work when that slot content contains other components so, in that case, the update() method logs an error and does nothing else. The update() method also logs a warning when the html() method returns more than one root element (as it only morphs the first into place) and, in development, when the root element is preserved (as a morph doesnāt change a preserved element).
Kitten runs your code with its component as the current owner (asOwner() and asRenderingOwner() in src/lib/ownerContext.ts, which use an AsyncLocalStorage): html(), event handlers, lifecycle hooks, and listeners added with addEventHandler(). When kitten.html renders an element that has a ws-send or data-ws-send attribute (which is what the connect attribute becomes), it adds a data-kitten-owner attribute with the current ownerās id, or with kitten-page when the owner is the page that the page route created. With each message, the client-side runtime (kitten-1.js) sends the data-kitten-component value of the closest element that has one as _componentId. It also sends _ownerId: the data-kitten-owner value of the closest element that has either attribute or, when that element has no data-kitten-owner, its data-kitten-component value.
On the server, the KittenPage._messageHandler() method removes the htmx headers from the data, converts key paths in its keys (e.g., person.name) into nested objects, and removes _ownerId from the data. It then calls the event handler of the first of these that has one (_handles()): the page or component in _ownerId, the component with the _componentId, that componentās ancestors, and the page. A component has a handler when it has the on⦠method, and a stateless page also when it has listeners for the eventās name. Kitten calls only that one. It looks each id up in the pageās own component hierarchy (_pathToComponentWithId()), and skips an id that the page doesnāt have. If none of them has a handler, Kitten logs a warning that mentions the handler and the class names of the components it tried.
Stateful and stateless pages use this one path. As the page is the last component Kitten tries, the page handles each event that none of the other candidates handles, including events from messages without a _componentId or an _ownerId.
You do not have to add event listeners to be notified of events. All you have to do is to implement an event handler, using the naming convention outlined above. Kitten calls it with the eventās data, the WebSocket message event, and the message headers (e.g., onUpdate(data, event, headers)). (Kitten also emits every event on the kitten.events event emitter as kittenPageEvent and kittenPageEvent-<page id>, which is useful for debugging.)
Live pages use more resources than other pages. Each live page has its own WebSocket connection, and Kitten keeps an instance of the page in memory (in kitten.pages) for as long as it is connected, along with an instance of each stateful component on it. This applies to stateless live pages too, as Kitten creates a kitten.Page instance to bind their functions to. So, if 1,000 people have a live page open and it has 10 stateful components, Kitten has 1,000 page instances and 10,000 component instances in memory. (Kitten removes a page from memory when its socket closes, or 10 seconds after its response finishes if it never connects.)
Each instance is an ordinary JavaScript object. Its methods are on its classās prototype, so the weight of an instance is that of its own properties: any state you keep in it, plus any references Kitten adds, like the request the page was created for. Given Small Web use cases, this should not present a scalability problem for personal web sites and apps.
(If it does, you can always not use live pages and implement a lighter system that keeps only the data you need for each connection.)
You can create live pages as stateful (class-based) pages or as stateless (function-based) pages. On both, you can use stateless (function-based) components and stateful (class-based) components, but only stateful components have event handlers of their own. An element that a stateless component renders belongs to the page or the stateful component that rendered the stateless component.
A stateful page is always live. A stateless page must be live (i.e., export an on⦠event handler) for you to use stateful components on it: the page route then creates a KittenPage instance and binds your page function to it, so you can call this.addChild(). A stateless page that isnāt live has no page instance.
Flowchart: How PageRoute handles a request
The PageRoute.lazilyLoadedHandler() method handles each GET request for a page:
On the first request, the
initialise()method imports the page module. If the module exportsauthorise, Kitten throws an error, as only HTTP routes take it. If its default export is a class, the class must extendkitten.Pageand the module must not exportonā¦functions (otherwise Kitten throws an error), and the page is stateful and live. If its default export is a function, the page is stateless, and it is live if the module exports anonā¦event handler. If there is no default export, Kitten throws an error.Saves the requestās URL on the route instance (
this.url).If the page is live, stores the requestās session (
storeSessionNow()), so that the pageās socket finds it, and then creates aKittenPageinstance to track its lifecycle, handle events from the client, and stream responses back to it (constructPage(), which removes the page fromkitten.pagesif its constructor throws). For a stateful page, this is an instance of yourkitten.Pagesubclass, with_isAuthoredPageset totrue. For a stateless page, it is a plainKittenPagewhosehtml()method is your default export, bound to the page. Kitten passes the request and the response toconstructPage(), and theKittenPageconstructor sets the pageāsrequestandresponseproperties (which also setspage.session), so they are set before your constructorās own code runs. Kitten records the routeās file on the page (_routeFilePath), so that only this routeās page socket attaches to it, and starts the pageās connection timer (startConnectionTimer()) when the response finishes or closes. If your constructor has ended the response (with a redirect, say), Kitten starts the connection timer and does nothing else.Calls the pageās render function (
page.html()on a live page, the default export otherwise), passing it{ page, request, response }. On a live page, Kitten calls it with the page as the current owner (asRenderingOwner()), and stores the same three values as the pageās_tagProps, so that the pageāsupdate()method passes them to thehtml()method again. On a page that isnāt live,pageisnull.If the page has ended the
responseitself (this is not encouraged, but is possible), does nothing else. If the page returnsundefined, Kitten throws an error.Renders the final page with
renderHtml(), which wraps the result in a valid HTML document with Kittenās libraries, slots, and styles. Kitten escapes a string that the page returns, and logs a warning the first time, as onlykitten.htmlresults are added as markup. On a live page, therenderHtml()method also:adds the htmx, Idiomorph, and htmx WebSocket libraries,
sets
hx-ext='ws,morph'andws-connect='wss://<host><page socket route>?id=<page id>'on the<body>, where the page socket route contains the values of the pageās parameters (including the path that a wildcard matched), and the host is the requestāsHostheader (in production, only when it is the main domain or one of its aliases, andkitten.domainandkitten.portotherwise),sets the
hx-on:htmx:ws-connecting,hx-on:htmx:ws-open, andhx-on:htmx:ws-closeattributes on the<body>, which trigger thews:connecting,ws:connect, andws:disconnectevents on every element that has the__htmxWsEventTargetclass. This is because htmx only raises its WebSocket connection events on the element that has thews-connectattribute.kitten.htmladds the class to elements that have anon:connecting,on:connect, oron:disconnectattribute, and renames those attributes tohx-on:ws:connecting,hx-on:ws:connect, andhx-on:ws:disconnect(see Connection events),marks the pageās root element with
markRoot()(see Live pages), which adds adata-kitten-componentattribute (unless the element already has one, as the root element of a child component does) and the pageāsid(if it has none) to the first element after any leading<page>tags,<content>tags for page slots,<style>tags that arenātinline, and comments, andadds
hx-ext='ws'to every<form>that doesnāt have it.
Responds with status 200 and the
content-type: text/html; charset=utf-8header.Counts the hit for the pageās path in the
pagesstats table (countStat(); see the stats middleware in Middleware).
Page socket routes are special in that, unlike all other types of routes, they do not have their own file on the file system.
Instead, the Routes instance creates a PageSocketRoute for every page file (.page.js, .page.ts, and .page.md) at start-up. It cannot know which pages are live without importing them, which would undo the start-up benefit of lazy loading. Nothing connects to the page socket route of a page that isnāt live.
If a page is called, say, /my.page.js in the site or app being served, the path of its route will be /my/, and the path of its page socket route will be /my/default.socket.
When /my/ is hit and the page is live, the page route:
Lazily loads /my.page.js.
Creates a
KittenPageinstance for this request (the live page).Adds
ws-connect='wss://<host>/my/default.socket?id=<page id>'to the pageās<body>. The htmx WebSocket extension uses this attribute to open the pageās WebSocket when the page loads.Starts the pageās 10-second connection timer when the response finishes or closes (see below).
The KittenPage instance, while being constructed:
Generates a cryptographically secure universally unique identifier (UUID) with
crypto.randomUUID()and prefixes it withkid-(for āKitten IDā) to act as the pageāsid. (TheKittenComponentconstructor does this, so every stateful component has anidin the same format.)Adds itself to the global registry of live pages,
kitten.pages, keyed by itsid.Emits a
kittenPageCreateevent, with{ id }, on thekitten.eventsevent emitter.
The pageās connection timer (startConnectionTimer(), which the page route calls once the response finishes or closes) removes the page from kitten.pages if it hasnāt connected 10 seconds later. This avoids memory leaks when a person reloads a page faster than its WebSocket can connect. Starting it when the response finishes ensures that a page whose render takes more than 10 seconds can still connect.
Then, when the page loads in the browser and connects to its page socket route, the Kitten Serverās upgradeHandler() adds a ws() method to the request, and the page socket route (which passes on a request that isnāt an upgrade, so Kitten responds to it with 404):
If the request has no session cookie (e.g., in a browser that blocks cookies), accepts the connection and closes it normally, without the reload command, so the client doesnāt reconnect.
Looks up the page by the
idin the query (request.query.id,ownPage()). It treats the page as missing unless this route rendered it (its_routeFilePathis the routeās file) for the requestās session. If the page is missing (e.g., because Kitten restarted, because the browser restored the page from its back/forward cache after Kitten removed it, or because the id belongs to another route or session), accepts the connection, sends the page a script that reloads it, and closes the socket.On the first connection to a stateless page, imports the page module again and saves the
onā¦functions it exports as the routeāseventHandlers. (A stateful page already has its event handlers as methods.)Accepts the WebSocket connection (
await request.ws()) and pings it every 30 seconds, terminating the connection if a ping is not answered with a pong.Adds a
closehandler (see below).Checks that the page
idis present, is akid-UUID, and belongs to a page that this route rendered for the requestās session (ownPage(), as in step 2). If not, it sends the page a script that reloads it. Otherwise, it sets the socketāsid(ws.id) to the pageāsid.Binds the event handlers to the page, so
thisin an event handler exported by a stateless page refers to the page, and adds the socket to the routeās list of sockets (sockets). Note that this list contains the sockets of all live pages of this page route.If the page is already connected (e.g., the browser reconnected after a network change), calls the pageās
replaceSocket()method, which moves the page to the new socket and closes the old one without callingonConnect()again. Otherwise, calls the pageāsconnect()method, passing it the socket, the list of sockets, and the bound event handlers.
When the socket closes, the page socket route stops pinging it and removes it from its list of sockets. If the socket still belongs to a page in kitten.pages, it then:
Calls the pageās
_onDisconnect()method, which removes the pageās message listener and callsonDisconnect()on the page and all its descendants, removing the listeners they added withaddEventHandler().Removes the page from
kitten.pages.Emits a generic
kittenPageDeleteevent, with{ id }, and a specifickittenPageDelete-<page id>event on thekitten.eventsevent emitter.
The page, when its connect() method is called:
Saves the socket and the list of sockets it is passed by the page socket route.
Adds the event handlers, if any, to itself as methods. (For a stateless page, these are the
onā¦functions exported from the page module, including anyonConnect()andonDisconnect()lifecycle hooks.)Listens for
messageevents on the socket (_messageHandler()).Creates two
MessageSenderproperties,everyoneandeveryoneElse, that the pageās author uses to send messages to every socket in the list, or to every socket in the list apart from the pageās own, respectively. As the list contains the sockets of all live pages of the page route, whatever their route parameters, these reach every person who has a page of that route open. Before Kitten sends markup to a socket other than the pageās own, it removes thedata-kitten-ownerattributes that have a componentāsid(withoutOwnerStamps()), as those components are on the senderās page. (It leaves the ones that havekitten-page.)Calls
_onConnect(), which marks the page and all its descendants as connected and callsonConnect()on each, passing it{ page, request, response }.Listens for
kittenSessionDeleteon its session and, when it fires, sends the page a script that reloads it and closes the socket.Emits a generic
kittenPageConnectevent as well as a specifickittenPageConnect-<page id>event, both with{ page }, on thekitten.eventsevent emitter.In development, logs the pageās component tree and a line that you can paste into the Kitten REPL to get a reference to the page.
In addition to message sending functionality, the page parses incoming messages and maps them to event handlers (onEventName()) in _messageHandler(), following the rules in Live pages. It ignores messages that arenāt JSON and logs a warning for messages that arenāt objects or have no htmx HEADERS.
Source code: