Skip to content
GitHub

API Reference

Any object that can render to an HTML string.

Implemented by Component, Element, and any custom renderable in lexigram-ui. Export this protocol from the UIModule so that other packages can accept UI objects without importing from lexigram-ui implementation modules.


Abstract base for all input components.

Provides:

  • Common props handling (name, value, label, error, disabled, required)
  • Shared CSS class generation
  • Common wrapper rendering (label + error display)

Subclasses must implement:

  • _render_input(): Returns the actual input element
__init__
def __init__(
    name: str,
    value: Any = None,
    label: str | None = None,
    error: str | None = None,
    disabled: bool = False,
    required: bool = False,
    readonly: bool = False,
    **props
)
input_id
property input_id() -> str

Get the input ID (from props or fallback to name).

render
def render() -> Any

Render complete input component.

Calls _render_input() and wraps with label/error if needed.


Standardized action button with icon support and consistent styling.
__init__
def __init__(
    label: str,
    variant: Literal['primary', 'secondary', 'danger', 'ghost', 'link'] = 'primary',
    icon: str | None = None,
    icon_position: Literal['left', 'right'] = 'left',
    size: Literal['sm', 'md', 'lg'] = 'md',
    **props
) -> None

Initialize action button.

Parameters
ParameterTypeDescription
`label`strButton text
`variant`Literal['primary', 'secondary', 'danger', 'ghost', 'link']Button style variant
`icon`str | NoneIcon name (from icons.py)
`icon_position`Literal['left', 'right']Position of icon relative to label
`size`Literal['sm', 'md', 'lg']Button size **props: Additional props (HTMX attributes, type, disabled, etc.)
render
def render() -> Any

Render action button.


Activity feed component showing recent events/actions.
__init__
def __init__(
    title: str = 'Recent Activity',
    items: list[dict[str, Any]] | None = None,
    max_items: int = 5,
    **props
) -> None
Parameters
ParameterTypeDescription
`title`strFeed title
`items`list[dict[str, Any]] | NoneList of dicts with 'user', 'action', 'resource', 'timestamp' keys
`max_items`intMaximum number of items to display
render
def render() -> Any

Alert component for notifications and messages.
__init__
def __init__(
    message: str,
    variant: AlertVariant = 'info',
    dismissible: bool = False,
    **props
) -> None
render
def render() -> Any

Builder for ARIA attributes.
to_dict
def to_dict() -> dict[str, str]

Convert to HTML attribute dictionary.


ARIA live region politeness settings.

Common ARIA roles for components.

A layout component for asides/sidebars within a page.
__init__
def __init__(
    *children,
    position: str = 'left',
    width: str = 'w-64',
    **props
) -> None
render
def render() -> Any

Specialized file upload for user avatars.
render
def render() -> Any

Badge component for status indicators.
__init__
def __init__(
    text: str,
    variant: BadgeVariant = 'default',
    **props
) -> None
render
def render() -> Any

Base configuration for all layouts.

Extends HTMLDocumentConfig with common layout settings.


Base context for all layouts.

Common context data used across layouts.


Select field for BelongsTo relationships.

Links to another resource and can be searchable.

__init__
def __init__(
    name: str,
    resource: str,
    searchable: bool = False,
    **kwargs
) -> None

Breadcrumb navigation component with home icon.
Parameters
ParameterTypeDescription
`items`List of dicts with 'label' and 'url'
__init__
def __init__(
    items: list[dict[str, str]],
    **props
) -> None
render
def render() -> Any

A block-based content editor. Allows adding, removing, and reordering structured content blocks.

Data is stored as a JSON array of objects: [ {“type”: “heading”, “data”: {“text”: “Hello”}}, {“type”: “text”, “data”: {“body”: “World”}} ]

__init__
def __init__(
    blocks: list[Any],
    name: str,
    value: list[dict] | str | None = None,
    label: str | None = None,
    **props
) -> None
render
def render() -> Any

Button with ShadCN-compatible variants and sizes.
Parameters
ParameterTypeDescription
`label`Button text.
`variant`Visual style variant.
`size`Size variant.
`as_child`If True, renders as first child element. **props: Additional HTML attributes.
__init__
def __init__(
    label: str = '',
    *,
    variant: ButtonVariant = 'default',
    size: ButtonSize = 'default',
    as_child: bool = False,
    **props: Any
) -> None
render
def render() -> Any

Manages CSS asset injection for layout rendering.
__init__
def __init__() -> None

Initialize CSS collections.

add_css
def add_css(
    href: str,
    **attrs: str
) -> None

Add a CSS file link.

Parameters
ParameterTypeDescription
`href`strURL to CSS file **attrs: Additional attributes (media, crossorigin, etc.)
add_inline_style
def add_inline_style(css: str) -> None

Add inline CSS.

Parameters
ParameterTypeDescription
`css`strCSS rules
render_css
def render_css() -> str

Render all CSS as HTML.

Returns
TypeDescription
strHTML string with link and style tags

Refined Card component for better aesthetics.
__init__
def __init__(
    title: str | Any | None = None,
    content: str | Any | None = None,
    footer: Any = None,
    *,
    as_child: bool = False,
    **props
) -> None
render
def render() -> Any

Simple CSS-based chart component for dashboard metrics. Supports bar, line, area, and pie charts with configurable colors.
__init__
def __init__(
    title: str,
    data: list[dict[str, Any]],
    chart_type: str = 'bar',
    color: str = 'indigo',
    **props
) -> None
Parameters
ParameterTypeDescription
`title`strChart title
`data`list[dict[str, Any]]List of dicts with 'label' and 'value' keys
`chart_type`strChart type - 'bar', 'line', 'area', or 'pie'
`color`strTailwind color name (indigo, blue, green, etc.)
render
def render() -> Any

Alias for Toggle for semantic clarity.

Multiple checkboxes for list selection.
__init__
def __init__(
    name: str,
    choices: list[tuple[str, str]],
    inline: bool = False,
    **kwargs
) -> None
render
def render() -> Any

Grid column component (vertical flow).
__init__
def __init__(
    *children,
    gap: int = 4,
    span: int | None = None,
    **props
) -> None
render
def render() -> Any

Color selection input.

Base UI Component for lexigram-admin (HTPy-backed).

Subclasses implement render() which returns either a string or an htpy element. render_to_string converts to HTML.

Components support Streamlit-style with usage via context manager methods: entering the context makes the component the current parent for subsequent calls to add_child_to_current or manual appends.

__init__
def __init__(
    *children: Any,
    as_child: bool = False,
    **props: Any
) -> None
on_mount
def on_mount() -> None

Lifecycle hook called when component is instantiated.

add
def add(*children: Any) -> Component

Fluent API to add children to this component.

render
def render() -> str | Any

__init__
def __init__(
    *children,
    **props
) -> None
render
def render() -> Any

Date input with label and error support.
__init__
def __init__(
    name: str,
    min_value: str | None = None,
    max_value: str | None = None,
    input_type: str = 'date',
    **kwargs
) -> None

Configuration for debounced HTMX triggers.
to_trigger
def to_trigger(base_trigger: str = 'input') -> str

Generate HTMX trigger string with debounce.


Render a divider line.
Parameters
ParameterTypeDescription
`orientation`'horizontal' or 'vertical'
`class_name`Additional CSS classes
__init__
def __init__(
    orientation: str = 'horizontal',
    class_name: str = '',
    **props
) -> None
render
def render() -> Any

A refined dropdown menu component with positioning control.
__init__
def __init__(
    trigger: str | Any,
    items: list[Any],
    position: str = 'right',
    direction: str = 'down',
    **props
) -> None
render
def render() -> Any

A lightweight, structured HTML element compatible with htpy.

This provides a small subset of behaviour we need: HTML attribute escaping, boolean attributes, self-closing tag handling and a stable __html__/__str__ API so our render_to_string function can consistently produce HTML regardless of whether htpy is present.

__init__
def __init__(
    tag: str,
    *children: Any,
    **attrs: Any
) -> None

Email input - TextInput with type='email'.
__init__
def __init__(
    name: str,
    **kwargs
) -> None

Empty state component for when no data is available.
Parameters
ParameterTypeDescription
`title`Main heading
`message`Descriptive message
`icon`Optional emoji or icon
`action`Optional action button/link
__init__
def __init__(
    title: str = 'No data available',
    message: str = "There's nothing to display yet.",
    icon: str = '📭',
    action: Any = None,
    **props
) -> None
render
def render() -> Any

Categories of errors with different handling strategies.

Standardized error response for HTMX.
to_toast_html
def to_toast_html() -> str

