Skip to content
spaceport / docs
The Spaceport handbook

HUD-Core.js — API Reference

Installation

<script defer src='https://cdn.jsdelivr.net/gh/spaceport-dev/hud-core.js@latest/hud-core.min.js'></script>

Current version: v1.1.3


on-* Event Attributes

Adding an on-* attribute to any HTML element binds that DOM event to a server round-trip via fetchDataAndUpdate(). The attribute value is a server action endpoint URL, generated by Launchpad's ${ _{ ... } } syntax.

Note that the on- prefix uses a dash, distinguishing Launchpad server events from standard inline DOM event handlers (e.g., on-click vs onclick).

Mouse Events

Attribute DOM Event Description
on-click click Element was clicked
on-dblclick dblclick Element was double-clicked
on-mousedown mousedown Mouse button pressed on element
on-mouseup mouseup Mouse button released on element
on-mouseover mouseover Mouse pointer entered element (bubbles)
on-mouseout mouseout Mouse pointer left element (bubbles)
on-mouseenter mouseenter Mouse pointer entered element (no bubble)
on-mouseleave mouseleave Mouse pointer left element (no bubble)
on-mousemove mousemove Mouse pointer moved within element
on-wheel wheel Mouse wheel scrolled on element
on-contextmenu contextmenu Right-click context menu triggered

Keyboard Events

Attribute DOM Event Description
on-keydown keydown Key was pressed down
on-keyup keyup Key was released
on-keypress keypress Key was pressed (deprecated in browsers, but supported)

Input & Form Events

Attribute DOM Event Description
on-input input Element value changed (fires on each keystroke)
on-change change Element value committed (fires on blur for text inputs). For <input> elements, also adds an Enter-key listener that blurs the input.
on-submit submit Form was submitted. Automatically calls event.preventDefault() on <form> elements.
on-select select Text was selected in an input or textarea
on-focus focus Element received focus
on-blur blur Element lost focus
on-focusin focusin Element or descendant received focus (bubbles)
on-focusout focusout Element or descendant lost focus (bubbles)
on-formblur formblur Custom event. Fires when focus leaves a <form> entirely (not just moving between inputs within the form).

Drag & Drop Events

Attribute DOM Event Description
on-drag drag Element is being dragged
on-dragstart dragstart Drag operation started
on-dragend dragend Drag operation ended
on-dragenter dragenter Dragged element entered a drop target
on-dragleave dragleave Dragged element left a drop target
on-dragover dragover Dragged element is over a drop target
on-drop drop Element was dropped on a drop target

Touch Events

Attribute DOM Event Description
on-touchstart touchstart Touch point placed on element
on-touchmove touchmove Touch point moved on element
on-touchend touchend Touch point removed from element
on-touchcancel touchcancel Touch event interrupted

Lifecycle & Custom Events

Attribute DOM Event Description
on-load load Element was loaded. Automatically dispatched on page load for elements that have this attribute.
on-beforeunload beforeunload Page is about to be unloaded
on-nudge nudge Custom event. Dispatched programmatically via the @nudge Transmission action.

Commented-Out Events

The following events are defined in HUD-Core's source but are currently disabled. They can be re-enabled by uncommenting them in the builtInEvents array:


Data Payload (What Gets Sent to the Server)

When an on-* event fires, HUD-Core constructs a JSON payload and POSTs it to the server action endpoint. This data is available in the server closure via the t parameter (e.g., _{ t -> ... }).

Element Value

The value property is determined intelligently based on the element type:

Element Type Value Sent
Checkbox / Radio value attribute (only if checked)
Multi-select <select> Array of selected option values
File input (single) { name: "file.pdf", data: "data:application/pdf;base64,..." }
File input (multiple) Array of { name, data } objects (each data is a data: URL)
Input / Textarea / Select .value property
Other elements (non-form) Trimmed innerHTML with whitespace collapsed

Element Metadata

Always included in the payload:

