App & Components API

API reference for application lifecycle (webcompy.app), component definitions and hooks (webcompy.components), plugin registration (webcompy.plugin), exceptions (webcompy.exception), and helpers (webcompy.utils).

Application & Configuration#

PluginScript#

class PluginScript:
    attrs: dict[str, str]
    script: str | None = None
    condition: str | None = None
    in_head: bool = False
    pre_paint: bool = False

Key: webcompy.app._config:PluginScript · Exports: from webcompy.app import PluginScript

Description of a script element generated by a plugin.

Args:

  • attrs: HTML attributes placed on the generated script element.
  • script: Inline script body when the script is inlined.
  • condition: JavaScript expression gating the script element; when set, the script is only injected while the expression is truthy.
  • in_head: Whether the script is appended to <head> instead of <body>.
  • pre_paint: Whether the script is emitted synchronously in the <head> pre-paint slot before stylesheets.

Attributes:

  • attrs: HTML attributes placed on the generated script element.
  • script: Inline script body when the script is inlined.
  • condition: JavaScript expression gating the script element; when set, the script is only injected while the expression is truthy.
  • in_head: Whether the script is appended to <head> instead of <body>.
  • pre_paint: Whether the script is emitted synchronously in the <head> pre-paint slot before stylesheets.

pre_paint_vars#

def pre_paint_vars(
    key: str,
    variants: Mapping[str, Mapping[str, str]],
    default: str,
    *,
    selector: str = ':root',
    storage: PrePaintStorage = 'cookie',
    important: bool = False,
    case_insensitive: bool = False,
    cookie_max_age: int = 31536000,
    cookie_samesite: str = 'Lax',
) -> PrePaintStyle

Key: webcompy.app.styles:pre_paint_vars · Exports: from webcompy.app import pre_paint_vars

Build a PrePaintStyle from a variant-to-CSS-variable mapping.

Args:

  • key: Storage key name.
  • variants: Mapping of variant names to CSS custom-property mappings.
  • default: Default variant name when storage is absent or invalid.
  • selector: CSS selector wrapped around each variant's declarations.
  • storage: Storage backend ("cookie", "local_storage", or "session_storage").
  • important: Whether to append !important to each CSS variable declaration.
  • case_insensitive: Whether stored values match variant names case-insensitively.
  • cookie_max_age: Max-Age in seconds when storage="cookie".
  • cookie_samesite: SameSite attribute when storage="cookie".

Returns: An immutable PrePaintStyle ready for app.append_style().

Raises:

  • ValueError: If selector is empty, variants is empty, default is missing, or any variant mapping is invalid.
  • TypeError: If any CSS variable name or value is not a string.

PrePaintStorage#

PrePaintStorage: TypeAlias = Literal['cookie', 'local_storage', 'session_storage']

Key: webcompy.app.styles:PrePaintStorage · Exports: from webcompy.app import PrePaintStorage

Supported browser storage backends for declarative pre-paint styles.

PrePaintStyle#

class PrePaintStyle:
    key: str
    variants: Mapping[str, str]
    default: str
    storage: PrePaintStorage = 'cookie'
    case_insensitive: bool = False
    cookie_max_age: int = 31536000
    cookie_samesite: str = 'Lax'

Key: webcompy.app.styles:PrePaintStyle · Exports: from webcompy.app import PrePaintStyle

Declarative specification for a pre-paint persisted style variant.

Args:

  • key: Storage key (cookie name, localStorage key, or sessionStorage key).
  • variants: Mapping of variant names to complete CSS rule strings.
  • default: Default variant name used when storage is absent or invalid.
  • storage: Storage backend ("cookie", "local_storage", or "session_storage").
  • case_insensitive: Whether stored variant values match keys case-insensitively.
  • cookie_max_age: Max-Age in seconds when storage="cookie".
  • cookie_samesite: SameSite attribute when storage="cookie".

Attributes:

  • key: Storage key name.
  • variants: Read-only mapping of variant names to CSS strings.
  • default: Default variant key.
  • storage: Storage backend identifier.
  • case_insensitive: Whether lookup matches variant names case-insensitively.
  • cookie_max_age: Cookie lifetime in seconds.
  • cookie_samesite: Cookie SameSite policy.

reactive_block#

def reactive_block(selector: str, content: ReactiveValue) -> Computed[str]

Key: webcompy.app.styles:reactive_block · Exports: from webcompy.app import reactive_block

Build {selector} { {content} } where content is a single CSS block.

Useful for arbitrary CSS, not just variable declarations. content may be a plain string, a SignalBase[str], or a callable returning a string.

Example: >>> app.append_style(reactive_block("body", Computed(lambda: f"color: {fg.value};")))

Args:

  • selector: CSS selector the style rule applies to.
  • content: A single CSS block of declarations for the selector.

Returns: A Computed[str] containing the rendered style block.

reactive_style#

def reactive_style(selector: str, vars: VarsMapping) -> Computed[str]

Key: webcompy.app.styles:reactive_style · Exports: from webcompy.app import reactive_style

Build {selector} { --x: v; --y: w; } from a var name -> value mapping.

Values may be plain strings, SignalBase[str] instances, or callables returning strings. The returned Computed[str] re-evaluates whenever any tracked signal changes.

Example: >>> app.append_style(reactive_style(":root", { ... "--color-accent": Signal("#0969da"), ... "--color-bg": "white", ... }))

Args:

  • selector: CSS selector the style rule applies to.
  • vars: Mapping of CSS variable names to reactive values.

Returns: A Computed[str] containing the rendered style block.

RenderContext#

class RenderContext(ABC):
    def __init__(
        self,
        app: WebComPyApp,
        path: str | None = None,
        *,
        initial_theme: Any = None,
        cookie_header: str | None = None,
    ) -> None

