Skip to content

Package

wybthon (package)

Top-level Wybthon package API and browser/runtime detection.

This module exposes the public surface area for both browser (Pyodide) and non-browser environments, importing DOM/VDOM features only when available.

Context dataclass

Opaque context identifier and default value container.

DomEvent

Thin wrapper around a JS event with convenience helpers.

prevent_default()

Prevent the default browser action for this event, if possible.

stop_propagation()

Stop propagation through the delegated listener chain.

Element

Thin wrapper around a DOM node with convenience methods.

add_class(*class_names)

Add one or more CSS classes to this element.

append(child)

Append a child Element or a text node to this element.

append_to(parent)

Append this element to the given parent element.

attach_ref(ref)

Attach this element to a mutable Ref container.

cleanup()

Remove all tracked event listeners from this element.

find(selector)

Find the first matching descendant by CSS selector.

find_all(selector)

Find all matching descendants by CSS selector.

get_attr(name)

Return attribute value or None when missing.

has_class(class_name)

Return True if the element currently has the given class.

load_html(url) async

Fetch HTML from url and set as innerHTML of this element.

off(event_type=None, handler=None)

Remove matching event listeners previously attached via on().

on(event_type, handler, *, options=None)

Add an event listener and track it for cleanup.

query(selector, within=None) classmethod

Query a single element by CSS selector, optionally within a parent.

query_all(selector, within=None) classmethod

Query all matching elements by CSS selector, optionally within a parent.

remove()

Remove this element from its parent if attached.

remove_attr(name)

Remove an attribute from this element.

remove_class(*class_names)

Remove one or more CSS classes from this element.

set_attr(name, value)

Set an attribute on this element, with text-node fallbacks.

set_html(html)

Set the innerHTML of this element to the provided HTML string.

set_style(styles=None, **style_kwargs)

Set CSS properties using a dict and/or keyword arguments.

set_text(text)

Set text content for this element.

toggle_class(class_name, force=None)

Toggle a CSS class, optionally forcing on/off.

FieldState dataclass

Signals representing a field's value, error message, and touched state.

Ref

Mutable container holding a reference to an Element.

Resource

Bases: Generic[R]

Async resource wrapper with Signals for data, error, and loading.

Use reload() to (re)fetch, cancel() to cancel the in-flight request. Optionally accepts a source getter; when the source signal changes the resource automatically refetches.

Route dataclass

Declarative route definition mapping a path to a component.

VNode dataclass

Virtual node representing an element, text, or component subtree.

Dynamic(component, props=None, **kwargs)

Render a dynamically-chosen component.

component may be a string tag name, a component function, or None (renders nothing).

Example::

Dynamic(heading_level(), f"Section {idx}")

ErrorBoundary(props)

Catch render errors in children and display a fallback.

Props
  • fallback: VNode | str | callable(error, reset) -> VNode
  • on_error: optional callback invoked with the caught exception
  • reset_key / reset_keys: when this value changes the error is auto-cleared
  • children: child VNodes to render when there is no error

For(each, children)

Render a list of items using a keyed mapping function.

each is an iterable (or a zero-arg getter returning one). children is a callback (item, index_getter) -> VNode called for every item.

Example::

For(items(), lambda item, i: li(item, key=i()))

Fragment(*args)

Group multiple children without adding a visible wrapper to the DOM.

Uses a <span style="display:contents"> so the wrapper is invisible to CSS layout while keeping the VDOM diffing algorithm simple.

Can be called directly::

Fragment(child1, child2)

Or used as a component tag via h()::

h(Fragment, {}, child1, child2)

Index(each, children)

Render a list by index with a stable item getter.

Unlike :func:For, the children callback receives (item_getter, index) so that the DOM node for each index is reused even when the underlying data changes.

Example::

Index(items(), lambda item, i: li(item()))

Anchor element component that navigates via history API without reloads.

Match(when, children=None)

Declare a branch inside a :func:Switch.

when is evaluated as a boolean (may be a getter). If truthy, children is the content to render.

Must be used inside Switch().

Provider(props)

Context provider component (function component).

Renders its children transparently. The reconciler handles pushing and popping context values around this component's subtree mount.

Props
  • context: Context
  • value: Any
  • children: VNode or list of VNodes

Router(props)

