CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-reflex

Web apps in pure Python with reactive components and automatic frontend generation.

Pending
Overview
Eval results
Files

event-system.mddocs/

Event System

Type-safe event handling system connecting frontend interactions to backend state changes with automatic synchronization, JavaScript integration, and comprehensive DOM manipulation capabilities.

Capabilities

Event Handler Creation

Core event handling mechanisms for connecting UI interactions to state changes with type safety and automatic serialization.

def event(fn: Callable) -> EventHandler:
    """
    Create an event handler from a function.
    
    Converts a regular function into a Reflex event handler that can
    be triggered from frontend interactions and automatically updates state.
    
    Args:
        fn: Function to convert to event handler
    
    Returns:
        EventHandler instance with automatic state synchronization
    """
    ...

class EventHandler:
    """
    Core event handler implementation for state changes.
    
    Represents a callable event that can be triggered from the frontend
    and executes backend logic with automatic state synchronization.
    """
    
    fn: Callable
    """The underlying function to execute."""
    
    args: tuple
    """Arguments to pass to the function."""
    
    kwargs: dict
    """Keyword arguments to pass to the function."""
    
    def __init__(self, fn: Callable, args: tuple = (), kwargs: dict = None) -> None:
        """
        Initialize event handler with function and arguments.
        
        Args:
            fn: Function to wrap as event handler
            args: Positional arguments for the function
            kwargs: Keyword arguments for the function
        """
        ...
    
    def __call__(self, *args, **kwargs) -> EventHandler:
        """
        Create new event handler with additional arguments.
        
        Args:
            *args: Additional positional arguments
            **kwargs: Additional keyword arguments
        
        Returns:
            New EventHandler with combined arguments
        """
        ...

class EventChain:
    """
    Chain multiple event handlers to execute in sequence.
    
    Allows combining multiple event handlers that execute one after
    another, useful for complex interactions requiring multiple actions.
    """
    
    events: list[EventHandler]
    """List of event handlers to execute in sequence."""
    
    def __init__(self, *events: EventHandler) -> None:
        """
        Initialize event chain with handlers.
        
        Args:
            *events: Event handlers to execute in order
        """
        ...
    
    def add_event(self, event: EventHandler) -> EventChain:
        """
        Add another event handler to the chain.
        
        Args:
            event: Event handler to append to chain
        
        Returns:
            Updated event chain with new handler
        """
        ...

Browser Actions

Direct browser manipulation and interaction capabilities for enhanced user experience and integration with browser APIs.

def redirect(
    path: str | Var[str],
    is_external: bool = False,
    replace: bool = False,
) -> EventSpec:
    """
    Redirect to a new path.
    
    Args:
        path: The path to redirect to
        is_external: Whether to open in new tab or not
        replace: If True, the current page will not create a new history entry
    
    Returns:
        EventSpec that performs navigation when triggered
    """
    ...

def console_log(message: str | Var[str]) -> EventSpec:
    """
    Do a console.log on the browser.
    
    Args:
        message: The message to log
    
    Returns:
        An event to log the message
    """
    ...

def window_alert(message: str | Var[str]) -> EventSpec:
    """
    Create a window alert on the browser.
    
    Args:
        message: The message to alert
    
    Returns:
        An event to alert the message
    """
    ...

def download(
    url: str | Var | None = None,
    filename: str | Var | None = None,
    data: str | bytes | Var | None = None,
) -> EventSpec:
    """
    Download the file at a given path or with the specified data.
    
    Args:
        url: The URL to the file to download
        filename: The name that the file should be saved as after download
        data: The data to download
    
    Returns:
        EventSpec that triggers download when executed
    """
    ...

def set_clipboard(content: str | Var[str]) -> EventSpec:
    """
    Set the text in content in the clipboard.
    
    Args:
        content: The text to add to clipboard
    
    Returns:
        EventSpec: An event to set some content in the clipboard
    """
    ...

def set_focus(element_id: str) -> EventHandler:
    """
    Set focus to a specific element by ID.
    
    Args:
        element_id: DOM element ID to focus
    
    Returns:
        EventHandler that focuses element when triggered
    """
    ...

def scroll_to(elem_id: str, align_to_top: bool | Var[bool] = True) -> EventSpec:
    """
    Select the id of a html element for scrolling into view.
    
    Args:
        elem_id: The id of the element to scroll to
        align_to_top: Whether to scroll to the top (True) or bottom (False) of the element
    
    Returns:
        An EventSpec to scroll the page to the selected element
    """
    ...