Key: webcompy.app._render_context:RenderContext · Exports: from webcompy.app import RenderContext

Per-render context encapsulating one application render operation.

Owns the DI scope, component store, router clone, and document root used for a single render. Head management and HTML mutation calls are forwarded to the document root, and dispose releases all bound resources. BrowserRenderContext is the default implementation; server deployments provide their own subclass for SSR/SSG.

Args:

  • app: Application this context renders for.
  • path: Initial route path to open.
  • initial_theme: Initial theme override.
  • cookie_header: Raw Cookie header used to resolve the initial theme.

Attributes:

  • hydration_report: Hydration mismatch records collected during this render.
  • routes: Routes exposed by the context's router, or None when there is no router.
  • router_mode: Mode of the context's router, or None when there is no router.
  • head: Reactive head data aggregated for this context.
  • scoped_styles: Scoped styles registered through this context, keyed by component id.
  • scripts: Script tuples appended through this context.
  • html_attrs: Document-level attributes managed by this context.
  • config: The application configuration this context renders with.
  • di_scope: The context's DIScope.

Members#

append_link (method)

def append_link(self, attributes: dict[str, str]) -> None

Append a link element to the document head.

Args:

  • attributes: HTML attributes of the link element.

append_script (method)

def append_script(
    self,
    attributes: dict[str, str],
    script: str | None = None,
    in_head: bool = False,
    pre_paint: bool = False,
) -> None

Append a script element.

Args:

  • attributes: HTML attributes of the script element.
  • script: Inline script body when the script is inlined.
  • in_head: Whether the script goes in <head> instead of <body>.
  • pre_paint: Whether to schedule the script synchronously in the <head> pre-paint slot before stylesheets.

append_style (method)

def append_style(self, content: str | Computed[str] | PrePaintStyle) -> None

Inject an app-level style.

Args:

  • content: CSS content, a reactive Computed producing it, or a declarative PrePaintStyle descriptor.

config (property)

@property
def config(self) -> WebComPyAppConfig

Return the application configuration.

Returns: The WebComPyAppConfig of the application.

di_scope (property)

@property
def di_scope(self) -> DIScope

Return the DI scope of this context.

Returns: The DIScope owning this context's provided values.

dispose (method)

def dispose(self) -> None

Release all resources bound to this render context.

head (property)

@property
def head(self)

Return the reactive head data of the document.

Returns: The head data aggregated for this context.

html_attrs (property)

@property
def html_attrs(self)

Return the attributes managed on the document element.

Returns: The document-level attributes of this context.

hydration_report (property)

@property
def hydration_report(self) -> tuple[HydrationMismatchRecord, ...]

Return the hydration mismatch records collected during this render.

Returns: Tuple of hydration mismatch records.

provide (method)

def provide(self, key: object, value: Any) -> None

Provide a value in the DI scope of this context.

Args:

  • key: Injection key the value is registered under.
  • value: Value provided under key.

remove_html_attr (method)

def remove_html_attr(self, key: str) -> None

Remove an attribute from the document element.

Args:

  • key: Attribute name.

render_html (async_method)

async def render_html(self, **kwargs: Any) -> str

Render the document into an HTML string.

Args:

  • **kwargs: Keyword arguments forwarded through the render pipeline.

Returns: The generated HTML string.

Raises:

  • WebComPyException: Always, because the browser context cannot produce an HTML string.

router_mode (property)

@property
def router_mode(self)

Return the router mode of this context.

Returns: The mode of the context's router, or None when there is no router.

routes (property)

@property
def routes(self)

Return the routes of this context.

Returns: The routes exposed by the context's router, or None when there is no router.

scoped_styles (property)

@property
def scoped_styles(self)

Return the scoped styles registered through this context.

Returns: Mapping of component ids to their scoped CSS rules.

scripts (property)

@property
def scripts(self)

Return the scripts appended to the document body.

Returns: List of script tuples appended through this context.

set_head (method)

def set_head(self, head: Any) -> None

Replace the head VDOM of the document.

Args:

  • head: The new head data.

set_html_attr (method)

def set_html_attr(self, key: str, value: Any) -> None

Set an attribute on the document element.

Args:

  • key: Attribute name.
  • value: Attribute value.

set_meta (method)

def set_meta(self, key: str, attributes: dict[str, str]) -> None

Add or replace a meta tag in the document head.

Args:

  • key: Identifier of the meta tag.
  • attributes: HTML attributes of the meta tag.

set_path (method)

def set_path(self, path: str)

Open the given route path.

Args:

  • path: The route path to open.

Returns: The result of the underlying navigation of the document root.

set_title (method)

def set_title(self, title: str) -> None

Set the document title.

Args:

  • title: The document title to set.

update_head (method)

def update_head(self, head: Any) -> None

Merge data into the head VDOM of the document.

Args:

  • head: Head data merged into the current head.

use_pre_paint_style#

def use_pre_paint_style(spec: PrePaintStyle) -> Signal[str]

Key: webcompy.app.styles:use_pre_paint_style · Exports: from webcompy.app import use_pre_paint_style

Resolve the per-context reactive Signal[str] for a registered PrePaintStyle.

Args:

  • spec: PrePaintStyle instance previously registered with app.append_style(spec).

Returns: The per-render-context Signal[str] holding the active variant name.

Raises:

  • TypeError: If spec is not a PrePaintStyle instance.
  • LookupError: If no active render context exists or spec was not registered via app.append_style(spec).

WebComPyApp#

class WebComPyApp:
    def __init__(
        self,
        *,
        root_component: ComponentGenerator[None],
        router: Router | None = None,
        config: WebComPyAppConfig | None = None,
        _render_context_class: type[RenderContext] | None = None,
    ) -> None