Render as a toast notification.

to_flash_html
def to_flash_html() -> str

Render as an OOB flash message targeting the flash container.

to_inline_errors_html
def to_inline_errors_html() -> str

Render field errors for form validation.

to_error_state_html
def to_error_state_html() -> str

Render as a full error state component.


Error state component for when something goes wrong.
Parameters
ParameterTypeDescription
`title`Error heading
`message`Error description
`action`Optional retry button/link
__init__
def __init__(
    title: str = 'Something went wrong',
    message: str = 'We encountered an error loading this data.',
    action: Any = None,
    **props
) -> None
render
def render() -> Any

Error for a specific form field.

Form field wrapper with label, input, error message, and help text.
__init__
def __init__(
    input_component: Component,
    label: str | None = None,
    error: str | None = None,
    help_text: str | None = None,
    hint: str | None = None,
    required: bool = False,
    hidden: bool = False,
    visible_condition: str | None = None,
    **props
) -> None
render
def render() -> Any

Native fieldset component for grouping form fields with a legend.
Parameters
ParameterTypeDescription
`legend`The title of the fieldset
`description`Optional description text
__init__
def __init__(
    *children,
    legend: str,
    description: str | None = None,
    **props
) -> None
render
def render() -> Any

File upload component with validation and preview.

Example

