API Reference
Protocols
Section titled “Protocols”RenderableProtocol
Section titled “RenderableProtocol”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.
Classes
Section titled “Classes”AbstractInput
Section titled “AbstractInput”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
Get the input ID (from props or fallback to name).
Render complete input component.
Calls _render_input() and wraps with label/error if needed.
Action
Section titled “Action”Base class for all actions (row, header, etc.).
Implements a fluent API for configuration.
Example
Action("approve").icon("check").color("success").requires_confirmation()Initialize an action.
| Parameter | Type | Description |
|---|---|---|
| `name` | str | Unique identifier for the action |
| `label` | str | None | Display label (defaults to title-cased name) |
Set action icon.
Set button color variant (primary, success, danger, etc.).
Set action color to danger.
Set action color to success.
Set action color to warning.
Set action color to info.
Set action color to gray.
Set URL for navigation actions.
Set backend action handler.
Open a modal when clicked.
Open in a side panel (SlideOver) when clicked.
Require confirmation before execution.
Control visibility.
Control enabled/disabled state.
Configure HTMX attributes manually.
Check if action should be visible.
Check if action should be disabled.
Resolve URL if it’s a callable.
Get the HTMX GET URL.
Get the HTMX POST URL.
Get the HTMX DELETE URL.
Render action as a button using ActionButton.
ActionButton
Section titled “ActionButton”Standardized action button with icon support and consistent styling.
Initialize action button.
| Parameter | Type | Description |
|---|---|---|
| `label` | str | Button text |
| `variant` | Literal['primary', 'secondary', 'danger', 'ghost', 'link'] | Button style variant |
| `icon` | str | None | Icon 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 action button.
ActionTarget
Section titled “ActionTarget”Where the action result should be rendered.
ActivityFeed
Section titled “ActivityFeed”
AdminCard
Section titled “AdminCard”ShadCN-styled card for admin dashboard sections.
| Parameter | Type | Description |
|---|---|---|
| `title` | Optional card header text. | |
| `content` | Card body — a string, htpy element, or Component. **props: Additional HTML attributes applied to the outer div. |
Alert component for notifications and messages.
AreaChart
Section titled “AreaChart”
AriaAttrs
Section titled “AriaAttrs”Builder for ARIA attributes.
Convert to HTML attribute dictionary.
AriaLive
Section titled “AriaLive”ARIA live region politeness settings.
AriaRole
Section titled “AriaRole”Common ARIA roles for components.
A layout component for asides/sidebars within a page.
AutoRefreshWidget
Section titled “AutoRefreshWidget”HTMX polling container that re-fetches *url* every *interval_ms* ms.
The component renders a <div> with hx-get and
hx-trigger="every <N>ms" attributes. The polled response should
return an HTML fragment that replaces innerHTML of the container.
A “Pause / Resume” toggle button (Alpine.js) lets users stop polling without a page reload.
| Parameter | Type | Description |
|---|---|---|
| `url` | Endpoint to poll (HTMX GET). | |
| `interval_ms` | Polling interval in milliseconds (default 5000). | |
| `target_id` | ``id`` given to the wrapper element, used as the HTMX target selector for OOB swaps. | |
| `content` | Optional initial HTML content rendered before first poll. | |
| `label` | Optional label shown next to the pause/resume button. | |
| `show_controls` | Whether to render the pause/resume button. |
AvatarUpload
Section titled “AvatarUpload”Specialized file upload for user avatars.
Badge component for status indicators.
BadgeColumn
Section titled “BadgeColumn”Status badge column with color coding.
Initialize badge column.
| Parameter | Type | Description |
|---|---|---|
| `name` | str | Column field name |
| `label` | str | None | Display label |
| `colors` | dict[str, str] | None | Mapping of values to colors (e.g., {"active": "green", "inactive": "gray"}) |
Set color mapping for values.
Set icon mapping for values (emoji or icon class).
Render as colored badge using atomic Badge component.
BarChart
Section titled “BarChart”
BaseLayoutConfig
Section titled “BaseLayoutConfig”Base configuration for all layouts.
Extends HTMLDocumentConfig with common layout settings.
BaseLayoutContext
Section titled “BaseLayoutContext”Base context for all layouts.
Common context data used across layouts.
BelongsTo
Section titled “BelongsTo”Select field for BelongsTo relationships.
Links to another resource and can be searchable.
BooleanColumn
Section titled “BooleanColumn”Boolean column with icons.
Set icon for true values.
Set icon for false values.
Set color for true values.
Set color for false values.
Render as icon with color.
Breadcrumbs
Section titled “Breadcrumbs”Breadcrumb navigation component with home icon.
| Parameter | Type | Description |
|---|---|---|
| `items` | List of dicts with 'label' and 'url' |
Builder
Section titled “Builder”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”}} ]
BulkAction
Section titled “BulkAction”Action that applies to multiple selected items.
Button
Section titled “Button”Button with ShadCN-compatible variants and sizes.
| Parameter | Type | Description |
|---|---|---|
| `label` | Button text. | |
| `variant` | Visual style variant. | |
| `size` | Size variant. | |
| `as_child` | If True, renders as first child element. **props: Additional HTML attributes. |
CSSManager
Section titled “CSSManager”Manages CSS asset injection for layout rendering.
Initialize CSS collections.
Add a CSS file link.
| Parameter | Type | Description |
|---|---|---|
| `href` | str | URL to CSS file **attrs: Additional attributes (media, crossorigin, etc.) |
Add inline CSS.
| Parameter | Type | Description |
|---|---|---|
| `css` | str | CSS rules |
Render all CSS as HTML.
| Type | Description |
|---|---|
| str | HTML string with link and style tags |
Refined Card component for better aesthetics.
ChartConfig
Section titled “ChartConfig”
ChartDataPoint
Section titled “ChartDataPoint”
ChartType
Section titled “ChartType”
Checkbox
Section titled “Checkbox”Alias for Toggle for semantic clarity.
CheckboxList
Section titled “CheckboxList”Multiple checkboxes for list selection.
Grid column component (vertical flow).
ColorPicker
Section titled “ColorPicker”Color selection input.
Column
Section titled “Column”Complete Column base class with all functionality.
Component
Section titled “Component”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.
Lifecycle hook called when component is instantiated.
Fluent API to add children to this component.
Container
Section titled “Container”
CreateAction
Section titled “CreateAction”Standard Create action implementation (Header Action).
CurrencyColumn
Section titled “CurrencyColumn”Currency column with formatting.
Set currency code (USD, EUR, GBP, etc.).
Set number of decimal places.
Render as formatted currency.
DataTableScriptRenderer
Section titled “DataTableScriptRenderer”Renderer for the client-side Alpine.js logic of the DataTable.
DateColumn
Section titled “DateColumn”Date/datetime column with formatting.
Initialize date column.
| Parameter | Type | Description |
|---|---|---|
| `name` | str | Column field name |
| `label` | str | None | Display label |
| `date_format` | str | strftime format string |
Set date format string.
Format as date only (YYYY-MM-DD).
Format as datetime (YYYY-MM-DD HH:MM:SS).
Format as time only (HH:MM:SS).
Show relative time (e.g., ‘2 hours ago’).
Render formatted date.
DateHierarchyFilter
Section titled “DateHierarchyFilter”Year/month/day drill-down filter navigation.
At each level the component renders quick-link buttons:
- No selection: Shows clickable year links (last 5 years + current).
- Year selected: Shows clickable month buttons (Jan–Dec).
- Year + month selected: Shows clickable day buttons for that month.
- Year + month + day: Shows breadcrumb with ”×” clear button.
HTMX is used to reload the table without a full page refresh.
| Parameter | Type | Description |
|---|---|---|
| `field_name` | Model field being filtered (used in URL params as ``{field_name}__year``, etc.). | |
| `year` | Currently selected year, or ``None``. | |
| `month` | Currently selected month (1–12), or ``None``. | |
| `day` | Currently selected day (1–31), or ``None``. | |
| `base_url` | Base URL for building drill-down links. | |
| `resource_prefix` | HTMX target resource prefix. | |
| `available_years` | Explicit list of years to show. If ``None``, defaults to the 5 years before and including the current year from the *year* argument or ``2026``. |
DateInput
Section titled “DateInput”Date input with label and error support.
DateRangeFilter
Section titled “DateRangeFilter”A simple date range filter with start and end inputs.
DebounceConfig
Section titled “DebounceConfig”Configuration for debounced HTMX triggers.
Generate HTMX trigger string with debounce.
DeleteAction
Section titled “DeleteAction”Standard Delete action implementation.
DeleteBulkAction
Section titled “DeleteBulkAction”Standard Bulk Delete action.
Divider
Section titled “Divider”Render a divider line.
| Parameter | Type | Description |
|---|---|---|
| `orientation` | 'horizontal' or 'vertical' | |
| `class_name` | Additional CSS classes |
Dropdown
Section titled “Dropdown”A refined dropdown menu component with positioning control.
EditAction
Section titled “EditAction”Standard Edit action implementation.
Element
Section titled “Element”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.
EmailInput
Section titled “EmailInput”Email input - TextInput with type='email'.
EmptyState
Section titled “EmptyState”Empty state component for when no data is available.
| Parameter | Type | Description |
|---|---|---|
| `title` | Main heading | |
| `message` | Descriptive message | |
| `icon` | Optional icon name (Lucide, resolved via ``get_icon``) or emoji | |
| `action` | Optional action button/link |
ErrorCategory
Section titled “ErrorCategory”Categories of errors with different handling strategies.
ErrorResponse
Section titled “ErrorResponse”Standardized error response for HTMX.
Render as a toast notification.
Render as an OOB flash message targeting the flash container.
Render field errors for form validation.
Render as a full error state component.
ErrorState
Section titled “ErrorState”Error state component for when something goes wrong.
| Parameter | Type | Description |
|---|---|---|
| `title` | Error heading | |
| `message` | Error description | |
| `action` | Optional retry button/link |
ExportAction
Section titled “ExportAction”Standard Export action implementation.
ExportBulkAction
Section titled “ExportBulkAction”Standard Bulk Export action.
FieldError
Section titled “FieldError”Error for a specific form field.
FieldSchema
Section titled “FieldSchema”Form field wrapper with label, input, error message, and help text.
Fieldset
Section titled “Fieldset”Native fieldset component for grouping form fields with a legend.
| Parameter | Type | Description |
|---|---|---|
| `legend` | The title of the fieldset | |
| `description` | Optional description text |
FileUpload
Section titled “FileUpload”File upload component with validation and preview.
Example
FileUpload( name=“avatar”, label=“Profile Picture”, accept=“image/*”, max_size=5 * 1024 * 1024, # 5MB preview=True )
Initialize file upload component.
| Parameter | Type | Description |
|---|---|---|
| `name` | str | Input name attribute |
| `label` | str | None | Label text |
| `accept` | str | None | Accepted file types |
| `max_size` | int | None | Maximum file size in bytes |
| `preview` | bool | Show image preview |
| `required` | bool | Whether field is required |
| `disabled` | bool | Whether field is disabled |
| `error` | str | None | Error message |
| `help_text` | str | None | Help text **props: Additional properties |
Render the file upload component.
FilterDrawer
Section titled “FilterDrawer”Slide-over filter panel with stacked filter controls.
Renders a “Filters” trigger button whose badge shows the number of active
filters, and a slide-over panel that contains the full filter form. The
panel is driven by Alpine.js (filterDrawerOpen state) so it requires
no page reload to open/close.
| Parameter | Type | Description |
|---|---|---|
| `filters` | Same format as ``FilterBar.filters`` — dict of ``{field_name: {"type": ..., "options": [...], ...}}``. | |
| `current_values` | Current active filter values. | |
| `resource_prefix` | Resource URL prefix for HTMX ``hx-get`` attributes. | |
| `state` | Optional ``TableState`` for building HTMX attrs on apply. |
FilterDropdown
Section titled “FilterDropdown”A dropdown filter for selecting categories or status.
FooterConfig
Section titled “FooterConfig”Configuration for footer.
FooterLink
Section titled “FooterLink”A footer link.
FooterRenderer
Section titled “FooterRenderer”Renders the admin footer.
Initialize the renderer.
| Parameter | Type | Description |
|---|---|---|
| `config` | FooterConfig | None | Footer configuration |
Render the footer.
| Type | Description |
|---|---|
| str | HTML string for footer |
A container for form fields with HTMX submission support.
FormActions
Section titled “FormActions”Form actions component for submit/cancel buttons.
Example
FormActions( primary_text=“Save Changes”, secondary_text=“Cancel”, primary_loading=False, cancel_url=“/admin/users” )
Initialize form actions.
| Parameter | Type | Description |
|---|---|---|
| `primary_text` | str | Primary button text |
| `secondary_text` | str | None | Secondary button text (None to hide) |
| `primary_loading` | bool | Show loading state on primary button |
| `primary_disabled` | bool | Disable primary button |
| `cancel_url` | str | None | URL for cancel button (if not provided, uses history.back()) |
| `align` | str | Button alignment (left, center, right) **props: Additional properties |
Render the form actions.
FormField
Section titled “FormField”Form field wrapper with label, input, error message, and help text.
Generic CSS Grid component.
GroupBySwitcher
Section titled “GroupBySwitcher”Grouping dropdown switcher for DataTable.
Renders a compact dropdown listing the table columns as grouping
options (plus “No grouping”) and emits HTMX requests carrying the
group_by query param through the updated TableState.
HTMLDocument
Section titled “HTMLDocument”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
Initialize the document.
| Parameter | Type | Description |
|---|---|---|
| `config` | HTMLDocumentConfig | None | Document configuration |
Render the complete HTML document.
| Parameter | Type | Description |
|---|---|---|
| `title` | str | Document title **context: Additional context for subclass rendering |
| Type | Description |
|---|---|
| Markup | Complete HTML document as Markup |
Get body element attributes.
Override in subclasses to add classes, data attributes, etc.
| Type | Description |
|---|---|
| str | String of HTML attributes |
Render content for the head section.
Subclasses should implement this to add CSS links, inline styles, etc.
| Type | Description |
|---|---|
| str | HTML string for head section |
Render the main body content.
Subclasses should implement this to render the page content.
| Type | Description |
|---|---|
| str | Markup | HTML string or Markup for body content |
Render content at the end of body (before ).
Subclasses can override to add scripts, etc.
| Type | Description |
|---|---|
| str | HTML string for body end |
HTMLDocumentConfig
Section titled “HTMLDocumentConfig”Configuration for HTML document generation.
HTMXAttrs
Section titled “HTMXAttrs”Factory for HTMX attributes.
This class provides convenient static methods for generating HTMX attributes for common use cases. For more control, use HTMXAttrsBuilder directly.
Examples
Data refresh (filter, sort, paginate)
Section titled “Data refresh (filter, sort, paginate)”attrs = HTMXAttrs.for_data_refresh(state, “/admin/users”)
Full refresh (layout/view change)
Section titled “Full refresh (layout/view change)”attrs = HTMXAttrs.for_full_refresh(state, “/admin/users”)
Delete with confirmation
Section titled “Delete with confirmation”attrs = HTMXAttrs.for_delete(“/admin/users/123”, confirm=“Delete this user?”)
Bulk action
Section titled “Bulk action”attrs = HTMXAttrs.for_bulk_action(“/admin/users/bulk/delete”, “DELETE”)
Generate HTMX attributes for a full table refresh.
Use for: Layout changes, view changes, clearing all filters.
| Parameter | Type | Description |
|---|---|---|
| `state` | TableState | Current table state |
| `resource_prefix` | str | Base URL (e.g., "/admin/users") |
| `push_url` | bool | Update browser history (default True) **extra_params: Additional query parameters |
| Type | Description |
|---|---|
| dict[str, str] | Dict of hx-* attributes |
Generate HTMX attributes for a data zone refresh.
Use for: Filtering, sorting, pagination, search.
| Parameter | Type | Description |
|---|---|---|
| `state` | TableState | Current table state |
| `resource_prefix` | str | Base URL |
| `push_url` | bool | Update browser history (default True) **extra_params: Additional query parameters |
| Type | Description |
|---|---|
| dict[str, str] | Dict of hx-* attributes |
Generate HTMX attributes for opening a modal.
| Parameter | Type | Description |
|---|---|---|
| `url` | str | URL to load into modal |
| Type | Description |
|---|---|
| dict[str, str] | Dict of hx-* attributes |
Generate HTMX attributes for opening a slide-over panel.
| Parameter | Type | Description |
|---|---|---|
| `url` | str | URL to load into slide-over |
| Type | Description |
|---|---|
| dict[str, str] | Dict of hx-* attributes |
Generate HTMX attributes for a delete action.
| Parameter | Type | Description |
|---|---|---|
| `url` | str | Delete endpoint URL |
| `target_zone` | Zone | None | Zone to update after delete (default: DATA) |
| `confirm_message` | str | None | Optional confirmation dialog |
| Type | Description |
|---|---|
| dict[str, str] | Dict of hx-* attributes |
Generate HTMX attributes for a bulk action.
Bulk actions include the checked checkboxes from the table plus the action name so the server can dispatch correctly.
| Parameter | Type | Description |
|---|---|---|
| `url` | str | Bulk action endpoint URL |
| `method` | str | HTTP method (POST, DELETE, etc.) |
| `confirm_message` | str | None | Optional confirmation dialog |
| `action_name` | str | None | Action identifier sent as ``action`` form value |
| Type | Description |
|---|---|
| dict[str, str] | Dict of hx-* attributes |
Generate HTMX attributes for form submission.
| Parameter | Type | Description |
|---|---|---|
| `url` | str | Form action URL |
| `method` | str | HTTP method |
| `target_zone` | Zone | None | Zone to update on success (default: DATA) |
| `close_on_success` | Whether to close modal/slide-over |
| Type | Description |
|---|---|
| dict[str, str] | Dict of hx-* attributes |
Generate HTMX attributes for a live table input (search-as-you-type).
Exception to the baked-URL pattern: live inputs use hx-include to send the current input value with each keystroke, rather than baking state into the URL. The input value changes too frequently for URL-based state.
| Parameter | Type | Description |
|---|---|---|
| `state` | Current table state (not baked into URL — used for hx-include scope) | |
| `resource_prefix` | str | Base URL (e.g., "/admin/users") |
| `input_name` | str | None | Optional custom name attribute for the live input selector. Defaults to the SEARCH zone ID. |
| Type | Description |
|---|---|
| dict[str, str] | Dict of hx-* attributes for a live table input. |
Merge multiple HTMX attribute dictionaries.
Later values override earlier ones.
| Parameter | Type | Description |
|---|
| Type | Description |
|---|---|
| dict[str, str] | Merged dictionary |
HTMXAttrsBuilder
Section titled “HTMXAttrsBuilder”Builder for consistent HTMX attributes.
This class encapsulates the logic for generating correct HTMX attributes for different action types. Use the static methods on HTMXAttrs for convenience unless you need custom configuration.
Attributes: action: The type of action (determines target zone and swap mode) state: The current TableState (used for baked URLs) resource_prefix: The base URL for the resource (e.g., “/admin/users”) extra_params: Additional query parameters to include push_url: Whether to update browser history (default: True for refresh actions) confirm_message: Optional confirmation dialog message
Generate HTMX attributes based on action type.
Returns a dict of hx-* attributes ready to be spread onto an element.
HeadConfig
Section titled “HeadConfig”Configuration for head section.
HeadRenderer
Section titled “HeadRenderer”Renders the head section content.
Initialize the renderer.
| Parameter | Type | Description |
|---|---|---|
| `config` | HeadConfig | None | Head configuration |
Render the head content.
| Parameter | Type | Description |
|---|---|---|
| `extra_css` | str | Additional inline CSS to include |
| Type | Description |
|---|---|
| str | HTML string for head section |
Hidden
Section titled “Hidden”Hidden input field.
HtmxActionResponse
Section titled “HtmxActionResponse”Builder for HTMX action responses with merged HX-Trigger headers.
| Parameter | Type | Description |
|---|---|---|
| `toast` | Optional toast notification to include in the trigger payload. | |
| `trigger` | Additional HX-Trigger events to merge alongside the toast. | |
| `status_code` | HTTP status code for the response (default 200). |
Usage
return HtmxActionResponse( toast=ToastData(message="User deleted", type=ToastType.SUCCESS), trigger={"refresh-list": True}, status_code=200,).to_response()return HtmxActionResponse( toast=ToastData(message="User deleted", type=ToastType.SUCCESS), trigger={"refresh-list": True}, status_code=200,).to_response()Return a Starlette HTMLResponse with the merged HX-Trigger header.
| Type | Description |
|---|---|
| Any | ``starlette.responses.HTMLResponse`` with empty body and ``HX-Trigger`` header set. |
Icon atom that wraps `get_icon` for consistent usage in templates.
| Parameter | Type | Description |
|---|---|---|
| `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). |
ImageColumn
Section titled “ImageColumn”Image column with thumbnail preview.
Set image size in Tailwind units (e.g., 10 = 40px).
Make image circular.
Make image square with rounded corners.
Render as image thumbnail.
InfiniteScrollTrigger
Section titled “InfiniteScrollTrigger”A component that triggers an HTMX request when scrolled into view.
InfolistEntry
Section titled “InfolistEntry”A single labelled entry within an ``InfolistWidget``.
InfolistEntryType
Section titled “InfolistEntryType”
InfolistWidget
Section titled “InfolistWidget”Render a read-only list of labelled entries suitable for detail pages.
Entries are arranged in a configurable-column grid. Supports grouping by section headings.
InlineEditCell
Section titled “InlineEditCell”A table cell whose value can be edited in place.
On click the cell switches to an <input> (or <select> / <textarea>).
On blur / Enter it fires PATCH {resource_url} with {field_name}=<new_value>.
On Escape it discards the change and reverts.
| Parameter | Type | Description |
|---|---|---|
| `value` | Current display value. | |
| `resource_url` | URL to PATCH, e.g. ``"/admin/users/42"``. | |
| `field_name` | Form field name to send in the PATCH body. | |
| `cell_type` | ``"text"``, ``"number"``, ``"select"``, or ``"textarea"``. | |
| `options` | For ``cell_type="select"`` — list of ``{"value": …, "label": …}`` dicts. | |
| `placeholder` | Placeholder text for the input. | |
| `css_class` | Additional Tailwind classes on the outer container. | |
| `editable` | When ``False`` renders a plain non-editable cell. |
InlineToast
Section titled “InlineToast”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.
| Parameter | Type | Description |
|---|---|---|
| `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). |
Text input with label and error support.
| Parameter | Type | Description |
|---|---|---|
| `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 )
InputGroup
Section titled “InputGroup”Input with prefix or suffix add-ons.
JSManager
Section titled “JSManager”Manages JavaScript asset injection for layout rendering.
Initialize JS collections.
Add a JavaScript file.
| Parameter | Type | Description |
|---|---|---|
| `src` | str | URL to JS file |
| `defer` | bool | Add defer attribute |
| `async_` | bool | Add async attribute **attrs: Additional attributes |
Add inline JavaScript.
| Parameter | Type | Description |
|---|---|---|
| `script` | str | JavaScript code |
| `defer` | bool | If True, render at end of body |
Render JS for head section.
| Type | Description |
|---|---|
| str | HTML string with script tags |
Render deferred JS for end of body.
| Type | Description |
|---|---|
| str | HTML string with script tags |
JumpToPage
Section titled “JumpToPage”Component for jumping to a specific page number. Uses Zone-based targeting for consistent HTMX behavior.
KeyValueField
Section titled “KeyValueField”Component for editing key-value pairs (JSON dictionary).
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")Initialise a Label atom.
| Parameter | Type | Description |
|---|---|---|
| `text` | str | The visible label text. |
| `for_` | str | None | The ``id`` of the associated form control (renders as ``for``). |
| `required` | bool | When ``True`` appends a required indicator asterisk. |
| `size` | LabelSize | Text size variant — ``"xs"``, ``"sm"`` (default), ``"md"``, ``"lg"``. |
| `weight` | LabelWeight | Font-weight variant. |
| `muted` | bool | When ``True`` applies a muted/secondary text colour. **props: Additional HTML attributes forwarded to the element. |
Render the label element.
LayoutBase
Section titled “LayoutBase”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’
Initialize the layout.
| Parameter | Type | Description |
|---|---|---|
| `config` | BaseLayoutConfig | None | Layout configuration |
| `context` | BaseLayoutContext | None | Layout context |
Add a CSS file link.
| Parameter | Type | Description |
|---|---|---|
| `href` | str | URL to CSS file **attrs: Additional attributes (media, crossorigin, etc.) |
Add inline CSS.
| Parameter | Type | Description |
|---|---|---|
| `css` | str | CSS rules |
Render all CSS as HTML.
| Type | Description |
|---|---|
| str | HTML string with link and style tags |
Add a JavaScript file.
| Parameter | Type | Description |
|---|---|---|
| `src` | str | URL to JS file |
| `defer` | bool | Add defer attribute |
| `async_` | bool | Add async attribute **attrs: Additional attributes |
Add inline JavaScript.
| Parameter | Type | Description |
|---|---|---|
| `script` | str | JavaScript code |
| `defer` | bool | If True, render at end of body |
Render JS for head section.
| Type | Description |
|---|---|
| str | HTML string with script tags |
Render deferred JS for end of body.
| Type | Description |
|---|---|
| str | HTML string with script tags |
Get HTMX configuration.
| Type | Description |
|---|---|
| dict[str, Any] | Configuration dict for htmx.config |
Render HTMX script tag for head.
| Type | Description |
|---|---|
| str | HTML string with HTMX script |
Get HTMX-related body attributes.
| Type | Description |
|---|---|
| str | String of HTML attributes |
Generate ShadCN-compatible CSS variable declarations.
Get theme-related HTML element attributes.
| Type | Description |
|---|---|
| str | String of HTML attributes |
Inline script that applies dark class before paint (prevents FOUC).
Must run synchronously in <head> before any CSS paints.
Register Alpine.js theme toggle component data.
Render the complete layout.
| Parameter | Type | Description |
|---|---|---|
| `content` | str | Markup | Main page content |
| `title` | str | None | Page title (overrides context title) **extra_context: Additional context |
| Type | Description |
|---|---|
| Markup | Complete HTML document as Markup |
Get body element attributes including theme and HTMX.
Render head content (CSS, theme, HTMX).
Render body content.
Default implementation just returns content. Subclasses should override to add layout structure.
| Parameter | Type | Description |
|---|---|---|
| `content` | str | Main content **context: Additional context |
| Type | Description |
|---|---|
| str | Markup | HTML string or Markup |
Render content at end of body (deferred scripts).
LayoutSwitcher
Section titled “LayoutSwitcher”Simple layout switcher (stack | sidebar) for DataTable.
Renders compact options and uses HTMX to request the table fragment with the chosen layout_type query param.
LazySelect
Section titled “LazySelect”Select dropdown that support infinite scroll / lazy loading of options.
LineChart
Section titled “LineChart”
Create a consistent styled link element.
| Parameter | Type | Description |
|---|---|---|
| `label` | Link text | |
| `href` | URL | |
| `variant` | Visual style variant | |
| `size` | Optional size (sm, md, lg) |
ListColumn
Section titled “ListColumn”Column for rendering lists of strings (e.g., tags, categories).
LiveCounter
Section titled “LiveCounter”A simple counter that updates in real-time.
LiveDataTable
Section titled “LiveDataTable”Auto-refreshing data table variant.
Convenience subclass with table-appropriate defaults: longer interval and no pause/resume controls by default.
| Parameter | Type | Description |
|---|---|---|
| `url` | Endpoint returning updated table HTML fragment. | |
| `interval_ms` | Polling interval (default 30 000 ms = 30 s). | |
| `target_id` | Wrapper element ID. | |
| `show_controls` | Whether to show pause button (default True). |
LoadingOverlay
Section titled “LoadingOverlay”Full-screen or container loading overlay.
| Parameter | Type | Description |
|---|---|---|
| `message` | Optional loading message | |
| `fullscreen` | Whether to cover entire screen |
MarkdownEditor
Section titled “MarkdownEditor”Markdown editor with optional preview toggle. Uses Alpine.js for client-side preview mode switching.
MetricCard
Section titled “MetricCard”MetricProtocol card for dashboard statistics.
Example
MetricCard( value=“1,234”, label=“Total Users”, trend=“+12%”, trend_direction=“up”, icon=”👥”, color=“success” )
Initialize metric card.
| Parameter | Type | Description |
|---|---|---|
| `value` | str | float | The metric value (number or formatted string) |
| `label` | str | Description label |
| `trend` | str | None | Trend indicator (e.g., "+12%", "-5%") |
| `trend_direction` | TrendDirection | None | Direction of trend ("up" or "down") |
| `icon` | str | None | Optional icon (emoji or icon class) |
| `variant` | MetricCardVariant | Color variant **props: Additional properties |
Render the metric card.
MetricProtocol
Section titled “MetricProtocol”A single metric data point.
MetricType
Section titled “MetricType”Types of metrics to collect.
MetricsCollector
Section titled “MetricsCollector”Collect and track UI metrics.
This is a simple in-memory collector. For production, integrate with Prometheus, StatsD, or similar.
Increment a counter.
Record a histogram observation.
Set a gauge value.
Get counter value.
Get histogram statistics.
Get gauge value.
Reset all metrics.
Export all metrics as dictionary.
MiniBar
Section titled “MiniBar”
A FAANG-level modal dialog powered by Alpine.js.
MorphTo
Section titled “MorphTo”Polymorphic relationship selector.
Consisted of two dropdowns: one for the type and one for the ID.
MultiFileUpload
Section titled “MultiFileUpload”Premium multi-file upload with drag and drop.
MultiSelect
Section titled “MultiSelect”Premium searchable tags-style multi-select.
NativeMultiSelect
Section titled “NativeMultiSelect”Native browser multiple select dropdown.
NotificationBell
Section titled “NotificationBell”In-app notification bell with real-time updates via SSE.
Alpine.js-driven component that loads the persisted inbox from the admin JSON endpoints, displays an unread count badge on the bell icon, and shows a dropdown of recent notifications with mark-as-read support (posting back to the inbox endpoints).
| Parameter | Type | Description |
|---|---|---|
| `sse_url` | SSE endpoint URL for real-time notification events. | |
| `inbox_url` | Link to the full notification inbox page. The "View all" footer is only rendered when a URL is set. | |
| `inbox_api_url` | JSON endpoint returning the persisted inbox (``{"unread_count": ..., "notifications": [...]}``). | |
| `mark_read_url` | POST endpoint marking one message read; the literal ``{message_id}`` placeholder is replaced with the message ID. | |
| `mark_all_read_url` | POST endpoint marking every message read. | |
| `max_display` | Maximum number of notifications shown in the dropdown. **props: Extra HTML attributes forwarded to the root element. |
NumberInput
Section titled “NumberInput”Number input with min/max/step validation.
| Parameter | Type | Description |
|---|---|---|
| `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 |
PageLayout
Section titled “PageLayout”Full-page admin layout wrapper with a header bar and content area.
| Parameter | Type | Description |
|---|---|---|
| `title` | Page title rendered in the header. | |
| `children` | Main page content — string, htpy element, Component, or list thereof. | |
| `actions` | Optional list of elements (e.g. Buttons) rendered in the header right side. **props: Additional HTML attributes applied to the outer wrapper div. |
PageSizeSelector
Section titled “PageSizeSelector”Component for selecting the number of items per page. Uses Zone-based targeting for consistent HTMX behavior.
PaginationLinks
Section titled “PaginationLinks”Component for rendering numeric page links and navigation buttons. Uses Zone-based targeting for consistent HTMX behavior.
PasswordInput
Section titled “PasswordInput”Password input - TextInput with type='password'.
PieChart
Section titled “PieChart”
Popover
Section titled “Popover”Popover component for richer content than tooltips.
ProgressBar
Section titled “ProgressBar”Linear progress bar with percentage display.
| Parameter | Type | Description |
|---|---|---|
| `value` | Current progress value | |
| `max` | Maximum value (default 100) | |
| `label` | Optional label text | |
| `show_percentage` | Whether to show percentage text | |
| `size` | Height variant (sm, md, lg) |
Radio button group for single selection.
Rating
Section titled “Rating”Star rating component.
RawHTML
Section titled “RawHTML”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.
RealTimeFeed
Section titled “RealTimeFeed”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..."))RenderCache
Section titled “RenderCache”LRU cache for rendered component fragments.
Use for expensive-to-render components that don’t change often.
Get cached render result if valid.
Cache a render result.
Invalidate cache entries.
Decorator for caching render methods.
Repeater
Section titled “Repeater”A component that allows users to add/remove sets of fields. Useful for JSON arrays or HasMany relations.
RequestCoalescer
Section titled “RequestCoalescer”Coalesce rapid-fire requests into single requests.
Useful for batch operations or rapid filter changes.
ResponseOptimizer
Section titled “ResponseOptimizer”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 hash for content.
Check if we can return 304 Not Modified.
Optimize response with caching headers.
| Parameter | Type | Description |
|---|---|---|
| `content` | str | The HTML content to return |
| `request_etag` | str | None | The If-None-Match header value from request |
| Type | Description |
|---|---|
| tuple[str, int, dict[str, str]] | Tuple of (content, status_code, headers) |
RichEditor
Section titled “RichEditor”WYSIWYG editor using Trix. Requires Trix JS/CSS to be loaded in the page.
RichSelect
Section titled “RichSelect”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) — HTMXhx-getfires 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 thanSEARCH_THRESHOLDoptions orgroupsare present.
| Parameter | Type | Description |
|---|---|---|
| `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. |
Grid row component (flexible layout).
SearchBar
Section titled “SearchBar”Reusable search bar with icon and optional clear button.
Initialize search bar.
| Parameter | Type | Description |
|---|---|---|
| `name` | str | Input name attribute |
| `value` | str | Current search value |
| `placeholder` | str | Placeholder text |
| `show_icon` | bool | Whether to show search icon |
| `show_clear` | bool | Whether to show clear button **props: Additional props (HTMX attributes, etc.) |
Render search bar.
Section
Section titled “Section”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 ) )
Initialize section component.
| Parameter | Type | Description |
|---|---|---|
| `title` | str | Section title |
| `description` | str | None | Optional description |
| `icon` | str | None | Optional icon (emoji or icon class) |
| `collapsible` | bool | Whether section can be collapsed |
| `collapsed` | bool | Initial collapsed state **props: Additional properties |
Render the section.
Select
Section titled “Select”Select dropdown with label and error support.
| Parameter | Type | Description |
|---|---|---|
| `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 |
ServerToastChannel
Section titled “ServerToastChannel”Renders toast notification container and messages (server-driven via HTMX).
Initialize the renderer.
| Parameter | Type | Description |
|---|---|---|
| `config` | ToastConfig | None | Toast configuration |
Render toast payloads as HTML.
| Parameter | Type | Description |
|---|---|---|
| `toasts` | list[ToastData] | List of toast data objects |
| Type | Description |
|---|---|
| str | HTML string for the toast container with toasts |
Render the toast container with optional initial toasts.
| Parameter | Type | Description |
|---|---|---|
| `toasts` | list[ToastData] | None | List of toast messages to show initially |
| Type | Description |
|---|---|
| str | HTML string for toast container |
Render a single toast notification.
| Parameter | Type | Description |
|---|---|---|
| `toast` | ToastData | Toast to render |
| Type | Description |
|---|---|
| str | HTML string for toast |
SimpleAlert
Section titled “SimpleAlert”Inline alert component for contextual feedback.
| Parameter | Type | Description |
|---|---|---|
| `message` | Alert message | |
| `type` | Alert type (info, success, warning, error) | |
| `title` | Optional alert title |
SimplePagination
Section titled “SimplePagination”Prev / Next pagination with no total-count requirement.
Renders only a “Previous” button and a “Next” button, enabling
fast pagination without an expensive COUNT(*) query.
| Parameter | Type | Description |
|---|---|---|
| `page` | Current (1-based) page number. | |
| `per_page` | Items per page. | |
| `has_next_page` | Whether a next page exists. Set this by fetching ``per_page + 1`` rows and checking if more than ``per_page`` were returned. | |
| `base_url` | Base URL for page links. | |
| `extra_query` | Additional query string parameters to append (without leading ``&``). | |
| `hx_target` | HTMX target selector (default ``#main-content``). | |
| `hx_push_url` | Whether HTMX should push the URL (default ``"true"``). |
Skeleton
Section titled “Skeleton”Skeleton loader placeholder for content.
| Parameter | Type | Description |
|---|---|---|
| `variant` | Shape variant (text, circular, rectangular) | |
| `width` | CSS width value | |
| `height` | CSS height value | |
| `count` | Number of skeleton lines (for text variant) |
SlideOver
Section titled “SlideOver”A side-panel drawer component for auxiliary content or editing.
| Parameter | Type | Description |
|---|---|---|
| `size` | Panel width — ``sm``, ``md``, ``lg`` (default), ``xl``, ``2xl``, ``full`` | |
| `variant` | ``"default"`` (indigo accent) or ``"danger"`` (red accent for delete confirms) |
Slider
Section titled “Slider”Range slider input.
| Parameter | Type | Description |
|---|---|---|
| `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 |
SortableRecordList
Section titled “SortableRecordList”Drag-n-drop sortable list for reordering records.
| Parameter | Type | Description |
|---|---|---|
| `rows` | Sequence of record dicts (or objects with ``__getitem__``). | |
| `id_field` | Key used to identify each record (default ``"id"``). | |
| `label_field` | Key used as the visible label (default ``"title"``). | |
| `reorder_url` | URL for the HTMX PATCH request carrying the new order. | |
| `hx_target` | HTMX swap target (default ``"this"``). | |
| `hx_swap` | HTMX swap strategy (default ``"none"``). | |
| `handle_class` | CSS class to add to the drag handle icon. | |
| `empty_label` | Text shown when *rows* is empty. |
Sparkline
Section titled “Sparkline”
Spinner
Section titled “Spinner”Circular loading spinner with size variants.
| Parameter | Type | Description |
|---|---|---|
| `size` | Size variant (sm=16px, md=24px, lg=32px, xl=48px) | |
| `aria_label` | Accessible label announced to screen readers (default: "Loading...") |
A vertical flex-column layout container.
Stacks its children elements vertically with a Tailwind CSS gap.
| Parameter | Type | Description |
|---|---|---|
| `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"), ],)StatCard
Section titled “StatCard”Dashboard metric card.
SubmitButton
Section titled “SubmitButton”Submit button with automatic loading state.
| Parameter | Type | Description |
|---|---|---|
| `label` | Button text. | |
| `variant` | Same as Button. | |
| `size` | Same as Button. | |
| `disabled` | Whether button is disabled. **props: Additional attributes. |
SwapMode
Section titled “SwapMode”Valid HTMX swap modes.
Switch
Section titled “Switch”A premium toggle switch component implemented using the shared `Toggle` molecule.
SystemBox
Section titled “SystemBox”A compact system menu display for the sidebar footer that mirrors the behavior of `UserBox`. It renders compact icons inline and exposes block-style items (e.g., Settings) in a dropdown for discoverability.
A single tab within a ``TabGroup``.
TabGroup
Section titled “TabGroup”Render a set of tabs with Alpine.js-driven switching.
Each tab can hold a list of schema fields (for forms) or arbitrary content (for detail views).
TabPanel
Section titled “TabPanel”Wrapper for tab content. Automatically shows/hides based on the parent Tabs' state.
TablePagination
Section titled “TablePagination”Pagination component with HTMX support and baked URL pattern.
Supports two modes:
- State-based (recommended): Pass a TableState for baked URLs
- Legacy: Pass page/total/per_page directly
TableState
Section titled “TableState”Encapsulates the complete state of a DataTable. This state is derived from the URL and drives the UI rendering.
Create state from a request object (Starlette/ASGI compatible).
Export state to dictionary suitable for URL generation. Only includes non-default and non-empty values to keep URLs clean.
Return a canonical URL (path + query) for this TableState.
Override model_copy to preserve internal defaults.
Return a copy with a new page number.
Resets cursor for offset-based pagination.
Example
new_state = state.with_page(2) attrs = HTMXAttrs.for_data_refresh(new_state, prefix)
Return a copy with a new per_page value.
Resets to page 1 since row counts change.
Return a copy with a new search term.
Resets to page 1 since results change.
Return a copy with an updated filter value.
Resets to page 1 since results change.
Example
new_state = state.with_filter(“status”, “active”)
Return a copy with a filter removed.
Resets to page 1 since results change.
Return a copy with sort toggled on the given column.
If already sorting by this column, toggles direction. Otherwise, sets ascending sort on the column.
Example
new_state = state.with_sort(“name”) # asc new_state = new_state.with_sort(“name”) # desc
Return a copy with a new view type.
Return a copy with a new layout type.
Return a copy with a new grouping column.
Pass None to clear grouping. Resets to page 1 since
grouping changes the result set.
Example
new_state = state.with_group_by(“category”) cleared = state.with_group_by(None)
Return a copy with a new include_deleted value.
Resets to page 1 since results change.
Example
new_state = state.with_include_deleted(True)
Return a copy with all filters and search cleared.
Resets to page 1.
Return a copy with sorting cleared.
Set the resource prefix for URL generation.
Get the resource prefix for URL generation.
Render hidden inputs for state preservation.
Used as a fallback when baked URLs aren’t possible (e.g., form submissions that need to preserve table state).
These inputs should be placed INSIDE the TABLE zone.
| Parameter | Type | Description |
|---|---|---|
| `exclude` | list[str] | None | Optional list of field names to skip (avoid duplication with UI inputs) |
| Type | Description |
|---|---|
| list | List of htpy input elements |
A responsive tabbed interface component with smooth animations and client-side switching.
| Parameter | Type | Description |
|---|---|---|
| `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 |
TagsInput
Section titled “TagsInput”Premium tags input using Alpine.js. Allows adding strings as tags/chips.
TaskProgress
Section titled “TaskProgress”Real-time progress tracking component with SSE updates.
Connects to a Server-Sent Events endpoint to display live progress of a background task. Shows progress bar, status, and messages.
| Parameter | Type | Description |
|---|---|---|
| `task_id` | Unique identifier for the task | |
| `title` | Progress dialog title | |
| `auto_close` | Whether to auto-close on completion | |
| `on_complete` | URL to redirect to or JS callback on completion | |
| `stream_url` | Custom SSE endpoint URL (defaults to /admin/progress/{task_id}/stream) |
TextArea
Section titled “TextArea”Multi-line text input.
| Parameter | Type | Description |
|---|---|---|
| `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 |
TextColumn
Section titled “TextColumn”Simple text column with optional formatting.
Set text color (gray, red, blue, green, yellow, etc.).
Set text size (xs, sm, base, lg, xl).
Set font weight (normal, medium, semibold, bold).
Use monospace font.
Render as styled text.
TextInput
Section titled “TextInput”Text input with label and error support.
| Parameter | Type | Description |
|---|---|---|
| `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 )
TimePicker
Section titled “TimePicker”Time selection input.
Deprecated alias for InlineToast. Will be removed in a future release.
ToastConfig
Section titled “ToastConfig”Configuration for toast container.
ToastData
Section titled “ToastData”A toast notification message.
ToastRenderer
Section titled “ToastRenderer”Deprecated alias for ServerToastChannel. Will be removed in a future release.
ToastType
Section titled “ToastType”Toast notification types.
Toggle
Section titled “Toggle”Simple checkbox toggle (use Switch from forms.py for premium toggle).
ToggleIcon
Section titled “ToggleIcon”Icon-based toggle button useful for theme toggles.
| Parameter | Type | Description |
|---|---|---|
| `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 |
Tooltip
Section titled “Tooltip”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.
| Parameter | Type | Description |
|---|---|---|
| `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. |
UIComponentRenderedHook
Section titled “UIComponentRenderedHook”Payload fired after a UI component completes rendering.
Attributes: component_name: Qualified name of the component class that rendered.
UIConfig
Section titled “UIConfig”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).
Check config is safe for the target environment.
UIContext
Section titled “UIContext”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.
UIModule
Section titled “UIModule”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): passfrom lexigram.ui.config import UIConfig
@module( imports=[UIModule.configure(UIConfig(default_theme="default"))])class AppModule(Module): passCreate a UIModule with explicit configuration.
| Parameter | Type | Description |
|---|---|---|
| `config` | Any | None | UIConfig or ``None`` to use defaults. **kwargs: Additional keyword arguments forwarded to UIProvider. |
| Type | Description |
|---|---|
| DynamicModule | A DynamicModule descriptor. |
Return a no-op UIModule for testing.
Registers the UI provider with default configuration. No real rendering backends are configured.
| Parameter | Type | Description |
|---|---|---|
| `config` | Any | Optional UIConfig override (passed to UIProvider). |
| Type | Description |
|---|---|
| DynamicModule | A DynamicModule with default UI configuration. |
UIProvider
Section titled “UIProvider”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: trueui: default_theme: my-theme debug_components: trueRegistered 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.
Register UI services in the DI container.
| Parameter | Type | Description |
|---|---|---|
| `container` | ContainerRegistrarProtocol | The DI container registrar. |
No boot-time initialisation required for the UI module.
No shutdown work required for the UI module.
Check provider health.
| Parameter | Type | Description |
|---|---|---|
| `timeout` | float | Maximum seconds to wait for health check response. |
| Type | Description |
|---|---|
| HealthCheckResult | HealthCheckResult with status and component details. |
UITemplateRenderedHook
Section titled “UITemplateRenderedHook”Payload fired after a template is rendered to its final HTML output.
Attributes: template_name: Name or path of the template that was rendered.
UserBox
Section titled “UserBox”A compact user profile display for headers or sidebars.
ViewAction
Section titled “ViewAction”Standard View action implementation.
ViewSwitcher
Section titled “ViewSwitcher”Simple view switcher dropdown for DataTable.
Renders a compact dropdown listing available views and emits HTMX
requests to the resource with data_view query param.
VirtualScroll
Section titled “VirtualScroll”Component for handling infinite scroll and virtualization.
This uses HTMX ‘revealed’ trigger to load next chunks of data.
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
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, }
Return all registered zones.
Return all zones that can be targeted by HTMX swaps.
Look up a zone by its ID.
Returns None if no zone with that ID exists.
Look up a zone by its CSS selector.
Handles both “#zone-id” and “zone-id” formats.
Functions
Section titled “Functions”SkipLink
Section titled “SkipLink”Return an HTML skip navigation link for accessibility.
| Parameter | Type | Description |
|---|---|---|
| `target_id` | str | The ID of the target element to skip to. |
| `label` | str | The link text for the skip link. |
| Type | Description |
|---|---|
| str | An HTML anchor tag with sr-only CSS class. |
add_htmx_timing_header
Section titled “add_htmx_timing_header”Add Server-Timing header for HTMX requests.
announce
Section titled “announce”Create an invisible live region announcement.
This element will be announced by screen readers when inserted into the DOM. Use for dynamic content updates.
| Parameter | Type | Description |
|---|---|---|
| `message` | str | The text to announce |
| `priority` | AriaLive | POLITE (wait for idle) or ASSERTIVE (immediate) |
| `atomic` | bool | Whether to announce the entire region or just changes |
| Type | Description |
|---|---|
| str | HTML string for the announcement element |
announce_action_complete
Section titled “announce_action_complete”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.
| Parameter | Type | Description |
|---|---|---|
| `action` | str | Human-readable description of the action, e.g. ``"User deleted"`` or ``"Export"``. |
| `success` | bool | When ``True`` (default), appends ``"completed successfully"``; when ``False``, appends ``"failed"``. |
| Type | Description |
|---|---|
| str | An HTML string containing the invisible announcement element. |
announce_selection_change
Section titled “announce_selection_change”Create a polite screen-reader announcement for a selection state change.
| Parameter | Type | Description |
|---|---|---|
| `count` | int | Number of items currently in the selection. |
| `action` | str | Past-tense verb describing the selection action, e.g. ``"selected"`` (default) or ``"deselected"``. |
| Type | Description |
|---|---|
| str | An HTML string containing the invisible announcement element. |
announce_table_update
Section titled “announce_table_update”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.
| Parameter | Type | Description |
|---|---|---|
| `total` | int | Total number of items currently displayed or matching the current filter. |
| `page` | int | None | Current page number when the table is paginated. Omit (or pass ``None``) for unpaginated tables. |
| `search` | str | None | Active search / filter text. When provided, the message includes ``"filtered by ' |
| Type | Description |
|---|---|
| str | An HTML string containing the invisible announcement element. |
button_aria
Section titled “button_aria”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.
| Parameter | Type | Description |
|---|---|---|
| `label` | str | Accessible name for the button, mapped to ``aria-label``. |
| `pressed` | bool | None | For toggle buttons, the current pressed state. ``True`` maps to ``aria-pressed="true"``, ``False`` to ``"false"``, ``None`` omits the attribute entirely. |
| `expanded` | bool | None | For disclosure/accordion buttons, whether the controlled region is currently visible. Maps to ``aria-expanded``. |
| `controls` | str | None | ID of the element this button controls. Maps to ``aria-controls``. |
| `haspopup` | str | None | Type of popup this button opens, e.g. ``"menu"``, ``"listbox"``, ``"dialog"``. Maps to ``aria-haspopup``. |
| `disabled` | bool | When ``True``, adds ``aria-disabled="true"``. |
| Type | Description |
|---|---|
| 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
Section titled “cached_render”Decorator for caching component renders.
| Parameter | Type | Description |
|---|---|---|
| `component_name` | str | None | Name for the cached component fragment. |
| `cache` | RenderCache | None | RenderCache instance to use. When None, returns an identity decorator. |
cell_aria
Section titled “cell_aria”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.
| Parameter | Type | Description |
|---|---|---|
| `colindex` | int | None | 1-based column position within the full column set. Maps to ``aria-colindex``. Required when columns are hidden. |
| `rowindex` | int | None | 1-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. |
| Type | Description |
|---|---|
| dict[str, str] | A ``dict[str, str]`` of HTML attribute names to their string values. |
component
Section titled “component”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.
| Parameter | Type | Description |
|---|---|---|
| `name` | str | None | Logical component name used for registration and cache keys. Defaults to the decorated function's ``__name__``. |
| `cacheable` | bool | When ``True``, signals that the component's rendered output may be cached by the render pipeline. Defaults to ``False``. |
| Type | Description |
|---|---|
| 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
Section titled “debounced_search_attrs”Generate HTMX attributes for a debounced search input.
| Parameter | Type | Description |
|---|---|---|
| `url` | str | URL to search endpoint |
| `delay_ms` | int | Debounce delay in milliseconds |
| `target` | str | None | HTMX target (defaults to Zones.DATA) |
| Type | Description |
|---|---|
| dict[str, str] | Dictionary of HTMX attributes |
dialog_aria
Section titled “dialog_aria”Return ARIA attributes for a modal or non-modal dialog overlay.
| Parameter | Type | Description |
|---|---|---|
| `label` | str | Accessible name for the dialog, mapped to ``aria-label``. Use a concise title that describes the dialog's purpose, e.g. ``"Confirm deletion"``. |
| `describedby` | str | None | ID of an element that provides a longer description of the dialog's purpose. Maps to ``aria-describedby``. |
| `modal` | bool | When ``True`` (default), adds ``aria-modal="true"`` to signal that background content is inert while the dialog is open. |
| Type | Description |
|---|---|
| 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"}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
Section titled “flash_to_toast”Convert Flask/Starlette flash messages to toasts.
| Parameter | Type | Description |
|---|---|---|
| `flash_messages` | list[tuple[str, str]] | None | List of (category, message) tuples |
| Type | Description |
|---|---|
| list[ToastData] | List of ToastData objects |
get_icon
Section titled “get_icon”Render a Lucide icon by name.
get_ui_context
Section titled “get_ui_context”Return the current request-scoped UIContext, or ``None`` outside a request.
| Type | Description |
|---|---|
| UIContext | None | The active UIContext set by set_ui_context, or ``None`` if called outside of a request (e.g. during startup). |
header_aria
Section titled “header_aria”Return ARIA attributes for a sortable or static column header cell.
| Parameter | Type | Description |
|---|---|---|
| `label` | str | Accessible name for the column, mapped to ``aria-label``. |
| `sortable` | bool | When ``True``, adds an ``aria-sort`` attribute to indicate the column participates in sorting. Defaults to ``False``. |
| `sort_direction` | str | None | Current sort direction. Pass ``"asc"`` for ascending, ``"desc"`` for descending, or ``None`` (default) to output ``aria-sort="none"`` when *sortable* is ``True``. |
| Type | Description |
|---|---|
| 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
Section titled “htmx_error_response”Build an HTMX-compatible error response.
infinite_scroll_trigger
Section titled “infinite_scroll_trigger”Create an infinite scroll trigger element.
| Parameter | Type | Description |
|---|---|---|
| `url` | str | URL to fetch next page from |
| `target` | str | None | HTMX target selector (defaults to Zones.DATA) |
| `swap` | str | HTMX swap mode |
| `threshold` | str | Distance from bottom to trigger load |
| Type | Description |
|---|---|
| str | HTML string for the trigger element |
keyboard_navigation_script
Section titled “keyboard_navigation_script”Return a script tag with keyboard navigation helpers.
| Type | Description |
|---|---|
| str | An HTML script tag with keyboard navigation JavaScript. |
lazy_load_placeholder
Section titled “lazy_load_placeholder”Create a lazy-load placeholder that fetches content on trigger.
| Parameter | Type | Description |
|---|---|---|
| `url` | str | URL to fetch content from |
| `target_id` | str | ID of the element to replace |
| `trigger` | str | HTMX trigger (load, revealed, intersect, etc.) |
| `placeholder` | str | None | Optional placeholder content (defaults to skeleton) |
| Type | Description |
|---|---|
| str | HTML string for the placeholder |
live_region_aria
Section titled “live_region_aria”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.
| Parameter | Type | Description |
|---|---|---|
| `politeness` | AriaLive | Interrupt behaviour for the announcement. Use AriaLive.POLITE (default) to wait until the user is idle, or AriaLive.ASSERTIVE for time-sensitive alerts. |
| `atomic` | bool | When ``True`` (default), the entire region is re-read on every change rather than just the changed nodes. |
| Type | Description |
|---|---|
| dict[str, str] | A ``dict[str, str]`` of HTML attribute names to their string values. |
measure_render_time
Section titled “measure_render_time”Decorator to measure render time.
not_found_error
Section titled “not_found_error”Create a not found error response (404).
optimize_htmx_response
Section titled “optimize_htmx_response”Convenience function for response optimization.
| Parameter | Type | Description |
|---|---|---|
| `content` | str | HTML content to optimize. |
| `request_etag` | str | None | ETag from the incoming request for cache validation. |
| `optimizer` | ResponseOptimizer | None | ResponseOptimizer instance. When None, returns the content unchanged. |
permission_error
Section titled “permission_error”Create a permission error response (403).
render_to_string
Section titled “render_to_string”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
Section titled “render_validation_errors”Render validation errors as an HTML string.
reset_ui_context
Section titled “reset_ui_context”Restore the previous UI context using the token returned by set_ui_context.
| Parameter | Type | Description |
|---|---|---|
| `token` | contextvars.Token[UIContext | None] | The token returned by set_ui_context. |
row_aria
Section titled “row_aria”Return ARIA attributes for a table row element.
| Parameter | Type | Description |
|---|---|---|
| `index` | int | 1-based row position within the full dataset (not the current page). Maps to ``aria-rowindex``. |
| `selected` | bool | Whether this row is currently selected. Maps to ``aria-selected``. |
| `expanded` | bool | None | For tree-grid rows, whether the row is expanded. Pass ``None`` (default) to omit the attribute entirely. |
| Type | Description |
|---|---|
| dict[str, str] | A ``dict[str, str]`` of HTML attribute names to their string values. |
search_aria
Section titled “search_aria”Return ARIA attributes for a search input field.
| Parameter | Type | Description |
|---|---|---|
| `label` | str | Accessible name for the search field. Defaults to ``"Search"``. |
| `controls` | str | None | ID of the live region or results container that this input updates. Maps to ``aria-controls`` and helps screen readers announce that results are available. |
| Type | Description |
|---|---|
| dict[str, str] | A ``dict[str, str]`` of HTML attribute names to their string values. |
server_error
Section titled “server_error”Create a server error response (500).
set_ui_context
Section titled “set_ui_context”Bind *ctx* as the active UI context for the current async task.
| Type | Description |
|---|---|
| contextvars.Token[UIContext | None] | A Token that can be passed to reset_ui_context to restore the previous value. |
shadcn_css
Section titled “shadcn_css”Generate ShadCN-compatible CSS with optional overrides.
| Parameter | Type | Description |
|---|---|---|
| `primary` | str | None | Override primary color (oklch or hex value). |
| `background` | str | None | Override background color. |
| `foreground` | str | None | Override foreground color. |
| `radius` | str | None | Override border radius. |
| `success` | str | None | Override success color. |
| `warning` | str | None | Override warning color. |
| `info` | str | None | Override info color. |
| Type | Description |
|---|---|
| Complete CSS string with | root and .dark variable blocks. |
tab_aria
Section titled “tab_aria”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.
| Parameter | Type | Description |
|---|---|---|
| `label` | str | Accessible name for the tab, mapped to ``aria-label``. |
| `selected` | bool | Whether this tab is currently the active tab. Maps to ``aria-selected``. |
| `controls` | str | None | ID of the ``tabpanel`` element this tab reveals. Maps to ``aria-controls``. |
| Type | Description |
|---|---|
| dict[str, str] | A ``dict[str, str]`` of HTML attribute names to their string values. |
table_aria
Section titled “table_aria”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.
| Parameter | Type | Description |
|---|---|---|
| `label` | str | Human-readable label describing the table's content, used as ``aria-label``. |
| `rowcount` | int | None | Total 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 | None | Total number of columns. Required when some columns are hidden or the table uses column groups. |
| `sortable` | bool | Reserved for future use. Pass ``True`` to signal that column headers may carry ``aria-sort`` attributes. |
| Type | Description |
|---|---|
| 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
Section titled “tabpanel_aria”Return ARIA attributes for a tab panel content area.
The panel must be associated with its controlling tab via labelledby.
| Parameter | Type | Description |
|---|---|---|
| `labelledby` | str | ID of the ``tab`` element that controls this panel. Maps to ``aria-labelledby``. |
| `hidden` | bool | When ``True``, adds ``aria-hidden="true"`` to hide the panel from assistive technologies when its tab is not selected. |
| Type | Description |
|---|---|
| dict[str, str] | A ``dict[str, str]`` of HTML attribute names to their string values. |
timeout_error
Section titled “timeout_error”Create a timeout error response (504).
validation_error
Section titled “validation_error”Create a validation error response (422).
Exceptions
Section titled “Exceptions”UIError
Section titled “UIError”Base exception for all UI-domain errors.