Key: webcompy.app._app:WebComPyApp · Exports: from webcompy.app import WebComPyApp

Application object bootstrapping the root component into the page.

Owns the per-app configuration, router, plugin manager, and RPC registry. Head management and DI provisioning calls are forwarded to the active render context, or deferred until one is created. In the browser, run mounts and renders the root component at the configured selector.

See https://webcompy.net/llms.txt for LLM-readable API documentation.

Args:

  • root_component: Generator function producing the root component.
  • router: Router defining the application's pages, when any.
  • config: Application configuration (defaults to WebComPyAppConfig()).
  • _render_context_class: Render context class override, used for testing and server-side rendering.

Attributes:

  • config: The WebComPyAppConfig of this application.
  • rpc: The ProcedureRegistry used to register RPC procedures.
  • profile_data: Mapping of phase names to timestamps when profiling is enabled, None otherwise.
  • di_scope: DI scope of the active render context; raises AttributeError without an active context.
  • router: The configured Router, or None when unset.
  • routes: Routes of the active render context, falling back to the configured router's routes.
  • router_mode: Router mode of the active render context, falling back to the configured router's mode.
  • head: Reactive head data of the active render context.
  • scoped_styles: Scoped styles collected by the active render context, keyed by component id.
  • scripts: Script tuples appended through the active render context.
  • html_attrs: Attributes managed on the document element; raises AttributeError without an active RenderContext.

Members#

append_link (method)

def append_link(self, attributes: dict[str, str]) -> None

Append a link element to the head, deferring the call until a render context exists.

Args:

  • attributes: HTML attributes of the link element.

append_script (method)

def append_script(
    self,
    attributes: dict[str, str],
    script: str | None = None,
    in_head: bool = False,
    pre_paint: bool = False,
) -> None

Append a script element, deferring the call until a render context exists.

Args:

  • attributes: HTML attributes of the script element.
  • script: Inline script body when the script is inlined.
  • in_head: Whether the script goes in <head> instead of <body>.
  • pre_paint: Whether to schedule the script synchronously in the <head> pre-paint slot before stylesheets.

append_style (method)

def append_style(self, content: str | Computed[str] | PrePaintStyle) -> None

Inject an app-level style, deferring the call until a render context exists.

Args:

  • content: CSS content, a reactive Computed producing it, or a declarative PrePaintStyle descriptor.

config (property)

@property
def config(self) -> WebComPyAppConfig

Return the application configuration.

Returns: The WebComPyAppConfig of this application.

create_render_context (method)

def create_render_context(
    self,
    path: str | None = None,
    *,
    initial_theme: Any = None,
    cookie_header: str | None = None,
) -> RenderContext

Create a render context and make it the active one for this application.

Args:

  • path: Initial route path to open in the created context.
  • initial_theme: Initial theme override for the created context.
  • cookie_header: Raw Cookie header value used to resolve the initial theme.

Returns: The newly created render context.

di_scope (property)

@property
def di_scope(self)

Return the DI scope of the active render context.

Returns: The active DIScope.

Raises:

  • AttributeError: When no render context is active.

head (property)

@property
def head(self)

Return the head data of the active render context.

Returns: The reactive head data of the active context.

Raises:

  • AttributeError: When no render context is active.

html_attrs (property)

@property
def html_attrs(self)

Return the attributes managed on the document element.

Returns: The html attributes of the active context.

Raises:

  • AttributeError: When no render context is active.

profile_data (property)

@property
def profile_data(self) -> dict[str, float] | None

Return per-phase timing data, available only when profiling is on.

Returns: Mapping of phase names to time.perf_counter timestamps, or None when profiling is disabled.

provide (method)

def provide(self, key: object, value: Any) -> None

Provide a value in the app DI scope, deferring until a render context exists.

Args:

  • key: Injection key the value is registered under.
  • value: Value provided under key.

remove_html_attr (method)

def remove_html_attr(self, key: str) -> None

Remove an attribute from the document element, deferring the call until a render context exists.

Args:

  • key: Attribute name.

router (property)

@property
def router(self)

Return the router configured on this application.

Returns: The Router of this application, or None when unset.

router_mode (property)

@property
def router_mode(self)

Return the router mode of the active render context, falling back to the configured router.

Returns: The router mode of the active context when one exists, otherwise the mode of the configured router.

routes (property)

@property
def routes(self)

Return the routes of the active render context, falling back to the configured router.

Returns: The routes of the active context when one exists, otherwise the routes of the configured router (or None).

rpc (property)

@property
def rpc(self) -> ProcedureRegistry

Return the JSON-RPC procedure registry of this application.

Returns: The ProcedureRegistry used to register RPC procedures.

run (method)

def run(self) -> None

Mount and render the application in the browser.

Raises:

  • WebComPyException: When called outside a browser (PyScript) environment.

scoped_styles (property)

@property
def scoped_styles(self)

Return the scoped styles collected by the active render context.

Returns: Mapping of component ids to their scoped CSS rules.

Raises:

  • AttributeError: When no render context is active.

scripts (property)

@property
def scripts(self)

Return the scripts appended by the active render context.

Returns: List of script tuples appended through the active context.

Raises:

  • AttributeError: When no render context is active.

set_head (method)

def set_head(self, head: Any) -> None

Replace the head VDOM, deferring the call until a render context exists.

Args:

  • head: The new head data.

set_html_attr (method)

def set_html_attr(self, key: str, value: Any) -> None

Set an attribute on the document element, deferring the call until a render context exists.

Args:

  • key: Attribute name.
  • value: Attribute value.

set_meta (method)

def set_meta(self, key: str, attributes: dict[str, str]) -> None

Add or replace a meta tag, deferring the call until a render context exists.