FileUpload( name=“avatar”, label=“Profile Picture”, accept=“image/*”, max_size=5 * 1024 * 1024, # 5MB preview=True )

__init__
def __init__(
    name: str,
    label: str | None = None,
    accept: str | None = None,
    max_size: int | None = None,
    preview: bool = False,
    required: bool = False,
    disabled: bool = False,
    error: str | None = None,
    help_text: str | None = None,
    **props
)

Initialize file upload component.

Parameters
ParameterTypeDescription
`name`strInput name attribute
`label`str | NoneLabel text
`accept`str | NoneAccepted file types
`max_size`int | NoneMaximum file size in bytes
`preview`boolShow image preview
`required`boolWhether field is required
`disabled`boolWhether field is disabled
`error`str | NoneError message
`help_text`str | NoneHelp text **props: Additional properties
render
def render() -> Any

Render the file upload component.


Configuration for footer.

A footer link.

Renders the admin footer.
__init__
def __init__(config: FooterConfig | None = None)

Initialize the renderer.

Parameters
ParameterTypeDescription
`config`FooterConfig | NoneFooter configuration
render
def render() -> str

Render the footer.

Returns
TypeDescription
strHTML string for footer

A container for form fields with HTMX submission support.
__init__
def __init__(
    action_url: str | None = None,
    method: str = 'post',
    submit_label: str = 'Save',
    hx_target: str = '#main-content',
    hx_swap: str = 'innerHTML',
    autosave: bool = False,
    form_id: str | None = None,
    suppress_submit: bool = False,
    **props
) -> None
render
def render() -> Any

Form actions component for submit/cancel buttons.

Example

FormActions( primary_text=“Save Changes”, secondary_text=“Cancel”, primary_loading=False, cancel_url=“/admin/users” )

__init__
def __init__(
    primary_text: str = 'Save',
    secondary_text: str | None = 'Cancel',
    primary_loading: bool = False,
    primary_disabled: bool = False,
    cancel_url: str | None = None,
    align: str = 'right',
    **props
)

Initialize form actions.

Parameters
ParameterTypeDescription
`primary_text`strPrimary button text
`secondary_text`str | NoneSecondary button text (None to hide)
`primary_loading`boolShow loading state on primary button
`primary_disabled`boolDisable primary button
`cancel_url`str | NoneURL for cancel button (if not provided, uses history.back())
`align`strButton alignment (left, center, right) **props: Additional properties
render
def render() -> Any

Render the form actions.


Form field wrapper with label, input, error message, and help text.
__init__
def __init__(
    input_component: Component,
    label: str | None = None,
    error: str | None = None,
    help_text: str | None = None,
    hint: str | None = None,
    required: bool = False,
    hidden: bool = False,
    visible_condition: str | None = None,
    **props
) -> None
render
def render() -> Any

Generic CSS Grid component.
__init__
def __init__(
    *children,
    cols: int | dict[str, int] = 1,
    gap: int = 4,
    **props
) -> None
render
def render() -> Any

Abstract base class for HTML document generation.

Provides the basic HTML5 document structure that all layouts build upon. Subclasses implement render_head_content(), render_body_content(), and render_body_end() to customize the document.

Features:

  • DOCTYPE html5
  • Configurable lang, charset, meta tags
  • Extensible head and body sections
  • Escape-safe by default
__init__
def __init__(config: HTMLDocumentConfig | None = None)

Initialize the document.

Parameters
ParameterTypeDescription
`config`HTMLDocumentConfig | NoneDocument configuration
render
def render(
    title: str = '',
    **context: Any
) -> Markup

Render the complete HTML document.

Parameters
ParameterTypeDescription
`title`strDocument title **context: Additional context for subclass rendering
Returns
TypeDescription
MarkupComplete HTML document as Markup
get_body_attributes
def get_body_attributes(**context: Any) -> str

Get body element attributes.

Override in subclasses to add classes, data attributes, etc.

Returns
TypeDescription
strString of HTML attributes
render_head_content
def render_head_content(**context: Any) -> str

Render content for the head section.

Subclasses should implement this to add CSS links, inline styles, etc.

Returns
TypeDescription
strHTML string for head section
render_body_content
def render_body_content(**context: Any) -> str | Markup

Render the main body content.

Subclasses should implement this to render the page content.

Returns
TypeDescription
str | MarkupHTML string or Markup for body content
render_body_end
def render_body_end(**context: Any) -> str

Render content at the end of body (before ).

Subclasses can override to add scripts, etc.

Returns
TypeDescription
strHTML string for body end

Configuration for HTML document generation.

Configuration for head section.

Renders the head section content.
__init__
def __init__(config: HeadConfig | None = None)

Initialize the renderer.

Parameters
ParameterTypeDescription
`config`HeadConfig | NoneHead configuration
render
def render(extra_css: str = '') -> str

Render the head content.

Parameters
ParameterTypeDescription
`extra_css`strAdditional inline CSS to include
Returns
TypeDescription
strHTML string for head section

Hidden input field.
render
def render() -> Any

Icon atom that wraps `get_icon` for consistent usage in templates.
Parameters
ParameterTypeDescription
`name`icon name (string or raw node)
`size`Tailwind size classes for icon (default: 'w-5 h-5')
`class_name`extra classes to apply to the icon
`aria_hidden`When True (default), marks icon as decorative with aria-hidden="true". Set to False for meaningful icons and supply an aria_label.
`aria_label`Accessible label for meaningful icons (used when aria_hidden=False).
__init__
def __init__(
    name: str | Any,
    size: str = 'w-5 h-5',
    class_name: str = '',
    aria_hidden: bool = True,
    aria_label: str | None = None,
    **props
) -> None
render
def render() -> Any

A component that triggers an HTMX request when scrolled into view.
__init__
def __init__(
    url: str,
    trigger: str = 'revealed',
    target: str | None = None,
    swap: str = 'afterend',
    select: str | None = None,
    **props
)
render
def render() -> Any

Toast notification component with Alpine.js auto-dismiss and optional action.

For server-driven toasts (HTMX X-Toast headers, configurable position, stacking), use ServerToastChannel with ToastData instead.

Parameters
ParameterTypeDescription
`message`Notification message.
`toast_type`Severity — ``"info"``, ``"success"``, ``"warning"``, ``"error"``.
`duration`Auto-dismiss delay in milliseconds (default 3000).
`action_label`Optional label for an inline action button.
`action_url`URL the action button links to (``href`` when set).
__init__
def __init__(
    message: str,
    toast_type: str = 'info',
    duration: int = 3000,
    action_label: str = '',
    action_url: str = '',
    **props: Any
) -> None
render
def render() -> Any

Text input with label and error support.
Parameters
ParameterTypeDescription
`name`Input name attribute
`value`Input value
`type`Input type (text, password, email, etc.)
`placeholder`Placeholder text
`label`Optional label text
`error`Error message to display
`disabled`Whether input is disabled
`required`Whether input is required
`readonly`Whether input is readonly **props: Additional HTML attributes (hx_*, data-*, etc.)

Example

TextInput( name=“username”, label=“Username”, placeholder=“Enter username”, required=True )

__init__
def __init__(
    name: str,
    value: str | None = None,
    input_type: str = 'text',
    placeholder: str | None = None,
    **kwargs
)

Input with prefix or suffix add-ons.
__init__
def __init__(
    label: str,
    name: str,
    input_type: str = 'text',
    prefix: str | None = None,
    suffix: str | None = None,
    placeholder: str | None = None,
    value: str = '',
    error: str | None = None,
    **props
) -> None
render
def render() -> Any

Manages JavaScript asset injection for layout rendering.
__init__
def __init__() -> None

Initialize JS collections.

add_js
def add_js(
    src: str,
    defer: bool = False,
    async_: bool = False,
    **attrs: str
) -> None

Add a JavaScript file.

Parameters
ParameterTypeDescription
`src`strURL to JS file
`defer`boolAdd defer attribute
`async_`boolAdd async attribute **attrs: Additional attributes
add_inline_script
def add_inline_script(
    script: str,
    defer: bool = False
) -> None

Add inline JavaScript.

Parameters
ParameterTypeDescription
`script`strJavaScript code
`defer`boolIf True, render at end of body
render_js_head
def render_js_head() -> str

Render JS for head section.

Returns
TypeDescription
strHTML string with script tags
render_js_body_end
def render_js_body_end() -> str

Render deferred JS for end of body.

Returns
TypeDescription
strHTML string with script tags

Component for editing key-value pairs (JSON dictionary).
__init__
def __init__(
    name: str,
    key_label: str = 'Key',
    value_label: str = 'Value',
    **kwargs
) -> None
render
def render() -> Any

Accessible label component for form fields and descriptive text.

Can be used as a standalone text label or associated with a form control via the for_ attribute (renders as HTML for).

Example

Label("Email address", for_="email-input", required=True)
Label("Optional note", size="sm", weight="normal")
Label("Email address", for_="email-input", required=True)
Label("Optional note", size="sm", weight="normal")
__init__
def __init__(
    text: str,
    for_: str | None = None,
    required: bool = False,
    size: LabelSize = 'sm',
    weight: LabelWeight = 'medium',
    muted: bool = False,
    **props: Any
) -> None

Initialise a Label atom.

Parameters
ParameterTypeDescription
`text`strThe visible label text.
`for_`str | NoneThe ``id`` of the associated form control (renders as ``for``).
`required`boolWhen ``True`` appends a required indicator asterisk.
`size`LabelSizeText size variant — ``"xs"``, ``"sm"`` (default), ``"md"``, ``"lg"``.
`weight`LabelWeightFont-weight variant.
`muted`boolWhen ``True`` applies a muted/secondary text colour. **props: Additional HTML attributes forwarded to the element.
render
def render() -> Any

Render the label element.


Base layout class for all admin layouts.

Combines HTMLDocument with CSS, JS, HTMX, and theming via composition. Subclasses should implement render_body_content() and optionally override other methods for customization.

Example

class MyLayout(LayoutBase): def render_body_content(self, content: str = "", **context) -> str: return f’

{content}

__init__
def __init__(
    config: BaseLayoutConfig | None = None,
    context: BaseLayoutContext | None = None
)

Initialize the layout.

Parameters
ParameterTypeDescription
`config`BaseLayoutConfig | NoneLayout configuration
`context`BaseLayoutContext | NoneLayout context
add_css
def add_css(
    href: str,
    **attrs: str
) -> None

Add a CSS file link.

Parameters
ParameterTypeDescription
`href`strURL to CSS file **attrs: Additional attributes (media, crossorigin, etc.)
add_inline_style
def add_inline_style(css: str) -> None

Add inline CSS.

Parameters
ParameterTypeDescription
`css`strCSS rules
render_css
def render_css() -> str

Render all CSS as HTML.

Returns
TypeDescription
strHTML string with link and style tags
add_js
def add_js(
    src: str,
    defer: bool = False,
    async_: bool = False,
    **attrs: str
) -> None

Add a JavaScript file.

Parameters
ParameterTypeDescription
`src`strURL to JS file
`defer`boolAdd defer attribute
`async_`boolAdd async attribute **attrs: Additional attributes
add_inline_script
def add_inline_script(
    script: str,
    defer: bool = False
) -> None

Add inline JavaScript.

Parameters
ParameterTypeDescription
`script`strJavaScript code
`defer`boolIf True, render at end of body
render_js_head
def render_js_head() -> str

Render JS for head section.

Returns
TypeDescription
strHTML string with script tags
render_js_body_end
def render_js_body_end() -> str

Render deferred JS for end of body.

Returns
TypeDescription
strHTML string with script tags
get_htmx_config
def get_htmx_config() -> dict[str, Any]

Get HTMX configuration.

Returns
TypeDescription
dict[str, Any]Configuration dict for htmx.config
render_htmx_head
def render_htmx_head() -> str

Render HTMX script tag for head.

Returns
TypeDescription
strHTML string with HTMX script
get_htmx_body_attrs
def get_htmx_body_attrs() -> str

Get HTMX-related body attributes.

Returns
TypeDescription
strString of HTML attributes
get_theme_css_variables
def get_theme_css_variables() -> str

Generate ShadCN-compatible CSS variable declarations.

get_theme_html_attrs
def get_theme_html_attrs() -> str

Get theme-related HTML element attributes.

Returns
TypeDescription
strString of HTML attributes
get_dark_mode_script
def get_dark_mode_script() -> str

Inline script that applies dark class before paint (prevents FOUC).

Must run synchronously in <head> before any CSS paints.

get_alpine_theme_data
def get_alpine_theme_data() -> str

Register Alpine.js theme toggle component data.

render
def render(
    content: str | Markup = '',
    title: str | None = None,
    **extra_context: Any
) -> Markup

Render the complete layout.

Parameters
ParameterTypeDescription
`content`str | MarkupMain page content
`title`str | NonePage title (overrides context title) **extra_context: Additional context
Returns
TypeDescription
MarkupComplete HTML document as Markup
get_body_attributes
def get_body_attributes(**context: Any) -> str

Get body element attributes including theme and HTMX.

render_head_content
def render_head_content(**context: Any) -> str

Render head content (CSS, theme, HTMX).

render_body_content
def render_body_content(
    content: str = '',
    **context: Any
) -> str | Markup

Render body content.

Default implementation just returns content. Subclasses should override to add layout structure.

Parameters
ParameterTypeDescription
`content`strMain content **context: Additional context
Returns
TypeDescription
str | MarkupHTML string or Markup
render_body_end
def render_body_end(**context: Any) -> str

Render content at end of body (deferred scripts).


Select dropdown that support infinite scroll / lazy loading of options.
__init__
def __init__(
    name: str,
    lazy_url: str,
    choices: list[tuple[str, str]] | None = None,
    page: int = 1,
    **kwargs
) -> None
render_options
def render_options() -> list[Any]

Create a consistent styled link element.
Parameters
ParameterTypeDescription
`label`Link text
`href`URL
`variant`Visual style variant
`size`Optional size (sm, md, lg)
__init__
def __init__(
    label: str,
    href: str,
    *,
    as_child: bool = False,
    variant: LinkVariant = 'default',
    size: LinkSize | None = None,
    **props
) -> None
render
def render() -> Any

A simple counter that updates in real-time.
__init__
def __init__(
    label: str,
    url: str,
    interval: str = '5s',
    **props: Any
)
render
def render() -> Any

Full-screen or container loading overlay.
Parameters
ParameterTypeDescription
`message`Optional loading message
`fullscreen`Whether to cover entire screen
__init__
def __init__(
    message: str = 'Loading...',
    fullscreen: bool = True,
    **props
) -> None
render
def render() -> Any

Markdown editor with optional preview toggle. Uses Alpine.js for client-side preview mode switching.
__init__
def __init__(
    name: str,
    value: str | None = None,
    label: str | None = None,
    placeholder: str | None = None,
    error: str | None = None,
    rows: int = 10,
    disabled: bool = False,
    preview: bool = True,
    min_height: int = 300,
    **props
) -> None
render
def render() -> Any

MetricProtocol card for dashboard statistics.

Example

MetricCard( value=“1,234”, label=“Total Users”, trend=“+12%”, trend_direction=“up”, icon=”👥”, color=“success” )

__init__
def __init__(
    value: str | float,
    label: str,
    trend: str | None = None,
    trend_direction: TrendDirection | None = None,
    icon: str | None = None,
    variant: MetricCardVariant = 'default',
    **props
)

Initialize metric card.

Parameters
ParameterTypeDescription
`value`str | floatThe metric value (number or formatted string)
`label`strDescription label
`trend`str | NoneTrend indicator (e.g., "+12%", "-5%")
`trend_direction`TrendDirection | NoneDirection of trend ("up" or "down")
`icon`str | NoneOptional icon (emoji or icon class)
`variant`MetricCardVariantColor variant **props: Additional properties
render
def render() -> Any

Render the metric card.


A single metric data point.

Types of metrics to collect.

Collect and track UI metrics.

This is a simple in-memory collector. For production, integrate with Prometheus, StatsD, or similar.

__init__
def __init__() -> None
inc
def inc(
    name: str,
    value: float = 1.0,
    labels: dict[str, str] | None = None
) -> None

Increment a counter.

observe
def observe(
    name: str,
    value: float,
    labels: dict[str, str] | None = None
) -> None

Record a histogram observation.

set
def set(
    name: str,
    value: float,
    labels: dict[str, str] | None = None
) -> None

Set a gauge value.

get_counter
def get_counter(
    name: str,
    labels: dict[str, str] | None = None
) -> float

Get counter value.

get_histogram_stats
def get_histogram_stats(
    name: str,
    labels: dict[str, str] | None = None
) -> dict[str, float]

Get histogram statistics.

get_gauge
def get_gauge(
    name: str,
    labels: dict[str, str] | None = None
) -> float

Get gauge value.

reset
def reset() -> None

Reset all metrics.

to_dict
def to_dict() -> dict[str, Any]

Export all metrics as dictionary.


A FAANG-level modal dialog powered by Alpine.js.
__init__
def __init__(
    title: str,
    trigger: str | Any = None,
    footer: list[Any] | None = None,
    is_open: bool = False,
    render_trigger: bool = True,
    max_width: str | None = None,
    max_height: str | None = None,
    **props
) -> None
render
def render() -> Any

Polymorphic relationship selector.

Consisted of two dropdowns: one for the type and one for the ID.

__init__
def __init__(
    name: str,
    type_name: str,
    types: list[tuple[str, str]],
    options_url: str,
    type_value: Any = None,
    **kwargs
) -> None
render
def render() -> Any

Premium multi-file upload with drag and drop.
__init__
def __init__(
    name: str,
    accept: str = '*',
    **kwargs
) -> None
render
def render() -> Any

Premium searchable tags-style multi-select.
__init__
def __init__(
    name: str,
    choices: list[tuple[str, str]],
    placeholder: str = 'Select options...',
    **kwargs
) -> None
render
def render() -> Any

Native browser multiple select dropdown.
__init__
def __init__(
    *args,
    **kwargs
) -> None

Number input with min/max/step validation.
Parameters
ParameterTypeDescription
`name`Input name attribute
`value`Input value
`min`Minimum allowed value
`max`Maximum allowed value
`step`Step increment
`label`Optional label text
`error`Error message to display **kwargs: Additional props
__init__
def __init__(
    name: str,
    value: float | None = None,
    min_value: float | None = None,
    max_value: float | None = None,
    step: float | None = None,
    placeholder: str | None = None,
    **kwargs
)

Password input - TextInput with type='password'.
__init__
def __init__(
    name: str,
    **kwargs
) -> None

Popover component for richer content than tooltips.
__init__
def __init__(
    trigger: str | Any,
    position: str = 'bottom',
    width: str = 'md',
    **props
) -> None
render
def render() -> Any

Linear progress bar with percentage display.
Parameters
ParameterTypeDescription
`value`Current progress value
`max`Maximum value (default 100)
`label`Optional label text
`show_percentage`Whether to show percentage text
`color`Tailwind color class
`size`Height variant (sm, md, lg)
__init__
def __init__(
    value: int,
    max_value: int = 100,
    label: str | None = None,
    show_percentage: bool = True,
    color: str = 'indigo',
    size: Literal['sm', 'md', 'lg'] = 'md',
    **props
) -> None
render
def render() -> Any

Radio button group for single selection.
__init__
def __init__(
    name: str,
    choices: list[tuple[str, str]],
    inline: bool = False,
    **kwargs
) -> None
render
def render() -> Any

Star rating component.
__init__
def __init__(
    name: str,
    max_value: int = 5,
    **kwargs
) -> None
render
def render() -> Any

Wrapper for raw HTML strings that should be included verbatim.

Instances implement __html__ so they are detected as htpy-like elements and their contents are not escaped when inserted as children.

__init__
def __init__(value: str) -> None

A component that polls or uses SSE to update its content in real-time.

Example

feed = RealTimeFeed(
url="/admin//updates",
interval="5s",
content=el("p", "Waiting for updates...")
)
__init__
def __init__(
    url: str,
    interval: str | None = '10s',
    use_sse: bool = False,
    content: Any = None,
    **props: Any
) -> None
render
def render() -> Any

LRU cache for rendered component fragments.

Use for expensive-to-render components that don’t change often.

get
def get(
    component_name: str,
    **kwargs: Any
) -> str | None

Get cached render result if valid.

set
def set(
    component_name: str,
    content: str,
    **kwargs: Any
) -> None

Cache a render result.

invalidate
def invalidate(component_name: str | None = None) -> None

Invalidate cache entries.

cached
def cached(component_name: str | None = None) -> Callable[[Callable[Ellipsis, str]], Callable[Ellipsis, str]]

Decorator for caching render methods.


A component that allows users to add/remove sets of fields. Useful for JSON arrays or HasMany relations.
__init__
def __init__(
    name: str,
    schema: list[Component] | Callable[[], list[Component]],
    value: list[dict] | None = None,
    label: str | None = None,
    add_label: str = 'Add Item',
    item_label: str = 'Item',
    **props
) -> None
render
def render() -> Any

Coalesce rapid-fire requests into single requests.

Useful for batch operations or rapid filter changes.

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

Add a value to coalesce.

flush
def flush() -> dict[str, Any]

Get and clear all pending values.


Optimize HTMX responses with caching and conditional rendering.

Features:

  • ETag-based caching for unchanged content
  • Content hashing to detect changes
  • Conditional response headers
compute_etag
def compute_etag(content: str) -> str

Compute ETag hash for content.

should_return_304
def should_return_304(
    content: str,
    request_etag: str | None
) -> bool

Check if we can return 304 Not Modified.

optimize_response
def optimize_response(
    content: str,
    request_etag: str | None = None
) -> tuple[str, int, dict[str, str]]

Optimize response with caching headers.

Parameters
ParameterTypeDescription
`content`strThe HTML content to return
`request_etag`str | NoneThe If-None-Match header value from request
Returns
TypeDescription
tuple[str, int, dict[str, str]]Tuple of (content, status_code, headers)

WYSIWYG editor using Trix. Requires Trix JS/CSS to be loaded in the page.
__init__
def __init__(
    name: str,
    value: str | None = None,
    label: str | None = None,
    placeholder: str | None = None,
    error: str | None = None,
    disabled: bool = False,
    required: bool = False,
    min_height: int = 300,
    toolbar: str | None = None,
    **props
) -> None
render
def render() -> Any

Full-featured accessible select component powered by Alpine.js.

Supports:

  • Single-select (default) — click an option to choose it; dropdown closes.
  • Multi-select (multi=True) — checkbox-style; multiple values selectable.
  • Grouped options (groups) — render labelled option groups.
  • Async search (search_url) — HTMX hx-get fires on the search input; the response should return a <ul id="{name}-options"> fragment.
  • Client-side filter (no search_url) — shown when there are more than SEARCH_THRESHOLD options or groups are present.
Parameters
ParameterTypeDescription
`label`Visible label for the control.
`name`HTML ``name`` attribute used for form submission.
`options`Flat list of ``{"value": ..., "label": ...}`` dicts.
`multi`Enable multi-select behaviour.
`search_url`HTMX URL for server-side search. Receives ``?q=``.
`groups`Grouped options: ``[{"label": "Group", "options": [...]}]``.
`error`Validation error message shown below the control.
`placeholder`Trigger button placeholder text when nothing is selected.
__init__
def __init__(
    label: str,
    name: str,
    options: list[dict[str, Any]] | None = None,
    multi: bool = False,
    search_url: str = '',
    groups: list[dict[str, Any]] | None = None,
    error: str | None = None,
    placeholder: str = 'Select an option',
    **props: Any
) -> None
render
def render() -> Any

Grid row component (flexible layout).
__init__
def __init__(
    *children,
    cols: int = 1,
    gap: int = 4,
    **props
) -> None
render
def render() -> Any

Form section component for grouping related fields.

Example

Section( title=“Personal Information”, description=“Basic details about the user”, Grid( TextInput(“first_name”, label=“First Name”), TextInput(“last_name”, label=“Last Name”), cols=2 ) )

__init__
def __init__(
    *children,
    title: str,
    description: str | None = None,
    icon: str | None = None,
    collapsible: bool = False,
    collapsed: bool = False,
    **props
)

Initialize section component.

Parameters
ParameterTypeDescription
`title`strSection title
`description`str | NoneOptional description
`icon`str | NoneOptional icon (emoji or icon class)
`collapsible`boolWhether section can be collapsed
`collapsed`boolInitial collapsed state **props: Additional properties
render
def render() -> Any

Render the section.


Select dropdown with label and error support.
Parameters
ParameterTypeDescription
`name`Input name attribute
`choices`List of (value, label) tuples
`value`Currently selected value
`label`Optional label text
`error`Error message to display
`multiple`Whether multiple selection is allowed
`disabled`Whether input is disabled
`required`Whether input is required
__init__
def __init__(
    name: str,
    choices: list[tuple[str, str]] | None = None,
    multiple: bool = False,
    **kwargs
) -> None

Renders toast notification container and messages (server-driven via HTMX).
__init__
def __init__(config: ToastConfig | None = None)

Initialize the renderer.

Parameters
ParameterTypeDescription
`config`ToastConfig | NoneToast configuration
render
def render(toasts: list[ToastData]) -> str

Render toast payloads as HTML.

Parameters
ParameterTypeDescription
`toasts`list[ToastData]List of toast data objects
Returns
TypeDescription
strHTML string for the toast container with toasts
render_container
def render_container(toasts: list[ToastData] | None = None) -> str

Render the toast container with optional initial toasts.

Parameters
ParameterTypeDescription
`toasts`list[ToastData] | NoneList of toast messages to show initially
Returns
TypeDescription
strHTML string for toast container
render_toast
def render_toast(toast: ToastData) -> str

Render a single toast notification.

Parameters
ParameterTypeDescription
`toast`ToastDataToast to render
Returns
TypeDescription
strHTML string for toast

Inline alert component for contextual feedback.
Parameters
ParameterTypeDescription
`message`Alert message
`type`Alert type (info, success, warning, error)
`title`Optional alert title
__init__
def __init__(
    message: str,
    alert_type: str = 'info',
    title: str | None = None,
    **props
) -> None
render
def render() -> Any

Skeleton loader placeholder for content.
Parameters
ParameterTypeDescription
`variant`Shape variant (text, circular, rectangular)
`width`CSS width value
`height`CSS height value
`count`Number of skeleton lines (for text variant)
__init__
def __init__(
    variant: Literal['text', 'circular', 'rectangular', 'table'] = 'text',
    width: str = '100%',
    height: str | None = None,
    count: int = 1,
    **props
) -> None
render
def render() -> Any

A side-panel drawer component for auxiliary content or editing.
Parameters
ParameterTypeDescription
`size`Panel width — ``sm``, ``md``, ``lg`` (default), ``xl``, ``2xl``, ``full``
`variant```"default"`` (indigo accent) or ``"danger"`` (red accent for delete confirms)
__init__
def __init__(
    title: str,
    trigger: str | Any = None,
    slide_id: str = 'slide-over',
    is_open: bool = False,
    render_trigger: bool = True,
    footer: list[Any] | None = None,
    size: str = 'lg',
    variant: str = 'default',
    subtitle: str | None = None,
    **props
) -> None
render
def render() -> Any

Range slider input.
Parameters
ParameterTypeDescription
`name`Input name attribute
`value`Current value
`min`Minimum value (default: 0)
`max`Maximum value (default: 100)
`step`Step increment (default: 1)
`label`Optional label text **kwargs: Additional props
__init__
def __init__(
    name: str,
    value: float = 0,
    min_value: float = 0,
    max_value: float = 100,
    step: float = 1,
    **kwargs
)
render
def render() -> Any

Custom render with value display.


Circular loading spinner with size variants.
Parameters
ParameterTypeDescription
`size`Size variant (sm=16px, md=24px, lg=32px, xl=48px)
`color`Tailwind color class (e.g., 'primary', 'blue', 'gray')
`aria_label`Accessible label announced to screen readers (default: "Loading...")
__init__
def __init__(
    size: Literal['sm', 'md', 'lg', 'xl'] = 'md',
    color: str = 'primary',
    aria_label: str = 'Loading...',
    **props
) -> None
render
def render() -> Any

A vertical flex-column layout container.

Stacks its children elements vertically with a Tailwind CSS gap.

Parameters
ParameterTypeDescription
`children`Sequence of child elements to render inside the stack.
`gap`Tailwind spacing unit for ``gap-*`` (e.g. ``6`` → ``gap-6``).
`class_`Additional CSS classes appended to the container element.

Example

content = Stack(
gap=4,
children=[
el("h2", "Title"),
el("p", "Body text"),
],
)
content = Stack(
gap=4,
children=[
el("h2", "Title"),
el("p", "Body text"),
],
)
__init__
def __init__(
    children: list[Any] | None = None,
    gap: int = 4,
    class_: str = ''
) -> None

Dashboard metric card.
__init__
def __init__(
    label: str,
    value: Any,
    delta: str | None = None,
    delta_color: str = 'green',
    icon: str | None = None,
    sparkline_data: list[float] | None = None,
    sparkline_color: str = 'indigo',
    **props
) -> None
render
def render() -> Any

Submit button with automatic loading state.
Parameters
ParameterTypeDescription
`label`Button text.
`variant`Same as Button.
`size`Same as Button.
`disabled`Whether button is disabled. **props: Additional attributes.
__init__
def __init__(
    label: str = 'Submit',
    *,
    variant: ButtonVariant = 'default',
    size: ButtonSize = 'default',
    disabled: bool = False,
    **props: Any
) -> None
render
def render() -> Any

Valid HTMX swap modes.

A premium toggle switch component implemented using the shared `Toggle` molecule.
__init__
def __init__(
    label: str,
    name: str,
    value: bool = False,
    description: str | None = None,
    error: str | None = None,
    **props
) -> None
render
def render() -> Any

Wrapper for tab content. Automatically shows/hides based on the parent Tabs' state.
__init__
def __init__(
    tab_id: str,
    *children,
    **props
) -> None
render
def render() -> Any

A responsive tabbed interface component with smooth animations and client-side switching.
Parameters
ParameterTypeDescription
`tabs`List of (label, id) or (label, url) tuples
`active_tab`Initially active tab ID or label
`client_side`If True, uses Alpine.js for content switching without page load
__init__
def __init__(
    tabs: list[tuple[str, str]],
    active_tab: str | None = None,
    client_side: bool = True,
    **props
)
render
def render() -> Any

Premium tags input using Alpine.js. Allows adding strings as tags/chips.
__init__
def __init__(
    name: str,
    placeholder: str = 'Add tag...',
    **kwargs
) -> None
render
def render() -> Any

Multi-line text input.
Parameters
ParameterTypeDescription
`name`Input name attribute
`value`Input value
`rows`Number of visible rows (default: 3)
`label`Optional label text
`error`Error message to display **kwargs: Additional props
__init__
def __init__(
    name: str,
    value: str | None = None,
    rows: int = 3,
    placeholder: str | None = None,
    **kwargs
)

Text input with label and error support.
Parameters
ParameterTypeDescription
`name`Input name attribute
`value`Input value
`type`Input type (text, password, email, etc.)
`placeholder`Placeholder text
`label`Optional label text
`error`Error message to display
`disabled`Whether input is disabled
`required`Whether input is required
`readonly`Whether input is readonly **props: Additional HTML attributes (hx_*, data-*, etc.)

Example

TextInput( name=“username”, label=“Username”, placeholder=“Enter username”, required=True )

__init__
def __init__(
    name: str,
    value: str | None = None,
    input_type: str = 'text',
    placeholder: str | None = None,
    **kwargs
)

Time selection input.

Deprecated alias for InlineToast. Will be removed in a future release.
__init__
def __init__(
    *args: Any,
    **kwargs: Any
) -> None

Configuration for toast container.

A toast notification message.

Deprecated alias for ServerToastChannel. Will be removed in a future release.
__init__
def __init__(
    *args: Any,
    **kwargs: Any
) -> None

Toast notification types.

Simple checkbox toggle (use Switch from forms.py for premium toggle).
__init__
def __init__(
    name: str,
    value: Any = None,
    checked: bool | None = None,
    **kwargs
) -> None
render
def render() -> Any

Icon-based toggle button useful for theme toggles.
Parameters
ParameterTypeDescription
`icon_on`icon name to show when state var is true
`icon_off`icon name to show when state var is false
`state_var`the JS state variable in scope to toggle (e.g., 'darkMode')
`aria_label`accessible label
__init__
def __init__(
    icon_on: str = 'sun',
    icon_off: str = 'moon',
    state_var: str = 'darkMode',
    aria_label: str = 'Toggle',
    size: str = 'sm',
    **props
) -> None
render
def render() -> Any

Tooltip component with auto-positioning and ARIA accessibility support.

The tooltip element receives role="tooltip" and a stable id. If a trigger element is wired via trigger_id, the wrapper element receives aria-describedby pointing to the tooltip’s id.

Parameters
ParameterTypeDescription
`content`The tooltip text shown on hover.
`position`Visual position hint (default: "top").
`tooltip_id`Explicit ``id`` for the tooltip span. Defaults to a generated value so ``aria-describedby`` always resolves.
`trigger_id`Optional ``id`` of the associated trigger element.
__init__
def __init__(
    content: str,
    position: str = 'top',
    tooltip_id: str | None = None,
    trigger_id: str | None = None,
    **props
) -> None
render
def render() -> Any

Payload fired after a UI component completes rendering.

Attributes: component_name: Qualified name of the component class that rendered.


Configuration for the lexigram-ui provider.

These settings control rendering defaults and are read from the [ui] section of application.yaml (or equivalent config source).

validate_for_environment
def validate_for_environment(env: Environment | None = None) -> list[ConfigIssue]

Check config is safe for the target environment.


Immutable per-request UI rendering context.

Attributes: theme: Active theme name (e.g. "default", "dark"). locale: BCP-47 locale string (e.g. "en", "fr-FR"). user: Optional current user object; application-defined type. extra: Arbitrary extra key-value pairs for application-specific state.


HTMX/htpy component library module.

Call configure to configure and register the UI component system for injection.

Usage

from lexigram.ui.config import UIConfig
@module(
imports=[UIModule.configure(UIConfig(default_theme="default"))]
)
class AppModule(Module):
pass
from lexigram.ui.config import UIConfig
@module(
imports=[UIModule.configure(UIConfig(default_theme="default"))]
)
class AppModule(Module):
pass
configure
def configure(
    cls,
    config: Any | None = None,
    **kwargs: Any
) -> DynamicModule

Create a UIModule with explicit configuration.

Parameters
ParameterTypeDescription
`config`Any | NoneUIConfig or ``None`` to use defaults. **kwargs: Additional keyword arguments forwarded to UIProvider.
Returns
TypeDescription
DynamicModuleA DynamicModule descriptor.
stub
def stub(
    cls,
    config: Any = None
) -> DynamicModule

Return a no-op UIModule for testing.

Registers the UI provider with default configuration. No real rendering backends are configured.

Parameters
ParameterTypeDescription
`config`AnyOptional UIConfig override (passed to UIProvider).
Returns
TypeDescription
DynamicModuleA DynamicModule with default UI configuration.

Registers the lexigram-ui component system.

Bind into your application bootstrap

from lexigram.ui.di import UIProvider
app.add_provider(UIProvider())
from lexigram.ui.di import UIProvider
app.add_provider(UIProvider())

Configuration (application.yaml)

ui:
default_theme: my-theme
debug_components: true
ui:
default_theme: my-theme
debug_components: true

Registered services:

  • UIConfig (singleton) — resolved UI configuration.
  • MetricsCollector (singleton) — in-memory UI metrics collection.
  • ResponseOptimizer (singleton) — ETag-based HTMX response optimization.
  • RenderCache (singleton) — LRU cache for rendered component fragments.
__init__
def __init__(
    config: UIConfig | None = None,
    **kwargs: Any
) -> None
register
async def register(container: ContainerRegistrarProtocol) -> None

Register UI services in the DI container.

Parameters
ParameterTypeDescription
`container`ContainerRegistrarProtocolThe DI container registrar.
boot
async def boot(container: ContainerResolverProtocol) -> None

No boot-time initialisation required for the UI module.

shutdown
async def shutdown() -> None

No shutdown work required for the UI module.

health_check
async def health_check(timeout: float = 5.0) -> HealthCheckResult

Check provider health.

Parameters
ParameterTypeDescription
`timeout`floatMaximum seconds to wait for health check response.
Returns
TypeDescription
HealthCheckResultHealthCheckResult with status and component details.

Payload fired after a template is rendered to its final HTML output.

Attributes: template_name: Name or path of the template that was rendered.


Component for handling infinite scroll and virtualization.

This uses HTMX ‘revealed’ trigger to load next chunks of data.

__init__
def __init__(
    url: str,
    total_items: int | None = None,
    chunk_size: int = 50,
    target_id: str | None = None,
    placeholder: Any | None = None,
    **props
)
render
def render() -> Any

Definition of a UI zone.

A zone represents a targetable region of the page with specific semantics for how it can be updated via HTMX.

Attributes: id: The HTML element ID for this zone description: Human-readable description of this zone’s purpose swappable: Whether this zone can be targeted by HTMX swaps swap_mode: The default HTMX swap mode for this zone preserve_alpine: Whether Alpine.js state should be preserved on swap oob_only: If True, this zone should only be updated via OOB swaps

selector
property selector() -> str

Return the CSS selector for this zone.


Central registry of all UI zones.

This class provides a single source of truth for all targetable regions in the admin UI. Components should reference these zones rather than hardcoding IDs.

Zone Hierarchy:

TABLE (root scope)
├── TOOLBAR (switchers, header actions) - OOB only
├── SEARCH (search input) - never swap
├── FILTERS (filter bar) - OOB only
└── DATA (rows + pagination) - most common target
DASHBOARD (dashboard page)
└── WIDGET_CONTAINER (per-widget lazy-load target)
MODAL (global, outside table)
SLIDE_OVER (global, outside table)
FLASH (toast notifications)

Usage

from lexigram.ui.core.zones import Zones

attrs = { “hx-target”: Zones.DATA.selector, “hx-swap”: Zones.DATA.swap_mode.value, }

all_zones
def all_zones(cls) -> list[Zone]

Return all registered zones.

swappable
def swappable(cls) -> list[Zone]

Return all zones that can be targeted by HTMX swaps.

get_by_id
def get_by_id(
    cls,
    zone_id: str
) -> Zone | None

Look up a zone by its ID.

Returns None if no zone with that ID exists.

get_by_selector
def get_by_selector(
    cls,
    selector: str
) -> Zone | None

Look up a zone by its CSS selector.

Handles both “#zone-id” and “zone-id” formats.


SkipLink
def SkipLink(
    target_id: str = 'main-content',
    label: str = 'Skip to main content'
) -> str
Return an HTML skip navigation link for accessibility.
Parameters
ParameterTypeDescription
`target_id`strThe ID of the target element to skip to.
`label`strThe link text for the skip link.
Returns
TypeDescription
strAn HTML anchor tag with sr-only CSS class.

add_htmx_timing_header
def add_htmx_timing_header(
    headers: dict[str, str],
    render_time_ms: float
) -> dict[str, str]
Add Server-Timing header for HTMX requests.

announce
def announce(
    message: str,
    priority: AriaLive = AriaLive.POLITE,
    atomic: bool = True
) -> str
Create an invisible live region announcement.

This element will be announced by screen readers when inserted into the DOM. Use for dynamic content updates.

Parameters
ParameterTypeDescription
`message`strThe text to announce
`priority`AriaLivePOLITE (wait for idle) or ASSERTIVE (immediate)
`atomic`boolWhether to announce the entire region or just changes
Returns
TypeDescription
strHTML string for the announcement element

announce_action_complete
def announce_action_complete(
    action: str,
    success: bool = True
) -> str
Create an assertive screen-reader announcement for an action outcome.

Uses ASSERTIVE politeness so the result is announced immediately, interrupting any in-progress speech. Suitable for confirming or reporting the failure of a user-initiated action.

Parameters
ParameterTypeDescription
`action`strHuman-readable description of the action, e.g. ``"User deleted"`` or ``"Export"``.
`success`boolWhen ``True`` (default), appends ``"completed successfully"``; when ``False``, appends ``"failed"``.
Returns
TypeDescription
strAn HTML string containing the invisible announcement element.

announce_selection_change
def announce_selection_change(
    count: int,
    action: str = 'selected'
) -> str
Create a polite screen-reader announcement for a selection state change.
Parameters
ParameterTypeDescription
`count`intNumber of items currently in the selection.
`action`strPast-tense verb describing the selection action, e.g. ``"selected"`` (default) or ``"deselected"``.
Returns
TypeDescription
strAn HTML string containing the invisible announcement element.

announce_table_update
def announce_table_update(
    total: int,
    page: int | None = None,
    search: str | None = None
) -> str
Create a polite screen-reader announcement for a table data refresh.

Composes a human-readable summary of the current table state and emits it as a POLITE live-region element via announce.

Parameters
ParameterTypeDescription
`total`intTotal number of items currently displayed or matching the current filter.
`page`int | NoneCurrent page number when the table is paginated. Omit (or pass ``None``) for unpaginated tables.
`search`str | NoneActive search / filter text. When provided, the message includes ``"filtered by ''"``.
Returns
TypeDescription
strAn HTML string containing the invisible announcement element.

button_aria
def button_aria(
    label: str,
    pressed: bool | None = None,
    expanded: bool | None = None,
    controls: str | None = None,
    haspopup: str | None = None,
    disabled: bool = False
) -> dict[str, str]
Return ARIA attributes for an interactive button element.

Covers toggle buttons, disclosure buttons, and menu-trigger buttons. Pass only the arguments relevant to the button’s role; unused attributes are omitted from the returned dict.

Parameters
ParameterTypeDescription
`label`strAccessible name for the button, mapped to ``aria-label``.
`pressed`bool | NoneFor toggle buttons, the current pressed state. ``True`` maps to ``aria-pressed="true"``, ``False`` to ``"false"``, ``None`` omits the attribute entirely.
`expanded`bool | NoneFor disclosure/accordion buttons, whether the controlled region is currently visible. Maps to ``aria-expanded``.
`controls`str | NoneID of the element this button controls. Maps to ``aria-controls``.
`haspopup`str | NoneType of popup this button opens, e.g. ``"menu"``, ``"listbox"``, ``"dialog"``. Maps to ``aria-haspopup``.
`disabled`boolWhen ``True``, adds ``aria-disabled="true"``.
Returns
TypeDescription
dict[str, str]A ``dict[str, str]`` of HTML attribute names to their string values.

Example

attrs = button_aria("Toggle sidebar", expanded=False, controls="sidebar")
# {"role": "button", "aria-label": "Toggle sidebar",
# "aria-expanded": "false", "aria-controls": "sidebar"}
attrs = button_aria("Toggle sidebar", expanded=False, controls="sidebar")
# {"role": "button", "aria-label": "Toggle sidebar",
# "aria-expanded": "false", "aria-controls": "sidebar"}

cached_render
def cached_render(
    component_name: str | None = None,
    cache: RenderCache | None = None
) -> Callable[[Callable[Ellipsis, str]], Callable[Ellipsis, str]]
Decorator for caching component renders.
Parameters
ParameterTypeDescription
`component_name`str | NoneName for the cached component fragment.
`cache`RenderCache | NoneRenderCache instance to use. When None, returns an identity decorator.

cell_aria
def cell_aria(
    colindex: int | None = None,
    rowindex: int | None = None
) -> dict[str, str]
Return ARIA attributes for an interactive table data cell.

Uses the gridcell role, which is appropriate for cells inside a grid-role container that supports keyboard interaction.

Parameters
ParameterTypeDescription
`colindex`int | None1-based column position within the full column set. Maps to ``aria-colindex``. Required when columns are hidden.
`rowindex`int | None1-based row position within the full dataset. Maps to ``aria-rowindex``. Usually set on the row element instead; provide here only when the row element cannot be annotated.
Returns
TypeDescription
dict[str, str]A ``dict[str, str]`` of HTML attribute names to their string values.

component
def component(
    name: str | None = None,
    *,
    cacheable: bool = False
) -> Callable[[F], F]
Mark a callable as a named UI component and attach component metadata.

Tags the decorated function with __component_name__ and __component_cacheable__ attributes so that component registries, debug tooling, and render pipelines can discover and identify components by name without relying on __qualname__.

This decorator does not register the component in any global registry by itself — registration is handled by the DI container via the UIProvider. The decorator provides the metadata that the provider reads during component discovery.

Parameters
ParameterTypeDescription
`name`str | NoneLogical component name used for registration and cache keys. Defaults to the decorated function's ``__name__``.
`cacheable`boolWhen ``True``, signals that the component's rendered output may be cached by the render pipeline. Defaults to ``False``.
Returns
TypeDescription
Callable[[F], F]Decorator that attaches component metadata to the target callable.

Example

@component("user_card", cacheable=True)
def user_card(user: User) -> str:
return render_to_string(
el("div", {"class": "card"}, user.display_name)
)
@component()
def avatar(src: str, alt: str = "") -> str:
return render_to_string(el("img", {"src": src, "alt": alt}))
@component("user_card", cacheable=True)
def user_card(user: User) -> str:
return render_to_string(
el("div", {"class": "card"}, user.display_name)
)
@component()
def avatar(src: str, alt: str = "") -> str:
return render_to_string(el("img", {"src": src, "alt": alt}))

debounced_search_attrs
def debounced_search_attrs(
    url: str,
    delay_ms: int = 300,
    target: str | None = None
) -> dict[str, str]
Generate HTMX attributes for a debounced search input.
Parameters
ParameterTypeDescription
`url`strURL to search endpoint
`delay_ms`intDebounce delay in milliseconds
`target`str | NoneHTMX target (defaults to Zones.DATA)
Returns
TypeDescription
dict[str, str]Dictionary of HTMX attributes

dialog_aria
def dialog_aria(
    label: str,
    describedby: str | None = None,
    modal: bool = True
) -> dict[str, str]
Return ARIA attributes for a modal or non-modal dialog overlay.
Parameters
ParameterTypeDescription
`label`strAccessible name for the dialog, mapped to ``aria-label``. Use a concise title that describes the dialog's purpose, e.g. ``"Confirm deletion"``.
`describedby`str | NoneID of an element that provides a longer description of the dialog's purpose. Maps to ``aria-describedby``.
`modal`boolWhen ``True`` (default), adds ``aria-modal="true"`` to signal that background content is inert while the dialog is open.
Returns
TypeDescription
dict[str, str]A ``dict[str, str]`` of HTML attribute names to their string values.

Example

attrs = dialog_aria("Delete user", describedby="delete-desc")
# {"role": "dialog", "aria-label": "Delete user",
# "aria-describedby": "delete-desc", "aria-modal": "true"}
attrs = dialog_aria("Delete user", describedby="delete-desc")
# {"role": "dialog", "aria-label": "Delete user",
# "aria-describedby": "delete-desc", "aria-modal": "true"}

el
def el(
    tag: str,
    *children: Any,
    **attrs: Any
) -> Any
Construct an element using `htpy` when available, otherwise return an `Element` fallback that implements `__html__`.

For self-closing tags we prefer our local Element to ensure consistent output (including trailing slash), even when htpy is installed.


flash_to_toast
def flash_to_toast(flash_messages: list[tuple[str, str]] | None) -> list[ToastData]
Convert Flask/Starlette flash messages to toasts.
Parameters
ParameterTypeDescription
`flash_messages`list[tuple[str, str]] | NoneList of (category, message) tuples
Returns
TypeDescription
list[ToastData]List of ToastData objects

get_icon
def get_icon(
    name: str | Any,
    class_name: str = '',
    size: str = 'w-5 h-5',
    **attrs
) -> Any
Render a Lucide icon by name.

get_ui_context
def get_ui_context() -> UIContext | None
Return the current request-scoped UIContext, or ``None`` outside a request.
Returns
TypeDescription
UIContext | NoneThe active UIContext set by set_ui_context, or ``None`` if called outside of a request (e.g. during startup).

header_aria
def header_aria(
    label: str,
    sortable: bool = False,
    sort_direction: str | None = None
) -> dict[str, str]
Return ARIA attributes for a sortable or static column header cell.
Parameters
ParameterTypeDescription
`label`strAccessible name for the column, mapped to ``aria-label``.
`sortable`boolWhen ``True``, adds an ``aria-sort`` attribute to indicate the column participates in sorting. Defaults to ``False``.
`sort_direction`str | NoneCurrent sort direction. Pass ``"asc"`` for ascending, ``"desc"`` for descending, or ``None`` (default) to output ``aria-sort="none"`` when *sortable* is ``True``.
Returns
TypeDescription
dict[str, str]A ``dict[str, str]`` of HTML attribute names to their string values.

Example

attrs = header_aria("Name", sortable=True, sort_direction="asc")
# {"role": "columnheader", "aria-label": "Name", "aria-sort": "ascending"}
attrs = header_aria("Name", sortable=True, sort_direction="asc")
# {"role": "columnheader", "aria-label": "Name", "aria-sort": "ascending"}

htmx_error_response
def htmx_error_response(
    error: ErrorResponse,
    include_flash: bool = True
) -> tuple[str, int, dict]
Build an HTMX-compatible error response.

infinite_scroll_trigger
def infinite_scroll_trigger(
    url: str,
    target: str | None = None,
    swap: str = 'beforeend',
    threshold: str = '200px'
) -> str
Create an infinite scroll trigger element.
Parameters
ParameterTypeDescription
`url`strURL to fetch next page from
`target`str | NoneHTMX target selector (defaults to Zones.DATA)
`swap`strHTMX swap mode
`threshold`strDistance from bottom to trigger load
Returns
TypeDescription
strHTML string for the trigger element

keyboard_navigation_script
def keyboard_navigation_script() -> str
Return a script tag with keyboard navigation helpers.
Returns
TypeDescription
strAn HTML script tag with keyboard navigation JavaScript.

lazy_load_placeholder
def lazy_load_placeholder(
    url: str,
    target_id: str,
    trigger: str = 'load',
    placeholder: str | None = None
) -> str
Create a lazy-load placeholder that fetches content on trigger.
Parameters
ParameterTypeDescription
`url`strURL to fetch content from
`target_id`strID of the element to replace
`trigger`strHTMX trigger (load, revealed, intersect, etc.)
`placeholder`str | NoneOptional placeholder content (defaults to skeleton)
Returns
TypeDescription
strHTML string for the placeholder

live_region_aria
def live_region_aria(
    politeness: AriaLive = AriaLive.POLITE,
    atomic: bool = True
) -> dict[str, str]
Return ARIA attributes for a live region container.

Live regions allow assistive technologies to announce dynamic content changes without requiring user focus. Use announce for one-shot screen-reader announcements; use this function when you need to annotate a persistent container.

Parameters
ParameterTypeDescription
`politeness`AriaLiveInterrupt behaviour for the announcement. Use AriaLive.POLITE (default) to wait until the user is idle, or AriaLive.ASSERTIVE for time-sensitive alerts.
`atomic`boolWhen ``True`` (default), the entire region is re-read on every change rather than just the changed nodes.
Returns
TypeDescription
dict[str, str]A ``dict[str, str]`` of HTML attribute names to their string values.

measure_render_time
def measure_render_time(func: Callable[Ellipsis, str]) -> Callable[Ellipsis, tuple[str, float]]
Decorator to measure render time.

not_found_error
def not_found_error(message: str = 'The requested resource was not found.') -> ErrorResponse
Create a not found error response (404).

optimize_htmx_response
def optimize_htmx_response(
    content: str,
    request_etag: str | None = None,
    optimizer: ResponseOptimizer | None = None
) -> tuple[str, int, dict[str, str]]
Convenience function for response optimization.
Parameters
ParameterTypeDescription
`content`strHTML content to optimize.
`request_etag`str | NoneETag from the incoming request for cache validation.
`optimizer`ResponseOptimizer | NoneResponseOptimizer instance. When None, returns the content unchanged.

permission_error
def permission_error(message: str = "You don't have permission to perform this action.") -> ErrorResponse
Create a permission error response (403).

raw
def raw(value: str) -> RawHTML

render_to_string
def render_to_string(value: str | Any) -> str
Render a component or htpy element to an HTML string.

This performs a best-effort conversion: strings are returned verbatim, htpy elements are converted if they provide a renderer, iterables are flattened by rendering each child and concatenating the results, and component instances are rendered via their render() method.


render_validation_errors
def render_validation_errors(
    errors: list[FieldError] | dict[str, str | list[str]],
    field_name: str | None = None
) -> str
Render validation errors as an HTML string.

reset_ui_context
def reset_ui_context(token: contextvars.Token[UIContext | None]) -> None
Restore the previous UI context using the token returned by set_ui_context.
Parameters
ParameterTypeDescription
`token`contextvars.Token[UIContext | None]The token returned by set_ui_context.

row_aria
def row_aria(
    index: int,
    selected: bool = False,
    expanded: bool | None = None
) -> dict[str, str]
Return ARIA attributes for a table row element.
Parameters
ParameterTypeDescription
`index`int1-based row position within the full dataset (not the current page). Maps to ``aria-rowindex``.
`selected`boolWhether this row is currently selected. Maps to ``aria-selected``.
`expanded`bool | NoneFor tree-grid rows, whether the row is expanded. Pass ``None`` (default) to omit the attribute entirely.
Returns
TypeDescription
dict[str, str]A ``dict[str, str]`` of HTML attribute names to their string values.

search_aria
def search_aria(
    label: str = 'Search',
    controls: str | None = None
) -> dict[str, str]
Return ARIA attributes for a search input field.
Parameters
ParameterTypeDescription
`label`strAccessible name for the search field. Defaults to ``"Search"``.
`controls`str | NoneID of the live region or results container that this input updates. Maps to ``aria-controls`` and helps screen readers announce that results are available.
Returns
TypeDescription
dict[str, str]A ``dict[str, str]`` of HTML attribute names to their string values.

server_error
def server_error(
    message: str = 'An unexpected error occurred. Please try again.',
    retry_url: str | None = None
) -> ErrorResponse
Create a server error response (500).

set_ui_context
def set_ui_context(ctx: UIContext) -> contextvars.Token[UIContext | None]
Bind *ctx* as the active UI context for the current async task.
Parameters
ParameterTypeDescription
`ctx`UIContextThe UIContext to set as active.
Returns
TypeDescription
contextvars.Token[UIContext | None]A Token that can be passed to reset_ui_context to restore the previous value.

tab_aria
def tab_aria(
    label: str,
    selected: bool = False,
    controls: str | None = None
) -> dict[str, str]
Return ARIA attributes for a tab button within a tab list.

The tab element must be a child of an element with role="tablist" and must reference its associated panel via controls.

Parameters
ParameterTypeDescription
`label`strAccessible name for the tab, mapped to ``aria-label``.
`selected`boolWhether this tab is currently the active tab. Maps to ``aria-selected``.
`controls`str | NoneID of the ``tabpanel`` element this tab reveals. Maps to ``aria-controls``.
Returns
TypeDescription
dict[str, str]A ``dict[str, str]`` of HTML attribute names to their string values.

table_aria
def table_aria(
    label: str,
    rowcount: int | None = None,
    colcount: int | None = None,
    sortable: bool = False
) -> dict[str, str]
Return ARIA attributes for an accessible data table (grid role).

Use on the <table> or wrapper element that contains rows and cells. The grid role is used instead of table to support interactive keyboard navigation patterns expected by Admin UI tables.

Parameters
ParameterTypeDescription
`label`strHuman-readable label describing the table's content, used as ``aria-label``.
`rowcount`int | NoneTotal number of data rows across all pages. Pass the full dataset size when the table is paginated so assistive technologies can announce ``"row N of M"``.
`colcount`int | NoneTotal number of columns. Required when some columns are hidden or the table uses column groups.
`sortable`boolReserved for future use. Pass ``True`` to signal that column headers may carry ``aria-sort`` attributes.
Returns
TypeDescription
dict[str, str]A ``dict[str, str]`` of HTML attribute names to their string values, ready to be spread onto the element.

Example

attrs = table_aria("User list", rowcount=250, colcount=5)
# {"role": "grid", "aria-label": "User list",
# "aria-rowcount": "250", "aria-colcount": "5"}
attrs = table_aria("User list", rowcount=250, colcount=5)
# {"role": "grid", "aria-label": "User list",
# "aria-rowcount": "250", "aria-colcount": "5"}

tabpanel_aria
def tabpanel_aria(
    labelledby: str,
    hidden: bool = False
) -> dict[str, str]
Return ARIA attributes for a tab panel content area.

The panel must be associated with its controlling tab via labelledby.

Parameters
ParameterTypeDescription
`labelledby`strID of the ``tab`` element that controls this panel. Maps to ``aria-labelledby``.
`hidden`boolWhen ``True``, adds ``aria-hidden="true"`` to hide the panel from assistive technologies when its tab is not selected.
Returns
TypeDescription
dict[str, str]A ``dict[str, str]`` of HTML attribute names to their string values.

timeout_error
def timeout_error(
    message: str = 'The request timed out. Please try again.',
    retry_url: str | None = None
) -> ErrorResponse
Create a timeout error response (504).

validation_error
def validation_error(
    message: str = 'Please correct the errors below.',
    field_errors: list[FieldError] | None = None
) -> ErrorResponse
Create a validation error response (422).

Base exception for all UI-domain errors.
__init__
def __init__(
    message: str,
    *,
    code: str | None = None
) -> None