Server Elements — API Reference
Element Trait
import spaceport.launchpad.element.Element
The core trait that all Server Elements implement. Defined in spaceport.launchpad.element.Element. Classes implementing this trait become usable as custom HTML elements in Launchpad templates.
Properties
| Property | Type | Default | Description |
|---|---|---|---|
_bindings |
Map |
[:] |
Reactive bindings registered by this element. Managed internally. |
_source |
String |
'' |
Reserved for debugging. Not currently implemented. |
_handler |
String |
'' |
Aggregated JavaScript code block generated during initialize(). Becomes a <script> tag in the rendered output. |
_handlerMap |
Map |
[:] |
Maps generated function IDs to @Bind method closures. Used to route WebSocket calls to the correct server method. |
_id |
String |
'uninitialized' |
Unique identifier assigned to each element instance. Set by Launchpad during template processing (6-character random ID). Used as the element-id attribute in the DOM. |
_reactions |
Map |
[:] |
Reactive expression subscriptions belonging to this element. Managed internally. |
_style |
String |
'' |
Aggregated CSS from @CSS-annotated fields. Wrapped in <style> tags during initialize(). |
_scopedStyle |
String |
'' |
Aggregated CSS from @ScopedCSS-annotated fields, with selectors rewritten to scope to the element instance. Wrapped in <style> tags during initialize(). |
_initialized |
boolean |
false |
Whether initialize() has been called. Prevents double initialization. |
_prepend |
String |
'' |
Aggregated HTML from @Prepend-annotated fields. Injected once per element type into <head>. |
_scopedPrepend |
String |
'' |
Aggregated HTML from @ScopedPrepend-annotated fields. Injected before this specific element instance. |
_append |
String |
'' |
Aggregated HTML from @Append-annotated fields. Injected once per element type after </body>. |
_scopedAppend |
String |
'' |
Aggregated HTML from @ScopedAppend-annotated fields. Injected after this specific element instance. |
client |
Client |
(set by Launchpad) | The Client object for the current session. Provides access to authentication state, user document, and permissions. |
dock |
Cargo |
(set by Launchpad) | The session-scoped Cargo object. Shared persistent key-value store for user-specific data. |
launchpad |
Launchpad |
(set by Launchpad) | Reference to the parent Launchpad instance. Provides access to the binding context. |
Methods
prerender(String body, Map<String, String> attributes)
Required. Called server-side during page rendering to produce the element's inner HTML.
| Parameter | Type | Description |
|---|---|---|
body |
String |
The inner HTML content between the element's opening and closing tags in the template |
attributes |
Map<String, String> |
All attributes from the element's HTML tag, as string key-value pairs |
Returns: String — the rendered inner HTML of the element.
The attributes map is enhanced with convenience methods:
attributes.getInteger(key)— returns the value as anIntegerattributes.get(key)— returns the value as aString(standard map access)attributes.containsKey(key)— checks for the presence of an attribute (including boolean attributes likecheckedordisabled)
String prerender(String body, Map attributes) {
def color = attributes.color ?: 'blue'
def size = attributes.containsKey('large') ? '2em' : '1em'
return "<span style='color: ${color}; font-size: ${size}'>${body}</span>"
}
initialize()
Called automatically by Launchpad after prerender(), but only once per element instance (guarded by _initialized). Processes all annotation-based properties to build the aggregated CSS and JavaScript for the element.
You should not normally call this method directly. It is invoked by the framework during template rendering.
Processing order within initialize():
@CSSfields — aggregated into_style, wrapped in<style>tags@ScopedCSSfields — aggregated into_scopedStylewith instance-scoped selectors@Prependfields — aggregated into_prepend@ScopedPrependfields — aggregated into_scopedPrepend@Appendfields — aggregated into_append@ScopedAppendfields — aggregated into_scopedAppend@Bindmethods — generates client-side JavaScript proxy functions and registers server-side handlers in_handlerMap@Javascriptfields — appended to the JavaScript handler block- Wraps JavaScript in a
<script>tag only when@Bindor@Javascriptcontributes a handler; static elements emit no empty script wrapper
getTagName()
Returns the kebab-case version of the class's simple name. Used as the HTML tag name in the rendered output and as the form that matches <g:foo-bar> tags in templates.
// For class StarRating:
getTagName() // returns "star-rating"
Distinct from the static getName() below: for multi-word class names, getTagName() is kebab-case and getName() is the lowercase concatenation. For single-word names the two are identical.
grab(String reactiveVariableName)
Retrieves a reactive variable from the parent Launchpad template's binding context by name.
| Parameter | Type | Description |
|---|---|---|
reactiveVariableName |
String |
The name of the variable in the template binding |
Returns: The value of the reactive variable.
_(Closure c)
Shorthand for creating a Launchpad server action binding (equivalent to calling launchpad.bind(c) from within the element). Used in prerender() to create on-click, on-blur, and similar event handlers.
String prerender(String body, Map attributes) {
return """<button on-click=${ _{ counter.inc() }}>Increment</button>"""
}
getName() (static)
Returns the lowercase concatenation of the class's simple name. StarRating → "starrating". This is not the form that matches <g:> tags — use getTagName() for the kebab-case version ("star-rating") used in templates.
For single-word class names (Counter, Highlight) the two methods return the same value; they diverge only on multi-word names.
Cross-Element References
All Element classes in a single Launchpad's elements/ directory share one GroovyClassLoader, so they are mutually visible by class name. An Element's prerender() may call static methods or read static fields on its siblings:
class Page implements Element {
String prerender(String body, Map attributes) {
// Sibling Element class — visible because of the shared loader.
String sidebarHtml = Sidebar.renderHtml(client, '/path')
return "<div>${sidebarHtml}<main>${body}</main></div>"
}
}
Use this for shared rendering helpers that conceptually belong to a specific Element (e.g. Sidebar.renderHtml(...)). Helpers that aren't owned by any one Element can still live in modules/.
Emitting <g:> Tags from prerender()
The string returned by prerender() is scanned for <g:> patterns. Each tag found gets instantiated and registered into the same lifecycle as a template-authored tag — full CSS/handler injection, recursive nesting, qualified-syntax resolution. This means an Element can compose other Elements declaratively rather than concatenating their rendered HTML:
class Page implements Element {
String prerender(String body, Map attributes) {
return "<div><g:sidebar></g:sidebar><main>${body}</main></div>"
}
}
The outer parseElements loop caps at 16 passes, so a self-emitting Element (<g:foo> inside foo's own prerender) terminates safely rather than hanging.
Annotations
All annotations are defined in the spaceport.launchpad.element package with @Retention(RetentionPolicy.RUNTIME). They are marker annotations with no attributes.
import spaceport.launchpad.element.*
@CSS
Marks a field whose value contains CSS to be injected globally for this element type. The CSS is aggregated from all @CSS fields during initialize() and wrapped in a <style> tag.
Target: Fields (String or GString)
Behavior:
- Multiple
@CSSfields are concatenated in declaration order - The
&character at the start of the CSS is replaced with the element's tag name, enabling self-referencing styles - CSS is injected into the rendered page via a
<style>tag placed at the element's style marker position - The CSS is global — all instances of the element type share the same styles
Example:
@CSS String styles = """
& {
display: inline-flex;
gap: 0.5em;
span {
font-size: 2em;
color: goldenrod;
}
}
"""
If the element's class is StarRating, the & is replaced with star-rating, producing:
star-rating {
display: inline-flex;
gap: 0.5em;
span {
font-size: 2em;
color: goldenrod;
}
}
Notes:
- You can use
staticon the field (common pattern when CSS does not reference instance state) - No
<style>tags needed — the framework wraps the CSS automatically - Modern nested CSS syntax is supported (nesting selectors inside
&)
@ScopedCSS
Marks a field whose value contains CSS that is scoped to a specific element instance using its element-id attribute.
Target: Fields (String or GString)
Behavior:
- Each CSS selector is automatically prefixed with
[element-id=<id>] >where<id>is the unique instance ID - Selectors separated by commas are each individually prefixed
- The
&reference (when combined with the scoped selector) resolves to the specific instance, not the tag name - Useful when multiple instances of the same element need different styles, or to avoid style leakage between instances
Example:
@ScopedCSS String scopedStyles = """
.item {
padding: 1em;
}
.item:hover, .item:focus {
background: var(--lt-blue);
}
"""
Produces (for an instance with element-id="a1b2c3"):
[element-id=a1b2c3] > .item {
padding: 1em;
}
[element-id=a1b2c3] > .item:hover, [element-id=a1b2c3] > .item:focus {
background: var(--lt-blue);
}
@Javascript
Marks a field whose value contains JavaScript code to be injected on the client side.
Target: Fields (String, GString, or def)
Behavior depends on the field name and content:
Special field: constructed
A function that receives the DOM element as its parameter. Called after the element's HTML has been inserted into the DOM and all other @Javascript properties have been evaluated.
@Javascript String constructed = /* language=js */ """
function(element) {
element.listen('click', function(e) {
console.log('Element clicked');
});
}
"""
Special field: deconstructed
A function that receives the DOM element as its parameter. Called when the element is removed from the DOM. Used for cleanup of external resources (timers, global event listeners, observers).
@Javascript String deconstructed = /* language=js */ """
function(element) {
if (element._cleanup) element._cleanup();
}
"""
Named function properties
If the field value starts with function(, it becomes a method on the client-side element instance. The field name becomes the method name. Inside the function, this refers to the DOM element.
@Javascript def getValue = /* language=javascript */ """
function() {
return this.querySelector('input').value;
}
"""
@Javascript def setValue = /* language=javascript */ """
function(val) {
this.querySelector('input').value = val;
}
"""
These are callable from client-side JavaScript:
document.querySelector('my-element').getValue();
document.querySelector('my-element').setValue('hello');
Inline execution
If the field value does not start with function(, it executes as inline JavaScript when the element initializes on the client. References to this are automatically rewritten to reference the element instance.
@Javascript String setup = """
this.dataset.initialized = 'true';
console.log('Element ready:', this.tagName);
"""
Notes:
- The
/* language=js */or/* language=javascript */comment is a hint for IDE syntax highlighting and is stripped during processing - All JavaScript is aggregated and wrapped in a single
<script>tag per element instance - Inline JavaScript executes before
constructedis called - The element is referenced on the client as
element_<id>(a global variable onwindow)
@Bind
Marks a method as callable from client-side JavaScript via WebSocket. The framework generates a JavaScript proxy function on the element instance that, when called, sends a WebSocket message to the server to invoke the Groovy method.
Target: Methods
Behavior:
- For zero-parameter methods: the client-side proxy takes no arguments
- For methods with parameters: the client-side proxy accepts arguments, which are serialized as JSON and sent to the server. The last argument can be a callback function.
- After the bound method executes on the server, the framework checks all registered reactions and pushes any changed payloads to the client
- The return value is sent back to the client. If a callback was provided, it is invoked with the return value.
Example:
@Bind def getValue() {
return counter.get()
}
@Bind def setValue(def value) {
counter.set(value.toInteger())
}
Client-side usage:
// Fire-and-forget
document.querySelector('counter').setValue(42);
// With callback for return value
document.querySelector('counter').getValue(function(result) {
console.log('Current value:', result);
});
Notes:
- Bound methods execute on the server in the context of the element instance
- The element's
client,dock, andlaunchpadare available within bound methods - The WebSocket connection must be established (HUD-Core loaded) for
@Bindto function - Each bound method gets a unique random function ID to prevent collisions
@Prepend
Marks a field whose value is HTML to be injected at the beginning of the page (inside <head> if present, otherwise at the top of the output). Injected once per element type, regardless of how many instances appear on the page.
Target: Fields (String or GString)
Common use case: Loading external CSS or JavaScript libraries required by the element.
@Prepend String prepend = """
<link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
<script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>
"""
@ScopedPrepend
Marks a field whose value is HTML to be injected immediately before this specific element instance in the DOM. Unlike @Prepend, this is per-instance.
Target: Fields (String or GString)
@Append
Marks a field whose value is HTML to be injected at the end of the page (after </body> if present, otherwise at the bottom of the output). Injected once per element type.
Target: Fields (String or GString)
@ScopedAppend
Marks a field whose value is HTML to be injected immediately after this specific element instance in the DOM. Unlike @Append, this is per-instance.
Target: Fields (String or GString)
Template Integration
Using Elements in GHTML Templates
Elements are referenced using the g: prefix followed by the kebab-case element name:
<g:element-name attribute1="value1" attribute2="value2">
Inner body content
</g:element-name>
Elements must have both opening and closing tags.
Attribute Passing
All attributes on the element tag are passed to prerender() as a Map<String, String>:
<g:star-rating value="4" color="gold" readonly></g:star-rating>
In prerender():
String prerender(String body, Map attributes) {
// attributes = [value: "4", color: "gold", readonly: ""]
def stars = attributes.getInteger('value') ?: 0
def isReadonly = attributes.containsKey('readonly')
}
Boolean attributes (like readonly, disabled, checked) have an empty string value but can be detected with containsKey().
Passing Server-Side Values as Attributes
Use Groovy expressions to pass dynamic values. For simple string values:
<g:page-notes route="${ r.context.target }"></g:page-notes>
For passing closures or complex objects as attributes, use the server action binding syntax:
<g:stat-card value="${ _{ myList }}" transform="${ _{ myTransformClosure }}" color="blue" icon="users">
Total Users
</g:stat-card>
The ${ _{ expression }} syntax creates a server action that is evaluated when the attribute is resolved, allowing complex Groovy objects (lists, closures, Cargo objects) to be passed into elements.
Reactive Expressions in Elements
Elements can use Launchpad's reactive expression syntax (${{ }}) inside prerender():
String prerender(String body, Map attributes) {
return """<span>${{ counter.get() }}</span>"""
}
When the underlying Cargo value changes, only the affected DOM region updates automatically via WebSocket.
Server Actions in Elements
Elements can use Launchpad's server action syntax inside prerender():
String prerender(String body, Map attributes) {
return """<button on-click=${ _{ counter.inc() }}>+</button>"""
}
The _{ } closure executes on the server when the button is clicked.
Using Server Actions with Elements in Templates
You can attach server actions to element tags from the template side:
<g:star-rating value="3" on-change=${ _{ t ->
dock.ratings.put('item-1', t.value)
}}></g:star-rating>
Element Discovery and Registration
Automatic Discovery
When a Launchpad instance is created, it scans its own elements/ subdirectory for .groovy files. Each file is:
- Read as text
- Preprocessed (reactive
${{ }}syntax is transformed) - Parsed into a class using a
GroovyClassLoaderthat is shared across all Elements in this Launchpad (so sibling Elements can reference each other by class name) - Registered in the Launchpad's per-instance
elementsmap, keyed by the kebab-case name - Contributed to the cross-Launchpad shared pool (
Launchpad.sharedPool) according to the ownership rules described in the Launchpad API reference
Registration Maps
Per-Launchpad local map (always checked first during resolution):
launchpad.elements // Map<String, Class>
Cross-Launchpad shared pool (fallback for names a Launchpad doesn't define locally):
Launchpad.sharedPool // ConcurrentHashMap<String, Class>
Launchpad.poolOwners // ConcurrentHashMap<String, String> // name → owning Launchpad's name
The key is the kebab-case element name (e.g., "star-rating"); the value is the compiled Class object. Resolution from any Launchpad goes launchpad.elements[name] ?: Launchpad.sharedPool[name]. See the Launchpad API reference for the full multi-Launchpad model and the qualified <g:slice/element> syntax.
Migration note:
Launchpad.elements(a static map in earlier versions) was replaced by the per-instancelaunchpad.elements. Code that didLaunchpad.elements.put(name, cls)should migrate tolaunchpad.elements.put(name, cls).
Hot Reload
In debug mode, Spaceport watches the launchpad/ directory via a Beacon (file watcher). When any file changes:
- The template cache (
SpaceportTemplateEngine.templateCache) is cleared - All Launchpad element maps are cleared via
Launchpad.clearAllElements()(clears per-instance maps, the shared pool, and pool ownership) - On the next request, elements are rediscovered and recompiled when each Launchpad is next constructed
The template cache is also cleared each time a Launchpad finishes installing its Elements — this guarantees that adding a new Element file doesn't leave templates compiled against an older view of the registry. Hot-reload does not push changes to already-connected clients; a page refresh picks up the new code.
Built-in Template Variables Available in Elements
Elements have access to the following through the Element trait:
| Variable | Source | Description |
|---|---|---|
client |
Set by Launchpad | The Client session object |
dock |
Set by Launchpad | Session-scoped Cargo store |
launchpad |
Set by Launchpad | The parent Launchpad instance |
Elements do not have direct access to the template's r (HttpResult), data, cookies, or context variables. To pass request-specific data into an element, use attributes:
<g:my-element route="${ r.context.target }"></g:my-element>
Client-Side Element Reference
On the client, each element instance is registered as a global variable:
window.element_<id> // e.g., window.element_a1b2c3
This variable is also the DOM element itself (obtained via document.querySelector('[element-id="<id>"]')). It has:
- All
@Javascriptfunction properties as methods - All
@Bindproxy functions as methods - A
_listenersarray tracking event listeners registered with.listen() - A
.listen(type, handler, options)method that auto-cleans up on element removal - A
.constructedfunction (if defined) called after DOM insertion - A
.deconstructedfunction (if defined) called on DOM removal
The .listen() Helper
element.listen('click', handler, options)
Works like addEventListener but automatically removes the listener when the element is cleaned up by HUD-Core. Only available on the root element itself, not child elements.
Lifecycle Order
- Element
<script>tag executes element_<id>global variable is set to the DOM element_listenersarray is initialized@Javascriptinline code executes@Javascriptfunction properties are attached@Bindproxy functions are attachedconstructed(element)is called (if defined)
On removal:
- All listeners registered via
.listen()are removed deconstructed(element)is called (if defined)window.element_<id>is deleted
Make the docs better.Edit this page on GitHub