Function component that renders the matched route's component.

Props
  • routes: List[Route]
  • base_path: str
  • not_found: component to render on 404

Show(when, children=None, *, fallback=None)

Conditionally render children when when is truthy.

when may be a value or a zero-arg callable (getter). If falsy the fallback is rendered instead (defaults to an empty text node).

Example::

Show(is_logged_in(), p("Welcome!"), fallback=p("Please log in"))

Suspense(props)

Render a fallback while one or more resources are loading.

Props
  • resources | resource: Resource or list of Resources
  • fallback: VNode | str | callable returning VNode/str
  • keep_previous: bool (default False)
  • children: child VNodes to render when not loading

Switch(*branches, fallback=None)

Render the first matching :func:Match branch, or fallback.

Example::

Switch(
    Match(status() == "loading", p("Loading...")),
    Match(status() == "error", p("Error!")),
    Match(status() == "ready", p("Ready")),
    fallback=p("Unknown"),
)

a11y_control_attrs(field, *, described_by_id=None)

Return ARIA attributes for an input/select control bound to the field.

  • aria-invalid is set to "true" when there's an error, else "false".
  • aria-describedby includes the provided error element id when an error exists.

batch()

Batch signal updates within the returned context manager.

bind_checkbox(field)

Bind a checkbox input to a boolean field.

bind_select(field)

Bind a select element to a field, updating value on change.

bind_text(field, *, validators=None)

Bind a text input to a field with validation on input events.

create_context(default)

Create a new Context with a unique identifier and default value.

create_effect(fn)

Create an auto-tracking reactive effect.

The effect runs immediately and re-runs whenever any signal read inside fn changes. on_cleanup may be called inside fn to register per-run cleanup (runs before re-execution and on disposal).

If fn accepts a positional parameter, the previous return value is passed on each re-execution (None on the first run), matching SolidJS createEffect(prev => ...)::

create_effect(lambda prev: (print("was", prev), count())[1])

Inside a component, the effect is automatically disposed on unmount.

create_memo(fn)

Create an auto-tracking computed value. Returns a getter function.

Re-computes only when signals read inside fn change. Inside a component, the underlying computation is disposed on unmount.

Example::

doubled = create_memo(lambda: count() * 2)
print(doubled())  # reactive read

create_portal(children, container)

Render children into a different DOM container.

Returns a VNode that, when mounted, renders children into container instead of the parent component's DOM node. Useful for modals, tooltips, and overlays that need to break out of their parent's DOM hierarchy.

container may be an Element or a CSS selector string.

create_resource(source_or_fetcher, fetcher=None)

Create an async Resource with loading/error states and cancellation.

Can be called two ways:

  • create_resource(fetcher) -- simple fetcher, no source signal.
  • create_resource(source, fetcher) -- refetches automatically when the source getter's return value changes.

The fetcher should be an async function returning the data value. If it accepts a signal keyword argument, an AbortSignal will be passed for cancellation support when available.

create_root(fn)

Run fn with an independent reactive root.

fn receives a dispose callback that tears down all effects created inside the root::

result = create_root(lambda dispose: ...)

create_signal(value)

Create a reactive signal. Returns (getter, setter).

Works inside or outside components. Inside a stateful component the signal is captured by the render function's closure and persists naturally (no cursor system needed).

Example::

count, set_count = create_signal(0)
print(count())          # 0
set_count(5)
print(count())          # 5

email(message='Invalid email address')

Validate a basic email address format (lightweight regex).

error_message_attrs(*, id)

Return attributes for an error message container.

Use with a live region to announce validation errors to assistive tech.

form_state(initial)

Create a form state map from initial values using Signals.

forward_ref(render_fn)

Create a component that forwards a ref prop to a child element.

The wrapped function receives (props, ref) instead of (props,), where ref is the value of the ref prop (or None).

Example::

FancyInput = forward_ref(lambda props, ref: input_(
    type="text", ref=ref, class_name="fancy", **props,
))

h(tag, props=None, *children)

Create a VNode from a tag, props, and children (component-aware).

is_dev_mode()

Return whether development mode is currently active.

load_component(module_path, attr=None)

Dynamically import a module (optionally attribute) and return a function component factory.

The returned function component will render a small loader until the module is imported. On success it will render the loaded component with the same props. On error, it renders a minimal error text.