Args:

  • key: Identifier of the meta tag.
  • attributes: HTML attributes of the meta tag.

set_path (method)

def set_path(self, path: str)

Change the active route path.

Args:

  • path: The new route path.

Returns: The result of the underlying navigation, or None when no context exists in the browser.

Raises:

  • AttributeError: When called on the server without an active render context.

set_title (method)

def set_title(self, title: str) -> None

Set the document title, deferring the call until a render context exists.

Args:

  • title: The document title to set.

update_head (method)

def update_head(self, head: Any) -> None

Merge data into the head VDOM, deferring the call until a render context exists.

Args:

  • head: Head data merged into the current head.

WebComPyAppConfig#

class WebComPyAppConfig:
    base_url: str = '/'
    selector: str = '#webcompy-app'
    profile: bool = False
    hydrate: bool = True
    scroll_restoration: bool = True
    scripts: list[PluginScript] = field(default_factory=list)
    plugins: list[str] = field(default_factory=list)
    theme: dict | None = None
    loading: dict | None = None
    compression_threshold: int | None = 1024
    on_error: Callable[[Exception], Any] | None = None

Key: webcompy.app._config:WebComPyAppConfig · Exports: from webcompy import WebComPyAppConfig, from webcompy.app import WebComPyAppConfig

Configuration of a WebComPyApp.

Args:

  • base_url: Base URL the application is served under (defaults to "/").
  • selector: CSS selector of the page element the application mounts into.
  • profile: Whether boot phase timing is recorded and logged.
  • hydrate: Whether server-rendered markup is hydrated in the browser.
  • scroll_restoration: Whether scrolling is managed across navigations.
  • scripts: Declarative script elements appended by plugins.
  • plugins: Plugin module paths discovered at startup.
  • theme: Theme configuration (default and persist keys).
  • loading: Boot-time loading screen configuration.
  • compression_threshold: Minimum payload size in bytes before the hydration payload is gzip-compressed.
  • on_error: Callback invoked when a render operation raises an exception.

Attributes:

  • base_url: Base URL the application is served under (defaults to "/").
  • selector: CSS selector of the page element the application mounts into.
  • profile: Whether boot phase timing is recorded and logged.
  • hydrate: Whether server-rendered markup is hydrated in the browser.
  • scroll_restoration: Whether scrolling is managed across navigations.
  • scripts: Declarative script elements appended by plugins.
  • plugins: Plugin module paths discovered at startup.
  • theme: Theme configuration (default and persist keys).
  • loading: Boot-time loading screen configuration.
  • compression_threshold: Minimum payload size in bytes before the hydration payload is gzip-compressed.
  • on_error: Callback invoked when a render operation raises an exception.

Components & Lifecycle#

Component#

class Component(ElementBase):
    def __init__(
        self,
        component_def: FuncComponentDef,
        props: Any,
        slots: dict[str, Callable[[], ElementChildren]],
        generator: ComponentGenerator[Any] | None = None,
    ) -> None

Key: webcompy.components._component:Component · Exports: from webcompy.components import Component

Element node that runs a component definition and renders its result.

A Component wraps a function-style component definition: it creates the component Context (props, slots, lifecycle hooks, title/meta access), runs the setup function to obtain the template, and drives the lifecycle hooks (on_before_rendering, on_after_rendering, on_before_destroy, on_mounted, on_unmounted) around rendering, mounting, and removal. Async setup functions are supported through a two-phase render pipeline.

Normally obtained by calling a ComponentGenerator (the object returned by define_component); the framework constructs one per component instantiation site.

Args:

  • component_def: The component setup function.
  • props: Props object passed to the setup function.
  • slots: Mapping of slot names to child generators.
  • generator: The ComponentGenerator producing custom element metadata for named components.

component_context#

def component_context(state: ComponentRenderState) -> Generator[None, None, None]

Key: webcompy.components._context_manager:component_context · Exports: from webcompy.components import component_context

Activate state for the duration of a with block.

Inside the block, composables and lifecycle hooks target this component's context and effects join its effect scope.

Args:

  • state: Render state to activate.

Returns: A context manager that restores the previous state upon exit.

ComponentContext#

class ComponentContext(Protocol[PropsType])

Key: webcompy.components._libs:ComponentContext · Exports: from webcompy.components import ComponentContext

Interface the component setup function receives.

The framework passes an implementation of this protocol as the setup function's argument: it exposes props, named slots, lifecycle hook registration, document head helpers, DI provisioning, and reactive scoped style registration.

Attributes:

  • props: The props object passed to the component.
  • transfer_id: The hydration-stable per-instance id of the component.

Members#

get_meta (method)

def get_meta(self) -> dict[str, dict[str, str]]

Return the collected document head meta entries.

Returns: Mapping of meta key to its attribute mapping.

get_title (method)

def get_title(self) -> str

Return the current document title.

Returns: The document title.

on_after_rendering (method)

def on_after_rendering(
    self,
    func: Callable[[], Any] | Callable[[], Coroutine[Any, Any, Any]],
) -> None

Register a hook invoked after the component renders.

Args:

  • func: Hook callback; may be a coroutine function.

on_before_destroy (method)

def on_before_destroy(
    self,
    func: Callable[[], Any] | Callable[[], Coroutine[Any, Any, Any]],
) -> None

Register a hook invoked before the component is destroyed.

Args:

  • func: Hook callback; may be a coroutine function.

on_before_rendering (method)

def on_before_rendering(
    self,
    func: Callable[[], Any] | Callable[[], Coroutine[Any, Any, Any]],
) -> None

Register a hook invoked before the component renders.

Args:

  • func: Hook callback; may be a coroutine function.

on_error_captured (method)

def on_error_captured(self, func: Callable[[Exception], Any]) -> None

