Skip to main content

Component API

Types and base classes used when writing .lspa component Python blocks.

Class diagram

Component

Base class for all components. Available as Component in every <python> block (no import needed).

class MyComponent(Component):
def context(self, props):
return {"title": props.get("title", "Default")}

def client(self):
return {
"props": {"title": "Default"},
"state": {"count": 0},
"actions": {"inc": self.add("count")},
"lifecycle": {"onMount": ["inc"]},
}

context(self, props) → dict

Called server-side when rendering the template. Returns a dict that becomes the py namespace in {{ }} expressions.

ParameterTypeDescription
propsdictProps passed from parent or initial_props

Returns: Dict of template variables (accessible as py.<key> or directly by name in {{ }}).

client(self) → dict

Inspected at build time by the code generator to produce the setup() JavaScript function. The return value is a spec dict:

{
"props": { "name": "default" }, # expected props + defaults
"state": { "count": 0 }, # reactive state
"actions": { "inc": self.add("count") }, # state mutations
"lifecycle": { "onMount": ["inc"] }, # lifecycle hooks
}

ClientMethods

Mixin methods inherited by Component. Each returns an operation dict that the code generator translates to JavaScript.

add(state, value=1) → dict

Increment a state field.

self.add("count") # count += 1
self.add("count", 5) # count += 5

sub(state, value=1) → dict

Decrement a state field.

self.sub("count") # count -= 1
self.sub("count", 2) # count -= 2

set(state, value) → dict

Assign a fixed value to a state field.

self.set("name", "lua-spa")
self.set("count", 0)

toggle(state) → dict

Flip a boolean state field.

self.toggle("visible") # visible = !visible

StateField

Declarative state initialization. Use when state should be seeded from a prop.

from lua_spa.types import StateField

def client(self):
return {
"state": {
"count": StateField(
name="count",
from_prop="initialCount",
default=0,
cast="int",
)
}
}
FieldTypeDefaultDescription
namestrState variable name
from_propstr | NoneNoneProp name to seed from
defaultAnyNoneFallback value if prop absent
caststr"raw"Type coercion: "int", "float", "str", "bool", "raw"

ComponentDefinition

Internal dataclass representing a parsed .lspa file.

FieldTypeDescription
namestrComponent name
templatestrHTML template string
client_scriptstrCompiled setup() JS function
python_blockstrRaw <python> source
importsMapping[str, str]{alias: alias} import map