Components API Reference¶
Complete reference for the Pytonium reactive components system.
from Pytonium.components import (
Component, State, Computed, Element,
Div, Span, P, H1, H2, H3, H4, H5, H6,
Button, Input, Textarea, Select, Option, Label, Form,
A, Img, Ul, Ol, Li, Table, Tr, Td, Th, Thead, Tbody,
Header, Footer, Nav, Section, Article, Main,
Pre, Code, Hr, Br, Strong, Em,
Show, Switch, EventData,
)
Component¶
Base class for reactive components. Subclass it, define State fields, and implement render().
setup¶
Pre-register event handlers and the page-ready sentinel with CEF. Must be called before pytonium.initialize().
| Name | Type | Description |
|---|---|---|
pytonium | Pytonium | A Pytonium instance that has not been initialized yet. |
__init__¶
Create a component instance. Keyword arguments matching State field names set initial values.
render¶
Return the element tree for this component. Called once during mount(). Must be overridden by subclasses.
mount¶
Mount the component into a browser. Calls render(), injects HTML, analyzes dependencies, and registers events.
| Name | Type | Default | Description |
|---|---|---|---|
pytonium | Pytonium | (required) | Pytonium instance with an initialized browser. |
container_id | str or None | None | HTML element ID to mount into. If None, replaces document.body. |
unmount¶
Unmount the component. Removes event handlers, cleans up the dependency graph, and calls on_unmount().
on_mount¶
Lifecycle hook called after mount() completes. Override to initialize resources.
on_update¶
Lifecycle hook called after state changes are applied to the DOM.
| Name | Type | Description |
|---|---|---|
changed_fields | set[str] | Names of the State fields that changed. |
on_unmount¶
Lifecycle hook called when the component is unmounted. Override to clean up resources.
State¶
Reactive state descriptor. Declare as a class attribute on a Component subclass.
| Name | Type | Default | Description |
|---|---|---|---|
default | Any | None | Default value for this field. |
Reads trigger dependency tracking during render(). Writes trigger DOM updates through the dependency graph.
Mutable defaults
State([]) shares the same list instance across all component instances. For per-instance mutable defaults, set them in __init__ or on_mount.
Computed¶
Cached, auto-invalidating derived property.
The return value is cached until any upstream State field changes. DOM bindings that reference the Computed property update automatically.
class Cart(Component):
items = State([])
@Computed
def total(self):
return sum(item["price"] for item in self.items)
Element¶
HTML element builder with fluent API.
Constructor¶
Create an element with the given HTML tag. Keyword arguments set static HTML attributes.
| Name | Type | Description |
|---|---|---|
tag | str | HTML tag name. |
**attrs | str | Static HTML attributes (Python names converted automatically). |
Element("div", class_name="container", data_role="main")
# → <div class="container" data-role="main" data-pyt-id="...">
child¶
Append a single child element. Returns self.
children¶
Append multiple child elements. Returns self.
text¶
Set text content. Pass a string for static content or a lambda for reactive content.
attr¶
Set an HTML attribute. Pass a lambda for reactive attributes.
id¶
Set the HTML id attribute.
class_name¶
Add one or more static CSS classes (space-separated).
class_toggle¶
Toggle a CSS class based on a reactive boolean condition.
| Name | Type | Description |
|---|---|---|
name | str | CSS class name. |
condition | Callable | Lambda returning True (add) or False (remove). |
style¶
Set an inline style property. Pass a lambda for reactive styles.
| Name | Type | Description |
|---|---|---|
prop | str | CSS property name (e.g., "background-color", "font-size"). |
value | str or Callable | Value string or reactive lambda. |
bind_value¶
Two-way binding between an input element's value and a State field.
| Name | Type | Default | Description |
|---|---|---|---|
component | Component | (required) | Component instance owning the state field. |
field_name | str | (required) | Name of the State field. |
debounce_ms | int | 0 | Debounce delay in ms (0 = frame-buffered). |
Event Methods¶
All event methods take a single handler parameter and return self.
on_click(handler: Callable) -> Element
on_dblclick(handler: Callable) -> Element
on_keydown(handler: Callable) -> Element
on_keyup(handler: Callable) -> Element
on_input(handler: Callable) -> Element
on_change(handler: Callable) -> Element
on_submit(handler: Callable) -> Element
on_mouseenter(handler: Callable) -> Element
on_mouseleave(handler: Callable) -> Element
on_focus(handler: Callable) -> Element
on_blur(handler: Callable) -> Element
Handlers may take zero arguments or one EventData argument.
children_from¶
Render dynamic children from a reactive list source with keyed reconciliation.
| Name | Type | Description |
|---|---|---|
source | Callable | Lambda returning the current list. |
key | Callable | Function extracting a stable key from each item. |
render_item | Callable | (item, index) → Element for each item. |
to_html¶
Generate the HTML string with data-pyt-id markers. Reactive bindings are evaluated once for initial values.
Convenience Constructors¶
Functions that return Element(tag). All accept **attrs.
| Text & Container | Headings | Form | Lists | Tables | Semantic | Misc |
|---|---|---|---|---|---|---|
Div | H1 | Button | Ul | Table | Header | A |
Span | H2 | Input | Ol | Thead | Footer | Img |
P | H3 | Textarea | Li | Tbody | Nav | Hr |
Pre | H4 | Select | Tr | Section | Br | |
Code | H5 | Option | Td | Article | ||
Strong | H6 | Label | Th | Main | ||
Em | Form |
EventData¶
Deserialized DOM event data passed to Python handlers.
| Field | Type | Description |
|---|---|---|
type | str | Event type (e.g., "click", "keydown"). |
value | str | e.target.value (input/textarea/select elements). |
key | str | Keyboard key name (e.g., "Enter", "Escape"). |
key_code | int | Keyboard key code. |
client_x | float | Mouse X relative to viewport. |
client_y | float | Mouse Y relative to viewport. |
shift_key | bool | Shift key held. |
ctrl_key | bool | Ctrl key held. |
alt_key | bool | Alt key held. |
meta_key | bool | Meta/Cmd key held. |
checked | bool | e.target.checked (checkboxes). |
Show¶
Conditional rendering element with two branches.
| Name | Type | Default | Description |
|---|---|---|---|
when | Callable | (required) | Lambda returning True or False. |
then | Callable | (required) | Lambda returning an Element for the True branch. |
fallback | Callable or None | None | Lambda returning an Element for the False branch. |
Renders as a <div> placeholder. When the condition changes, the old branch is unmounted and the new branch is mounted in its place.
Switch¶
Multi-branch conditional rendering element.
| Name | Type | Description |
|---|---|---|
selector | Callable | Lambda returning the value to match against cases. |
case¶
Register a branch for a specific selector value. Returns self for chaining.
default¶
Register the fallback branch (when no case matches). Returns self.
EventRouter¶
Routes DOM events from JavaScript to Python handlers. Typically used internally by Component, but available for advanced use.
prepare¶
Pre-register the global event handler with CEF. Called by Component.setup(). Must be called before pytonium.initialize().
register_events¶
Register event listeners for an element tree. Walks the tree recursively.
cleanup¶
Remove all handlers and unregister this router.
DependencyTracker¶
Tracks dependencies between State fields and DOM bindings. All methods are classmethods operating on shared class state.
reset¶
Reset all tracking state. Used in tests and between mounts.
register_component¶
Register a component for dependency tracking. Called during mount().
unregister_component¶
Remove all dependency mappings for a component. Called during unmount().
UpdateType¶
Enum of DOM mutation types used internally by the MutationCompiler.
class UpdateType(Enum):
SET_TEXT_CONTENT = "text_content"
SET_ATTRIBUTE = "set_attribute"
REMOVE_ATTRIBUTE = "remove_attribute"
ADD_CLASS = "add_class"
REMOVE_CLASS = "remove_class"
TOGGLE_CLASS = "toggle_class"
SET_STYLE = "set_style"
SET_VALUE = "set_value"
INSERT_CHILD = "insert_child"
REMOVE_CHILD = "remove_child"
MOVE_CHILD = "move_child"
REPLACE_INNER_HTML = "replace_inner_html"