Register a hook invoked when a descendant error is captured.

Args:

  • func: Hook callback receiving the raised exception.

on_mounted (method)

def on_mounted(
    self,
    func: Callable[[], Any] | Callable[[], Coroutine[Any, Any, Any]],
) -> None

Register a hook invoked when the component enters the DOM.

Args:

  • func: Hook callback; may be a coroutine function.

on_unmounted (method)

def on_unmounted(
    self,
    func: Callable[[], Any] | Callable[[], Coroutine[Any, Any, Any]],
) -> None

Register a hook invoked when the component leaves the DOM.

Args:

  • func: Hook callback; may be a coroutine function.

props (property)

@property
def props(self) -> PropsType

Return the props object passed to the component.

Returns: The component props.

provide (method)

def provide(self, key: object, value: Any) -> None

Provide a dependency value in the component's DI scope.

Args:

  • key: Dependency key the value is registered under.
  • value: Value to provide.

remove_reactive_scoped_style (method)

def remove_reactive_scoped_style(self, style: ReactiveScopedStyle) -> None

Remove a previously registered reactive scoped style.

Args:

  • style: Reactive scoped style previously registered via use_reactive_scoped_style().

set_meta (method)

def set_meta(self, key: str, attributes: dict[str, str]) -> None

Set a document head meta entry while this component exists.

Args:

  • key: Unique key of the meta entry.
  • attributes: Mapping of attribute names to values.

set_title (method)

def set_title(self, title: str) -> None

Set the document title while this component exists.

Args:

  • title: New document title.

slots (method)

def slots(self, name: str, fallback: NodeGenerator | None = None) -> ElementChildren

Render the named slot contents.

Args:

  • name: Name of the slot to render.
  • fallback: Contents rendered when the slot is not provided.

Returns: The rendered slot children, or the fallback children.

transfer_id (property)

@property
def transfer_id(self) -> str

Return the hydration-stable per-instance transfer id.

Returns: The per-instance stable id string.

use_reactive_scoped_style (method)

def use_reactive_scoped_style(self, style: ReactiveScopedStyle) -> None

Register a reactive scoped style for this component.

Args:

  • style: Reactive scoped style created by reactive_scoped_style().

ComponentDisplay#

ComponentDisplay: TypeAlias = ...

Key: webcompy.components._generator:ComponentDisplay · Exports: from webcompy.components import ComponentDisplay

Supported CSS display modes for named components.

ComponentGenerator#

class ComponentGenerator(Generic[PropsType]):
    def __init__(
        self,
        name: str,
        component_def: FuncComponentDef[PropsType],
        *,
        custom_element_name: str,
        observed_attributes: tuple[str, ...] = (),
        display: ComponentDisplay | None = None,
    ) -> None

Key: webcompy.components._generator:ComponentGenerator · Exports: from webcompy.components import ComponentGenerator

Component instance factory created by define_component.

Calling a generator (MyComponent(props, slots={...})) produces a Component element node. The generator also owns the component's scoped style declarations, custom element name, observed attribute list, and display mode, and registers itself in the active ComponentStore.

Args:

  • name: Custom element name assigned to the component.
  • component_def: The component setup function.
  • custom_element_name: Validated custom element tag name.
  • observed_attributes: Attribute names mirrored into props.
  • display: CSS display mode applied to the component element.

Attributes:

  • custom_element_name: Validated custom element tag name.
  • observed_attributes: Attribute names mirrored into props.
  • observed_prop_keys: Mapping of attribute names to prop keys.
  • definition_key: Key identifying this generator's custom element definition for registry compatibility checks.
  • display: CSS display mode applied to the component element.
  • scoped_style: Compiled scoped style declarations of the component.

Members#

custom_element_name (property)

@property
def custom_element_name(self) -> str

Return the custom element tag name.

Returns: The custom element tag name.

definition_key (property)

@property
def definition_key(self) -> str

Return a stable identifier of the custom element definition.

Returns: A versioned key combining the tag name and sorted observed attributes.

display (property)

@property
def display(self) -> ComponentDisplay | None

Return the assigned CSS display mode.

Returns: The display mode, or None when not assigned.

observed_attributes (property)

@property
def observed_attributes(self) -> tuple[str, ...]

Return the attribute names mirrored into props.

Returns: A tuple of observed attribute names.

observed_prop_keys (property)

@property
def observed_prop_keys(self) -> dict[str, str]

Return the mapping of attribute names to props keys.

Returns: Mapping of observed attribute name to its props key.

scoped_style (property)

@property
def scoped_style(self) -> str

Return the rendered component-scoped CSS.

Returns: The rendered @layer webcompy-scope CSS text.

ComponentProperty#

class ComponentProperty(TypedDict)

Key: webcompy.components._libs:ComponentProperty · Exports: from webcompy.components import ComponentProperty

Bundle of a component instance's resolved setup results and hooks.

Attributes:

  • component_id: Stable identifier of the component instance.
  • component_name: Registered name of the component.
  • transfer_id: Optional stable id used for hydration value transfer; present when a custom transfer key is assigned.
  • template: Rendered template result, or None before render.
  • on_before_rendering: Hook invoked before the component renders.
  • on_after_rendering: Hook invoked after the component renders.
  • on_before_destroy: Hook invoked before the component is destroyed.
  • on_mounted: Hook invoked when the component enters the DOM.
  • on_unmounted: Hook invoked when the component leaves the DOM.

ComponentRenderState#

class ComponentRenderState:
    context: Context[Any]
    effect_scope: EffectScope
    framework_cleanup: Callable[[], None]

Key: webcompy.components._context_manager:ComponentRenderState · Exports: from webcompy.components import ComponentRenderState

Activation state bound to one component setup invocation.