Key Type Description
tagName String Tag name of the active target (uppercase)
classList Array<String> CSS classes on the active target
innerText String Trimmed visible text content
textContent String Trimmed text content (including hidden)
elementId String The id attribute (only if present)

Mouse Event Data

Included when the event carries mouse coordinates:

Key Type Description
clientX, clientY Number Position relative to viewport
pageX, pageY Number Position relative to document
screenX, screenY Number Position relative to screen
offsetX, offsetY Number Position relative to target element
movementX, movementY Number Movement since last event
button Number Which mouse button (0=left, 1=middle, 2=right)
buttons Number Bitmask of pressed buttons

Keyboard Event Data

Key Type Description
key String The key value (e.g., "Enter", "a")
keyCode Number Numeric key code
shiftKey Boolean Only included if true
ctrlKey Boolean Only included if true
altKey Boolean Only included if true
metaKey Boolean Only included if true (Cmd on Mac)
repeat Boolean Only included if true (key held down)

Form Data

If the active target is inside a <form>, all named form inputs are automatically included. Each input's name attribute becomes a key in the payload.

Input Type Value Sent
Text / Textarea / Select String value
Date / DateTime / Month / Week / Time Milliseconds since epoch (number)
Checkbox / Radio Boolean (true/false)
File (on submit) Array of { name, value: "data:<type>;base64,..." }
File (non-submit) Array of { name, value: null }
Multi-select Array of selected values
Custom [name] elements .value property

Data Attributes

All data-* attributes from both event.currentTarget and the active target are included as top-level keys with the data- prefix stripped:

<button data-user-id="123" data-role="admin" on-click=${ _{ t ->
    // t['user-id'] == "123" (the data- prefix is stripped without camelCase conversion)
    // t.role == "admin"
}}>Edit</button>

Note: The key is the attribute name with data- removed. data-user-id becomes user-id in the payload (the HTML dataset camelCase conversion does not apply here).

URL Query Parameters

All query parameters from the current page URL are automatically included as top-level keys:

Page URL: /items?page=2&sort=name
Payload: { ..., "page": "2", "sort": "name" }

Included Data (include Attribute)

The include attribute on the active target element explicitly adds external data to the payload. Keys are separated by commas, semicolons, or spaces.

Prefix Source Example
~ localStorage include="~theme" sends localStorage.getItem('theme')
~~ sessionStorage include="~~token" sends sessionStorage.getItem('token')
(none) Element attribute, then localStorage, then sessionStorage include="id" sends the id attribute value
all-attributes All attributes on the element include="all-attributes" sends every attribute
<button include="id, ~theme, ~~session-token" on-click=${ _{ t ->
    // t.id, t.theme, t['session-token']
}}>Send</button>

Content-Editable Data

If the active target has contentEditable set to true, the payload includes contentEditable: "true".

Bind Attribute

If the active target has a bind attribute, its value is included as bind in the payload.


The target Attribute

The target attribute determines which DOM element receives the Transmission response. HUD-Core first checks the element itself, then walks up the DOM tree looking for an ancestor with a target attribute.

Relative Targets

Value Target Element
self The element with the on-* attribute
outer Same as self, but single-value Transmissions replace outerHTML instead of innerHTML
none No target. The server action executes but no DOM update occurs.
parent Immediate parent element
grandparent Parent of the parent element
next Next sibling element
previous Previous sibling element
nextnext Next sibling's next sibling
previousprevious Previous sibling's previous sibling
first First child element
last Last child element

Insertion Targets

These targets create a new element and make it the target. Use the wrapper attribute to specify the tag type (default: div).

Value Behavior
append Inserts new element as last child
prepend Inserts new element as first child
after Inserts new element after the current element
before Inserts new element before the current element
<ul on-click=${ _{ '<li>New item</li>' }} target="append" wrapper="li">
    Add Item
</ul>

Indexed Targets

Value Required Attribute Behavior
nth-child index="N" Targets the Nth child (0-based)
nth-sibling index="N" Targets the Nth sibling (0-based)
nth-parent index="N" Targets the Nth child of the grandparent (0-based)