This utility is Pyodide-friendly: it uses Python's import system, which is compatible with packages pre-bundled or fetched via micropip. Use preload_component to warm the cache.

max_length(n, message=None)

Validate that stringified value length is at most n.

memo(component, are_props_equal=None)

Memoize a function component to skip re-renders when props are unchanged.

By default uses shallow identity comparison (is) on each prop value. Pass a custom are_props_equal(old_props, new_props) -> bool for deeper comparison logic.

merge_props(*sources)

Merge multiple prop dicts. Later sources win on conflict.

Example::

defaults = {"size": "md", "variant": "solid"}
final = merge_props(defaults, props)

min_length(n, message=None)

Validate that stringified value length is at least n.

navigate(path, *, replace=False)

Programmatically change the current path and update current_path.

on(deps, fn, defer=False)

Create an effect with explicit dependencies.

deps is a single getter or a list of getters. fn receives the current value(s) as positional arguments. Only the listed deps are tracked; the body of fn is run inside untrack.

When defer is True the effect skips the first execution (useful for reacting only to changes, not the initial value).

Example::

on(count, lambda v: print("count is now", v))

on_cleanup(fn)

Register a cleanup callback.

  • Inside create_effect: runs before each re-execution and on disposal.
  • Inside a component's setup phase: runs when the component unmounts.

on_mount(fn)

Register a callback to run once after the component mounts.

Must be called during a component's setup phase (the body of a @component function, before the return).

on_submit(handler, form)

Create a submit handler that prevents default and calls the handler.

on_submit_validated(rules, handler, form)

Submit handler that validates the whole form before invoking handler.

Prevents the default submit, validates via validate_form, and calls handler(form) only when the form is valid.

preload_component(module_path, attr=None)

Eagerly import a component to warm caches before navigation.

render(vnode, container)

Render a VNode tree into a container Element or CSS selector.

required(message='This field is required')

Validate that a value is present and non-empty.

rules_from_schema(schema)

Build a validators map from a simple, lightweight schema.

Supported keys per field: - required: bool or str (if str, used as custom message) - min_length: int (optional custom message via min_length_message) - max_length: int (optional custom message via max_length_message) - email: bool or str (if str, used as custom message)

Example

{ "name": {"required": True, "min_length": 2}, "email": {"email": True}, }

set_dev_mode(enabled)

Enable or disable development mode warnings globally.

split_props(props, *key_groups)

Split a props dict into groups by key name, plus a rest dict.

Returns (group1, group2, ..., rest) where rest contains keys not claimed by any group.

Example::

local, rest = split_props(props, ["class", "style"])

untrack(fn)

Run fn without tracking any signal reads.

Useful inside effects when you need to read a signal without creating a dependency::

create_effect(lambda: print("a changed:", a(), "b is:", untrack(b)))

use_context(ctx)

Read the current value for ctx, or its default if not provided.

validate(value, validators)

Return first validation error or None when all validators pass.

validate_field(field, validators=None)

Validate a single field and update its error/touched signals.

Returns the error message if any, else None.

validate_form(form, rules)

Validate all fields in a form against a rules map.

Mutates each field's touched and error signals. Returns (is_valid, errors_map).

Public API (top-level imports)

  • Core rendering
  • Element, Ref
  • VNode, h, render
  • Components
  • ErrorBoundary, Suspense
  • Reactivity
  • create_signal, create_effect, create_memo, batch
  • on_mount, on_cleanup
  • Resource, create_resource
  • Context
  • Context, create_context, use_context, Provider
  • Router
  • Route, Router, Link, navigate, current_path
  • Forms
  • State and validation: FieldState, form_state, validate, validate_field, validate_form
  • Validators: required, min_length, max_length, email
  • Bindings and submit helpers: bind_text, bind_checkbox, bind_select, on_submit, on_submit_validated
  • A11y helpers: a11y_control_attrs, error_message_attrs
  • Events
  • DomEvent
  • Lazy loading
  • lazy, load_component, preload_component
  • Development mode
  • DEV_MODE, set_dev_mode, is_dev_mode

Note: DOM/VDOM-related symbols (e.g., Element, h, render, router) require a Pyodide/browser environment. In non-browser contexts, only reactivity, forms, and lazy utilities are available.