Carries the pieces of ambient state that must be active while the component's setup function (and its re-renders) run: the component Context proxy, the EffectScope collecting effects created during setup, and a cleanup callable disposing framework resources.

Args:

  • context: The component Context proxy for this component.
  • effect_scope: Scope collecting effects created during setup.
  • framework_cleanup: Callable disposing framework-owned resources.

Attributes:

  • context: The component Context proxy for this component.
  • effect_scope: Scope collecting effects created during setup.
  • framework_cleanup: Callable disposing framework-owned resources.

ComponentStore#

class ComponentStore:
    def __init__(self) -> None

Key: webcompy.components._generator:ComponentStore · Internal allowlist entry

Registry of named components.

Attributes:

  • components: Mapping of registered component names to their generators.

Members#

add_component (method)

def add_component(self, name: str, component_generator: ComponentGenerator[Any])

Register a component generator under name.

Args:

  • name: Registered name of the component.
  • component_generator: Generator to associate with the name.

Raises:

  • WebComPyComponentException: If the component name or its custom element name is already registered.

components (property)

@property
def components(self) -> dict[str, ComponentGenerator[Any]]

Return the mapping of component names to generators.

Returns: The name-to-generator registry contents.

define_component#

def define_component(
    custom_element_name: str | None = None,
    *,
    observed_attributes: Iterable[str] = (),
    display: ComponentDisplay | None = None,
) -> Callable[[FuncComponentDef[PropsType]], ComponentGenerator[PropsType]]

Key: webcompy.components._generator:define_component · Exports: from webcompy.components import define_component

Decorate a setup function into a named component generator.

The decorator factory must be called (@define_component(...)). When custom_element_name is provided, its value forms the custom element tag and is validated against the custom-element naming rules; the setup function's name is not compared to it. When omitted, the tag is derived from the decorated function's name by converting PascalCase/camelCase to kebab-case, and only the derived value is validated. Non-round-tripping names such as acronyms are accepted in derived mode.

The component setup function receives the ComponentContext and returns the component template. The decorated function keeps its name and becomes callable as ComponentName(props, slots={...}).

See https://webcompy.net/llms.txt for LLM-readable component docs.

Args:

  • custom_element_name: Custom element tag name (lowercase, must contain a hyphen). Derived from the decorated function's name when omitted.
  • observed_attributes: Attribute names mirrored into the props mapping.
  • display: CSS display mode applied to the component element.

Returns: A decorator producing a ComponentGenerator for the component.

Raises:

  • WebComPyComponentException: If the decorator factory is applied without being called, if arguments are invalid, if the explicit or derived custom element name violates the custom-element naming rules, or if the decorated object is already a component definition.

on_after_rendering#

def on_after_rendering(
    func: Callable[[], Any] | Callable[[], Coroutine[Any, Any, Any]],
) -> Callable[[], Any]

Key: webcompy.components._hooks:on_after_rendering · Exports: from webcompy.components import on_after_rendering

Register a hook invoked after the component renders.

Args:

  • func: Hook callback; may be a coroutine function.

Returns: The registered callback.

Raises:

  • LookupError: If called outside a component setup function.

on_before_destroy#

def on_before_destroy(
    func: Callable[[], Any] | Callable[[], Coroutine[Any, Any, Any]],
) -> Callable[[], Any]

Key: webcompy.components._hooks:on_before_destroy · Exports: from webcompy.components import on_before_destroy

Register a hook invoked before the component is destroyed.

Args:

  • func: Hook callback; may be a coroutine function.

Returns: The registered callback.

Raises:

  • LookupError: If called outside a component setup function.

on_before_rendering#

def on_before_rendering(
    func: Callable[[], Any] | Callable[[], Coroutine[Any, Any, Any]],
) -> Callable[[], Any]

Key: webcompy.components._hooks:on_before_rendering · Exports: from webcompy.components import on_before_rendering

Register a hook invoked before the component renders.

Args:

  • func: Hook callback; may be a coroutine function.

Returns: The registered callback.

Raises:

  • LookupError: If called outside a component setup function.

on_error_captured#

def on_error_captured(func: Callable[[Exception], Any]) -> Callable[[Exception], Any]

Key: webcompy.components._hooks:on_error_captured · Exports: from webcompy.components import on_error_captured

Register a hook invoked when a descendant error is captured.

Args:

  • func: Hook callback receiving the raised exception.

Returns: The registered callback.

Raises:

  • LookupError: If called outside a component setup function.

on_mounted#

def on_mounted(
    func: Callable[[], Any] | Callable[[], Coroutine[Any, Any, Any]],
) -> Callable[[], Any]

Key: webcompy.components._hooks:on_mounted · Exports: from webcompy.components import on_mounted

Register a hook invoked when the component's node enters the DOM.

Args:

  • func: Hook callback; may be a coroutine function.

Returns: The registered callback.

Raises:

  • LookupError: If called outside a component setup function.

on_unmounted#

def on_unmounted(
    func: Callable[[], Any] | Callable[[], Coroutine[Any, Any, Any]],
) -> Callable[[], Any]

Key: webcompy.components._hooks:on_unmounted · Exports: from webcompy.components import on_unmounted

Register a hook invoked when the component's node leaves the DOM.

Args:

  • func: Hook callback; may be a coroutine function.

Returns: The registered callback.

Raises:

  • LookupError: If called outside a component setup function.

reactive_scoped_style#

def reactive_scoped_style(func: ReactiveScopedStyleFunc) -> ReactiveScopedStyle

Key: webcompy.components._reactive_scoped_style:reactive_scoped_style · Exports: from webcompy.components import reactive_scoped_style

Create a reactive scoped style from a style callable.

Register the returned style with context.use_reactive_scoped_style(style) inside a @define_component setup function.