Selector Targets

Value Behavior
> selector querySelector on the current element (descendant search)
< selector closest() on the current element (ancestor search)
#id or any CSS selector document.querySelector() on the entire document

The source Attribute

The source attribute controls which element provides the data payload, overriding the default behavior.

Value Behavior
(not set) Data comes from event.currentTarget (the element with on-*)
auto Explicitly sets data source to event.target (the actually clicked element)
strict Event only fires if event.target === event.currentTarget. Clicks on child elements are ignored.
CSS selector Walks up from event.target to find a matching ancestor (stops at currentTarget). Falls back to ID-based document.querySelector if selector starts with #.

The wrapper Attribute

Used with insertion targets (append, prepend, after, before) to specify the HTML tag type of the newly created element. Defaults to div.

<ul target="append" wrapper="li" on-click=${ _{ 'New item' }}>Add</ul>

Transmission Response Formats

Array Transmission

An array of strings applied to the payload target. Each string is either a class operation or an action.

Class Operations:

Prefix Behavior Example
(none) Toggle class 'active' — adds if absent, removes if present
+ Add class '+active'
- Remove class '-active'

Actions in Arrays:

Action Behavior
@click Calls .click() on the target
@focus Calls .focus() on the target
@blur Calls .blur() on the target
@select Calls .select() on the target
@submit Calls .submit() on the target
@reset Calls .reset() on the target
@remove Removes the target from the DOM
@show Restores the element's display (from stored x-display attribute)
@hide Stores the current display in x-display attribute, sets display: none
@scroll-to Calls .scrollTo() on the target
@clear Clears .value or .innerHTML on the target
@reload Reloads the page (window.location.reload())
@back Navigates back (window.history.back())
@forward Navigates forward (window.history.forward())
@print Opens the print dialog (window.print())

Map Transmission

A key-value object where each entry is an instruction. This is the most powerful format.

Content & Attribute Operations:

Key Behavior
value Sets .value property on the target
innerHTML Sets .innerHTML on the target
outerHTML Replaces the entire target element
innerText Sets .innerText on the target
append Inserts HTML as last child (beforeend)
prepend Inserts HTML as first child (afterbegin)
insertBefore Inserts HTML before the target (beforebegin)
insertAfter Inserts HTML after the target (afterend)
Any other key (no prefix) Sets as an HTML attribute. If value is null, removes the attribute.

Style & Class Prefixes:

Prefix Behavior Value
& Sets inline CSS style property '&backgroundColor': 'yellow'
+ Adds CSS class Value determines target: null/default = payload target, 'this' = event.target, 'it' = event.currentTarget, 'source' = active target
- Removes CSS class Same targeting as +
* Sets a data-* attribute '*userId': '123' sets dataset.userId

Selector-Based Entries:

Key Format Behavior
#id Sets innerHTML on the element with that ID
> selector Sets innerHTML on a descendant of the active target
< selector Sets innerHTML on an ancestor found via closest()

Storage & URL Operations:

Prefix Behavior
? Sets a URL query parameter without page reload (uses pushState)
~ Sets a localStorage item
~~ Sets a sessionStorage item

Action Operations (Map):

Actions in a Map Transmission support targeting via their value:

Key Behavior Additional Notes
@click Triggers .click()
@focus Triggers .focus()
@blur Triggers .blur()
@select Selects text. For non-input elements, uses Range API.
@end Moves cursor to end of input or contenteditable element
@submit Triggers .submit() on a form
@reset Triggers .reset() on a form
@show Restores display from stored x-display attribute. Uses .show() on <dialog>.
@hide Stores current display in x-display, sets display: none. Uses .hide() if available.
@open Opens <details> (sets open attr), <dialog> (calls .show()), or window.open() for URLs
@close Closes <details> (removes open), <dialog> (calls .close()), or window.close() for value 'window'
@remove Removes element from DOM
@clear Clears .value or .innerHTML
@scroll-to Calls .scrollTo(value) on target Value passed as argument
@scroll-by Calls .scrollBy(value) on target Value passed as argument
@scroll-into-view Calls .scrollIntoView(value) on target Value passed as argument (e.g., true or options object)
@redirect Navigates to URL Value is the URL string
@reload Reloads the page
@replace Replaces the current URL in history without navigation Value is the new URL
@back Navigates back in history
@forward Navigates forward in history
@download Triggers a file download Value is the file URL
@print Opens the print dialog
@alert Shows a browser alert() Value is the message string
@log Logs to browser console (console.log)
@table Logs to browser console (console.table)
@nudge Dispatches a custom nudge event that bubbles Target determined by value

Single Value Transmission

When the server returns a plain string (not JSON), it is treated as a single value:


documentData / document.data

A globally accessible reactive data object. Setting properties triggers automatic updates on all bound elements.

Setting Data

// Direct property assignment
documentData.userName = 'Alice'

// Nested objects (created automatically as reactive proxies)
documentData.user = { name: 'Alice', role: 'admin' }

// Dot-notation deep set
setDocumentDataProperty('user.profile.name', 'Alice')

Binding Elements

Elements with a bind attribute automatically display the bound value:

<span bind="userName">Loading...</span>
<input bind="user.profile.name">

Supports dot notation for nested values. For form elements (INPUT, TEXTAREA, SELECT, PROGRESS, METER), the .value property is updated. For other elements, innerHTML is updated. If the element has a custom .setValue() method (as with Server Elements), that method is called instead.

hudWrite(newValue)

An HTMLElement prototype method. Writes a value to documentData at the path specified by the element's bind attribute.

element.hudWrite('new value')
// Equivalent to: setDocumentDataProperty(element.getAttribute('bind'), 'new value')

hudRead()

An HTMLElement prototype method. Reads the value from documentData at the path specified by the element's bind attribute.

let value = element.hudRead()
// Returns the value at the path, or undefined if the path doesn't exist

Server-Side Population

The server populates documentData through CDATA comment nodes. HUD-Core scans for these on page load and whenever new DOM nodes are added. The CDATA can either replace or append (merge) data:

<!-- <![CDATA[{"userName": "Alice", "count": 42}]]> -->
<!-- <![CDATA[{"append": true, "newField": "value"}]]> -->

sendData(id, data)

Sends data to the server over the WebSocket connection.

Parameter Type Description
id String The handler-id that routes the message to the correct server-side @Alert handler
data Object Key-value pairs to send as the message payload
sendData('chat-message', { text: 'Hello!', room: 'lobby' })

Behavior:


HREF System

Any non-<a> element with an href attribute is automatically set up with click and keyboard navigation.

<div href="/dashboard">Go to Dashboard</div>

Behavior:


Loading State

During a server round-trip, HUD-Core adds a loading="true" attribute to the payload target (or the active target if no payload target exists). This attribute is removed when the response arrives.

/* Style loading state */
[loading] {
    opacity: 0.5;
    pointer-events: none;
}

Fatal Error Handling

If the server response starts with <fatal, the element is marked with a fatal-error attribute. Subsequent events on that element are silently ignored to prevent cascading errors.


History Management

HUD-Core listens for popstate events (browser back/forward navigation) and reloads the page.


Element Lifecycle Hooks

HUD-Core supports lifecycle callbacks on DOM elements via JavaScript properties:

Property When Called Arguments
element.mutated When the element is added to the DOM via mutation (node) — the element itself
element.removed When the element is removed from the DOM (node) — the element itself
element.attributeChanged When an attribute on the element changes (node, attributeName, oldValue, newValue)

Server Element Lifecycle

Elements with an element-id attribute (Server Elements) receive special treatment:


Event Propagation

All on-* events call event.stopPropagation() to prevent the event from bubbling. This prevents unintended duplicate handling when nested elements both have on-* attributes.

Make the docs better.Edit this page on GitHub