def set_value(element_id: str, value: str) -> EventHandler:
    """
    Set the value of a form element.
    
    Args:
        element_id: Form element ID to update
        value: New value to set
    
    Returns:
        EventHandler that updates element value when triggered
    """
    ...

Storage Management

Browser storage manipulation for client-side data persistence using localStorage, sessionStorage, and cookies.

def clear_local_storage() -> EventHandler:
    """
    Clear all browser localStorage data.
    
    Removes all key-value pairs from browser localStorage,
    useful for logout functionality or data cleanup.
    
    Returns:
        EventHandler that clears localStorage when triggered
    """
    ...

def remove_local_storage(key: str) -> EventHandler:
    """
    Remove specific key from localStorage.
    
    Args:
        key: localStorage key to remove
    
    Returns:
        EventHandler that removes localStorage item when triggered
    """
    ...

def clear_session_storage() -> EventHandler:
    """
    Clear all browser sessionStorage data.
    
    Returns:
        EventHandler that clears sessionStorage when triggered
    """
    ...

def remove_session_storage(key: str) -> EventHandler:
    """
    Remove specific key from sessionStorage.
    
    Args:
        key: sessionStorage key to remove
    
    Returns:
        EventHandler that removes sessionStorage item when triggered
    """
    ...

def remove_cookie(name: str, path: str = "/") -> EventHandler:
    """
    Remove browser cookie by name.
    
    Args:
        name: Cookie name to remove
        path: Cookie path (defaults to root path)
    
    Returns:
        EventHandler that removes cookie when triggered
    """
    ...

JavaScript Integration

Direct JavaScript code execution and function calls for advanced browser interactions and third-party library integration.

def call_script(script: str) -> EventHandler:
    """
    Execute arbitrary JavaScript code in the browser.
    
    Allows running custom JavaScript code for advanced interactions,
    third-party library integration, or browser API access.
    
    Args:
        script: JavaScript code string to execute
    
    Returns:
        EventHandler that executes JavaScript when triggered
    """
    ...

def run_script(script: str) -> EventHandler:
    """
    Alias for call_script - execute JavaScript code.
    
    Args:
        script: JavaScript code string to execute
    
    Returns:
        EventHandler that runs JavaScript when triggered
    """
    ...

def call_function(function_name: str, *args) -> EventHandler:
    """
    Call a specific JavaScript function with arguments.
    
    Invokes a JavaScript function available in the global scope
    with the provided arguments, useful for library integration.
    
    Args:
        function_name: Name of JavaScript function to call
        *args: Arguments to pass to the JavaScript function
    
    Returns:
        EventHandler that calls JavaScript function when triggered
    """
    ...

Event Control

Event flow control mechanisms for managing event propagation, preventing default behaviors, and handling edge cases.

def prevent_default() -> EventHandler:
    """
    Prevent default browser behavior for an event.
    
    Calls preventDefault() on the DOM event to stop default
    browser actions like form submission or link navigation.
    
    Returns:
        EventHandler that prevents default behavior when triggered
    """
    ...

def stop_propagation() -> EventHandler:
    """
    Stop event from bubbling up the DOM tree.
    
    Calls stopPropagation() on the DOM event to prevent it
    from triggering handlers on parent elements.
    
    Returns:
        EventHandler that stops event propagation when triggered
    """
    ...

def noop() -> EventHandler:
    """
    No-operation event handler that does nothing.
    
    Useful as a placeholder or to disable event handling
    temporarily while maintaining component interfaces.
    
    Returns:
        EventHandler that performs no action when triggered
    """
    ...

File Upload Events

Specialized event handlers for file upload operations with progress tracking and validation support.

def upload_files(
    upload_id: str = "",
    multiple: bool = False
) -> EventHandler:
    """
    Trigger file upload dialog and handle file selection.
    
    Opens browser file picker and processes selected files
    through the Reflex upload system with progress tracking.
    
    Args:
        upload_id: Unique identifier for upload session
        multiple: Whether to allow multiple file selection
    
    Returns:
        EventHandler that manages file upload process when triggered
    """
    ...

Client-Side Storage Components

Reactive storage classes for integrating browser storage with Reflex state management for persistent application data.