Args:

  • func: Zero-argument callable returning the style dictionary.

Returns: A ReactiveScopedStyle wrapping func in a Computed.

ReactiveScopedStyle#

class ReactiveScopedStyle:
    def __init__(self, func: ReactiveScopedStyleFunc) -> None

Key: webcompy.components._reactive_scoped_style:ReactiveScopedStyle · Exports: from webcompy.components import ReactiveScopedStyle

Reactive per-component scoped style.

Wraps a synchronous callable returning the scoped-style declaration shape (selector to declarations). The callable runs inside a Computed; register the instance with context.use_reactive_scoped_style(style) inside a @define_component setup function so the framework updates the emitted <style> element whenever a tracked signal changes.

Args:

  • func: Zero-argument callable returning the style dictionary.

Raises:

  • TypeError: If func is a coroutine function.

Attributes:

  • ref_count: How many component instances use this style.
  • subscription: Consumer node updating the emitted style element, or None before registration.
  • is_removed: Whether the style was removed from its component.
  • dict_computed: The Computed holding the raw style dictionary.
  • css_computed: The Computed holding the rendered, scoped CSS.

Members#

css_computed (property)

@property
def css_computed(self) -> Computed[str]

Return the computed holding the rendered, scoped CSS.

Returns: The Computed wrapping render_css().

Raises:

  • WebComPyComponentException: If the style is not yet bound to a component.

decrement_ref (method)

def decrement_ref(self) -> int

Record that one component instance released this style.

Returns: The new reference count.

dict_computed (property)

@property
def dict_computed(self) -> Computed[Any]

Return the computed holding the raw style dictionary.

Returns: The Computed wrapping the style callable.

Raises:

  • WebComPyComponentException: If the style is not yet bound to a component.

increment_ref (method)

def increment_ref(self) -> int

Record one more component instance using this style.

Returns: The new reference count.

is_removed (property)

@property
def is_removed(self) -> bool

Return whether the style was removed from its component.

Returns: True after mark_removed() was called.

mark_removed (method)

def mark_removed(self) -> None

Mark the style as removed from its component.

ref_count (property)

@property
def ref_count(self) -> int

Return how many component instances use this style.

Returns: The current reference count.

render_css (method)

def render_css(self, cid: str) -> str

Render the current style dictionary as scoped CSS text.

Args:

  • cid: Component id used to scope the selectors.

Returns: The rendered @layer webcompy-scope CSS text, or an empty string when the style dictionary is empty.

Raises:

  • WebComPyComponentException: If the style is bound without a host tag.

set_subscription (method)

def set_subscription(self, subscription: Any) -> None

Store the consumer node updating the emitted style element.

Args:

  • subscription: The consumer node to store.

subscription (property)

@property
def subscription(self) -> Any | None

Return the consumer node updating the emitted style element.

Returns: The subscription node, or None before registration.

use_async#

def use_async(func: Callable[[], Coroutine[Any, Any, Any]]) -> None

Key: webcompy.components._hooks:use_async · Exports: from webcompy.components import use_async

Run an async operation after every component render.

The wrapped operation is executed after each rendering; results are fire-and-forget. Use use_async_result() when the pending/error state must be observable.

Args:

  • func: Async operation factory; run without arguments.

use_async_result#

def use_async_result(
    func: Callable[[], Coroutine[Any, Any, T]],
    *,
    default: T | None = None,
    immediate: bool = True,
    watch: Iterable[SignalBase[Any]] = (),
    transfer: bool = True,
) -> AsyncResult[T]

Key: webcompy.components._hooks:use_async_result · Exports: from webcompy.components import use_async_result

Expose an async operation's state as an AsyncResult.

Called inside a component setup function, the result is registered with the component so its state can be transferred from SSR. Unless immediate is False, the operation starts right after the first render; listed watch signals refetch whenever they change.

Args:

  • func: Async operation factory; run without arguments.
  • default: Value exposed while the operation is pending.
  • immediate: Whether to start the operation after first render.
  • watch: Signals that trigger a refetch upon change.
  • transfer: Whether the result state transfers from SSR.

Returns: The AsyncResult tracking the operation's lifecycle.

WebComPyComponentException#

class WebComPyComponentException(WebComPyException)

Key: webcompy.components._libs:WebComPyComponentException · Exports: from webcompy.components import WebComPyComponentException

Error raised for invalid component definitions or usage.

Plugins#

PluginManager#

class PluginManager:
    def __init__(self, app: WebComPyApp) -> None

Key: webcompy.plugin._manager:PluginManager · Exports: from webcompy.app import PluginManager, from webcompy.plugin import PluginManager

Discover plugin classes and drive their lifecycle hooks for one app.

Plugin paths are resolved with discover, instantiated with init_all, and then called back per render context (init_render_context) and once the app is ready (call_on_app_ready).

Args:

  • app: Application instance the plugins extend.

Attributes:

  • scripts: Aggregated scripts contributed by all discovered plugins.

Members#

call_on_app_ready (method)

def call_on_app_ready(self, ctx: RenderContext) -> None

Notify all plugins that the application is ready.

Args:

  • ctx: Render context active when the application becomes ready.

discover (method)

def discover(self, plugin_paths: list[str]) -> None

Resolve "module:ClassName" paths to plugin subclasses.

Args:

  • plugin_paths: Plugin references formatted as "module:ClassName".

Raises:

  • WebComPyPluginException: If a path is malformed or does not point to a WebComPyPlugin subclass.

init_all (method)

def init_all(self) -> None

Instantiate all discovered plugins and call their on_app_init hooks.

init_render_context (method)

def init_render_context(self, ctx: RenderContext) -> None

Provide plugin DI values and initialize plugins for a render context.

