VNode
wybthon.vnode¶
vnode
¶
Virtual node data structure and tree-building helpers.
This module defines VNode and the functions that
build trees of them: h, Fragment,
and hole. It has no browser or DOM dependencies, so
VNode trees can be constructed and inspected anywhere CPython runs.
A reactive hole is a _hole VNode wrapping a reactive expression
(an Accessor or a zero-argument function). The
reconciler runs the expression inside its own render effect and patches
only that region of the DOM when its dependencies change. Holes are
created implicitly whenever a reactive expression appears in a child
position, and explicitly with hole() when you want a key.
Example
Building a small subtree without a browser:
Classes:
| Name | Description |
|---|---|
VNode |
Virtual node representing an element, text, component, fragment, or hole. |
Functions:
| Name | Description |
|---|---|
hole |
Create a reactive hole explicitly, optionally with a |
h |
Create a VNode from a tag, props, and children. |
Fragment |
Group children without adding a wrapper element. |
copy_vnode |
Return a structural copy of an unmounted VNode tree, including child sequences. |
Node
¶
Anything that renders: what html(), h(), and a component call give you.
Annotate component functions and node-holding variables with Node.
Item syntax sets a component call's children:
Card(title="Hi")[html(t"<p>Body</p>")].
VNode
¶
VNode(tag: str | Callable[..., Any] | None, props: PropsDict | None = None, children: list[Any] | None = None, key: str | int | None = None)
Bases: Node
Virtual node representing an element, text, component, fragment, or hole.
Uses __slots__ for a compact layout. The renderer populates the
internal attributes (el, subtree, render_effect,
component_ctx, ns, _frag_end) when the VNode mounts.
Attributes:
| Name | Type | Description |
|---|---|---|
tag |
Element tag name ( |
|
props |
PropsDict
|
Mapping of prop names to values: attributes, event handlers, refs, and reactive bindings. |
children |
list[Any]
|
Child VNodes (mixed values before normalization). |
key |
Optional stable identity for keyed reconciliation. |
|
el |
int | None
|
Kernel node id once mounted (for fragments the start marker; for holes the end marker). |
owner_scope |
Any
|
Optional reactive |
to_text_vnode
¶
Convert an arbitrary value to a text VNode (None becomes "").
hole
¶
Create a reactive hole explicitly, optionally with a key.
Reactive expressions in child positions become holes automatically;
reach for hole() when you need a stable key for keyed
reconciliation inside a fragment, or to make a hole visually
explicit.
The expression may return a VNode, a string, a list of either, or
None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
getter
|
Callable[[], Any]
|
Zero-arg reactive expression evaluated inside its own render effect. |
required |
key
|
str | int | None
|
Optional stable identity for keyed reconciliation. |
None
|
Returns:
| Type | Description |
|---|---|
VNode
|
A |
flatten_children
¶
Flatten nested child lists into a single list, dropping None entries.
normalize_children
¶
Normalize a mixed list of children into a flat list of VNodes.
VNode: kept as is; fragments are flattened into the parent list.- Reactive expression (accessor or zero-arg function): wrapped in a
_holeVNode. None,True, andFalse: skipped, socond and Widget()renders nothing when the condition is false (as in SolidJS).- Anything else: coerced to a text VNode.
h
¶
Create a VNode from a tag, props, and children.
The programmatic layer, the counterpart of Solid's h: use it for
markup built by code. Props use Python names (class_, on_click,
aria_label) as well as HTML names. Reactive expressions in child
positions are wrapped as holes when the parent mounts; components
receive their children verbatim through the children prop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tag
|
str | Callable[..., Any] | None
|
An HTML tag name, a special tag ( |
required |
props
|
PropsDict | None
|
Mapping of prop names to values. May be |
None
|
*children
|
Any
|
Children to attach. Lists and tuples are flattened. |
()
|
Returns:
| Type | Description |
|---|---|
VNode
|
A new |
Fragment
¶
Group children without adding a wrapper element.
Fragments mount their children directly into the parent between two
empty comment markers, so they never pollute selectors like
:first-child or affect layout.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*args
|
Any
|
Children. Lists and tuples are flattened. |
()
|
Returns:
| Type | Description |
|---|---|
VNode
|
A |
copy_vnode
¶
Return a structural copy of an unmounted VNode tree, including child sequences.
Mounting records DOM ids and normalized children on the VNodes it mounts, so a tree mounts once. Server rendering copies the root view for each render pass. Sequences without VNodes and other values are returned unchanged.
What's in this module¶
vnode defines the VNode data structure and the pure
helpers that build trees of them. It has no browser dependency, so
trees can be constructed and inspected anywhere CPython runs. A
reactive hole is a _hole VNode wrapping an accessor or zero-arg
function; the reconciler runs it in its own render effect and patches
only that region when its reads change.
| Name | Description |
|---|---|
VNode |
Element, text, component, fragment, hole, template, or region node; tag, props, children, key. |
h |
Hyperscript constructor: h(tag, props, *children); components get children as the children prop. |
Fragment |
Group children with no wrapper element. |
hole |
Explicit reactive hole, optionally with a key. |
Most nodes are built for you:
htmlreturns a_tplnode for a template with one root element: a reference to the compiled template plus the interpolated values, with no VNodes for the static markup. A template with several roots returns a fragment, and one with no elements returns text.ShowandSwitchreturn_branchnodes, andForandRepeatreturn_listnodes; the reconciler mounts these as native regions.h()builds ordinary element VNodes.
Treat these special tags as internal: build nodes with html, h,
and the flow functions rather than by tag name.
Holes are created implicitly: any accessor or zero-arg callable in a
child position becomes one, whether it's a getter the compiler made
from {count() * 2} in a template or a function passed to h().
Reach for hole() when you need a stable key or want the hole
visually explicit.
Building nodes with h()¶
h() is the programmatic layer, the counterpart of Solid's h. Most
markup is a template; use h() when code builds the markup: generated
forms, recursive trees, or a tag computed at run time. Templates and
h() trees mix freely in either direction.
from wybthon import create_signal, html
from wybthon.vnode import Fragment, h, hole
name, set_name = create_signal("Ada")
active, set_active = create_signal(False)
def field(label, kind):
return h("label", {}, label, h("input", {"type": kind, "aria_label": label}))
view = h(
"section",
{"class_": {"card": True, "active": active}, "data_testid": "card"},
h("h1", {}, "Hello, ", name), # an accessor child is a hole
hole(lambda: f"{len(name())} letters", key="count"), # explicit hole with a key
[field(label, kind) for label, kind in [("Email", "email"), ("Age", "number")]],
Fragment(h("p", {}, "Body 1"), h("p", {}, "Body 2")),
html(t"<p>A template inside: {name()}</p>"),
)
A key in h() props keys the node it builds, element or component,
so the reconciler remounts it when the key changes. It's the low-level
escape hatch: a component call takes no key= (use a keyed Show to
remount a component, and For for lists).
h() evaluates its arguments before Wybthon sees them, so the compiler
can't help here: pass an accessor (name) or a function
(lambda: name().upper()) wherever a value should stay live. A
t-string isn't markup outside html(); passing one to h() raises
TypeError.
VNode[...] sets children with item syntax and returns the node, so
h("section", {"class": "card"})[h("h1", {}, "Hello")] equals
h("section", {"class": "card"}, h("h1", {}, "Hello")). A component
call supports the same syntax for its children prop.
Prop names and values¶
h() stores props as written, and the prop applier maps the names when
it writes attributes. Templates write HTML names (class, for,
aria-label, onclick); h() props and template spreads
(<input {attrs}>) accept both those and Python names:
class_becomesclass, andhtml_for(orfor_) becomesfor.- Other underscores become hyphens:
aria_label,data_testid,stroke_width. - Event handlers use the
on_prefix (on_click,on_input) or the camelCase form (onClick).
| Prop value or name | What the applier does |
|---|---|
True |
Sets the attribute. Known boolean attributes (disabled, checked, hidden, required, readonly, selected, multiple, open, autofocus, ...) get ""; anything else gets "true". |
False or None |
Removes the attribute. |
value, checked, selected_values, inner_html / innerHTML |
Set as DOM properties, not attributes. value and checked are always re-asserted on patch so controlled inputs win over user edits. |
class as a str, list, or dict |
Lists join truthy entries; dicts include keys whose values are truthy. |
style as a dict or str |
Dict keys may be snake_case or camelCase and are converted to kebab-case; None or False removes a declaration; a string sets the style attribute. |
dataset={...} |
Each key becomes a data-* attribute. |
on_click, onClick, ... |
Registered with root-scoped event delegation; see events. |
ref |
A Ref, a callback ref(el), or a list of either; assigned an Element on mount, Ref.current reset to None on unmount. |
key, children |
Never written to the DOM. |
A prop value that's an accessor or a zero-arg function, or a class or
style dict containing one, becomes a reactive binding that
re-applies just that prop when its reads change. A binding that raises
NotReadyError keeps the current DOM value; other exceptions route to
the nearest Errored boundary. These rules are
shared with template attributes, where the compiler supplies the
getters.
The reconciler infers the SVG namespace from an svg root, so
h("svg", {"viewBox": "0 0 10 10"}, h("circle", {"r": 4})) and a
<svg> in a template both render SVG elements.
See also¶
- Templates: the
htmltemplate function, the primary way to write markup - Compiler: how templates get their getters
is_accessor: the rule that decides what becomes a hole- Reconciler: how VNodes mount and patch
- Events and DOM: handler props,
Element, andRef - Concepts: Virtual DOM