class Cookie:
    """
    Browser cookie state storage integration.
    
    Provides reactive interface to browser cookies with automatic
    state synchronization and expiration management.
    """
    
    name: str
    """Cookie name identifier."""
    
    value: Any
    """Current cookie value (automatically serialized)."""
    
    max_age: int | None = None
    """Cookie expiration in seconds (None for session cookie)."""
    
    path: str = "/"
    """Cookie path scope."""
    
    domain: str | None = None
    """Cookie domain scope."""
    
    secure: bool = False
    """Whether cookie requires HTTPS."""
    
    same_site: str = "lax"
    """SameSite cookie policy ('strict', 'lax', 'none')."""
    
    def __init__(self, name: str, **kwargs) -> None:
        """
        Initialize cookie storage with configuration.
        
        Args:
            name: Cookie name
            **kwargs: Cookie configuration options
        """
        ...

class LocalStorage:
    """
    Browser localStorage integration for persistent state.
    
    Provides reactive interface to browser localStorage with
    automatic JSON serialization and state synchronization.
    """
    
    key: str
    """localStorage key identifier."""
    
    value: Any
    """Current stored value (automatically serialized to JSON)."""
    
    def __init__(self, key: str, default: Any = None) -> None:
        """
        Initialize localStorage integration.
        
        Args:
            key: localStorage key name
            default: Default value if key doesn't exist
        """
        ...

class SessionStorage:
    """
    Browser sessionStorage integration for temporary state.
    
    Similar to LocalStorage but data expires when browser tab closes.
    Useful for temporary application state and user sessions.
    """
    
    key: str
    """sessionStorage key identifier."""
    
    value: Any
    """Current stored value (automatically serialized to JSON)."""
    
    def __init__(self, key: str, default: Any = None) -> None:
        """
        Initialize sessionStorage integration.
        
        Args:
            key: sessionStorage key name  
            default: Default value if key doesn't exist
        """
        ...

State Retrieval Utilities

Utility functions for accessing and manipulating state from within event handlers and computed variables.

def get_state(state_class: type[State]) -> State:
    """
    Retrieve current state instance within event handlers.
    
    Provides access to state instance for reading values or calling
    methods from within event handlers or computed variables.
    
    Args:
        state_class: State class to retrieve instance for
    
    Returns:
        Current state instance of the specified class
    """
    ...

Usage Examples

Basic Event Handling

import reflex as rx

class CounterState(rx.State):
    count: int = 0
    
    def increment(self):
        self.count += 1
    
    def decrement(self):
        self.count -= 1
    
    def reset(self):
        self.count = 0

def counter():
    return rx.vstack(
        rx.heading(f"Count: {CounterState.count}"),
        rx.hstack(
            rx.button("Decrement", on_click=CounterState.decrement),
            rx.button("Reset", on_click=CounterState.reset), 
            rx.button("Increment", on_click=CounterState.increment),
        ),
    )

Event Chaining

class FormState(rx.State):
    submitted: bool = False
    
    def submit_form(self):
        self.submitted = True
        # Process form data
    
    def show_success(self):
        return rx.toast.success("Form submitted successfully!")

def form():
    return rx.form(
        # ... form fields ...
        rx.button(
            "Submit",
            on_click=[
                FormState.submit_form,
                FormState.show_success,
                rx.redirect("/success")
            ]
        )
    )

Storage Integration

class UserState(rx.State):
    # Persistent user preferences in localStorage
    theme: str = rx.LocalStorage("user_theme", "light")
    
    # Session data that expires with tab
    session_data: dict = rx.SessionStorage("session", {})
    
    # Authentication cookie
    auth_token: str = rx.Cookie("auth", max_age=86400)  # 24 hours

Types

from typing import Any, Callable, Dict, List, Optional, Union
from reflex.vars.base import Var

# Event Types
EventType = Callable | EventHandler | list[EventHandler]
EventFunc = Callable[..., Any]  # Function that can become event handler

# Event Handler Types
class Event:
    """DOM event data from frontend."""
    token: str
    name: str
    router_data: Dict[str, Any]
    payload: Dict[str, Any]

# Storage Types
CookieOptions = Dict[str, Union[str, int, bool]]
StorageValue = Union[str, int, float, bool, Dict, List]

# JavaScript Integration Types
JavaScriptCode = str  # JavaScript code string
FunctionName = str  # JavaScript function name
FunctionArgs = List[Any]  # Arguments for JavaScript functions

# Browser Action Types
URLPath = str  # URL or route path
ElementID = str  # DOM element ID
LogLevel = Literal["info", "warn", "error", "debug"]
ScrollBehavior = Literal["smooth", "instant", "auto"]

Install with Tessl CLI

npx tessl i tessl/pypi-reflex

docs

advanced-features.md

core-framework.md

database-models.md

event-system.md

index.md

styling-theming.md

ui-components.md

tile.json