Args:

  • ctx: Render context receiving the plugin providers and lifecycle callbacks.

scripts (property)

@property
def scripts(self) -> list[PluginScript]

Aggregate scripts contributed by all discovered plugins.

WebComPyPlugin#

class WebComPyPlugin

Key: webcompy.plugin._plugin:WebComPyPlugin · Exports: from webcompy.app import WebComPyPlugin, from webcompy.plugin import WebComPyPlugin

Base class for WebComPy plugins providing lifecycle hooks and DI providers.

Subclass WebComPyPlugin to expose dependency-injection providers, inject client-side scripts, and hook into application and render-context lifecycle.

Attributes:

  • name: Human-readable plugin identifier.
  • version: Plugin version string.

Members#

get_fetch_middlewares (method)

@staticmethod
def get_fetch_middlewares() -> list[Any]

Return fetch middlewares contributed by the plugin.

Returns: List of FetchMiddleware callables applied in the order returned (index 0 outermost). An empty list contributes nothing.

get_providers (method)

@staticmethod
def get_providers() -> dict[object, Any]

Return DI providers contributed by the plugin.

Returns: Mapping of DI keys to provider values contributed for each render context.

get_rpc_middlewares (method)

@staticmethod
def get_rpc_middlewares() -> list[Any]

Return RPC middlewares contributed by the plugin.

Returns: List of RpcMiddleware callables applied in the order returned (index 0 outermost). An empty list contributes nothing.

get_scripts (method)

@staticmethod
def get_scripts() -> list[PluginScript]

Return scripts injected by the plugin.

Returns: List of PluginScript descriptors describing script elements to add to the rendered page.

on_app_init (method)

def on_app_init(self, app: WebComPyApp) -> None

Handle application initialization.

Args:

  • app: Application instance being initialized.

on_app_ready (method)

def on_app_ready(self, ctx: RenderContext) -> None

Handle the application becoming ready.

Args:

  • ctx: Render context active when the application is ready.

on_render_context_init (method)

def on_render_context_init(self, ctx: RenderContext) -> None

Handle creation of a new render context.

Args:

  • ctx: Render context being initialized.

WebComPyPluginException#

class WebComPyPluginException(Exception)

Key: webcompy.plugin._plugin:WebComPyPluginException · Exports: from webcompy.app import WebComPyPluginException, from webcompy.plugin import WebComPyPluginException

Error raised for invalid plugin configuration or lifecycle failures.

Exceptions & Utilities#

ENVIRONMENT#

ENVIRONMENT: Final[Literal['pyscript', 'other']] = _get_environment()

Key: webcompy.utils._environment:ENVIRONMENT · Exports: from webcompy.utils import ENVIRONMENT

Active runtime marker, "pyscript" in the PyScript browser runtime and "other" elsewhere.

IS_EMSCRIPTEN#

IS_EMSCRIPTEN: Final[bool] = _is_emscripten()

Key: webcompy.utils._environment:IS_EMSCRIPTEN · Exports: from webcompy.utils import IS_EMSCRIPTEN

Whether the active Python runtime executes under Emscripten/Pyodide.

is_json_seriarizable#

def is_json_seriarizable(obj: Any) -> bool

Key: webcompy.utils._serialize:is_json_seriarizable · Exports: from webcompy.utils import is_json_seriarizable

Return whether obj is JSON-serializable as a top-level list or dict.

Args:

  • obj: Value to test.

Returns: True if obj is a list or dict whose contents are recursively JSON-serializable (string-keyed dicts, primitives, None, and nested lists/dicts).

kebab_to_pascal#

def kebab_to_pascal(kebab: str) -> str

Key: webcompy.utils._casing:kebab_to_pascal · Exports: from webcompy.template import kebab_to_pascal

Convert kebab-case to PascalCase.

Args:

  • kebab: kebab-case input string; hyphen-separated parts are individually capitalized.

Returns:

The PascalCase string.

kebab_to_pascal("user-card") 'UserCard' >>> kebab_to_pascal("my-widget") 'MyWidget' >>> kebab_to_pascal("a-b-c") 'ABC'

kebab_to_snake#

def kebab_to_snake(kebab: str) -> str

Key: webcompy.utils._casing:kebab_to_snake · Exports: from webcompy.template import kebab_to_snake

Convert kebab-case to snake_case.

Args:

  • kebab: kebab-case input string; each hyphen is replaced with an underscore without further normalization.

Returns:

The snake_case string.

kebab_to_snake("item-count") 'item_count' >>> kebab_to_snake("data-value") 'data_value'

pascal_to_kebab#

def pascal_to_kebab(name: str) -> str

Key: webcompy.utils._casing:pascal_to_kebab · Exports: from webcompy.template import pascal_to_kebab

Convert PascalCase to kebab-case.

Args:

  • name: PascalCase (or camelCase) input string; acronym runs are split on case boundaries ("MyHTTPClient" → "my-http-client").

Returns:

The kebab-case string.

pascal_to_kebab("UserCard") 'user-card' >>> pascal_to_kebab("ToDoListPage") 'to-do-list-page' >>> pascal_to_kebab("MyHTTPClient") 'my-http-client'

strip_multiline_text#

def strip_multiline_text(text: str)

Key: webcompy.utils._text:strip_multiline_text · Exports: from webcompy.utils import strip_multiline_text

Strip leading blank lines and dedent the remaining block.

Args:

  • text: Multiline string whose first line determines the common leading whitespace to remove.

Returns: The dedented text with leading blank lines removed.

WebComPyException#

class WebComPyException(Exception)

Key: webcompy.exception:WebComPyException · Exports: from webcompy.exception import WebComPyException, from webcompy.template import WebComPyException

Base class for all WebComPy exceptions.

Next steps#