Reflex integration
The Reflex integration makes an xy chart a first-class Reflex component. It keeps small handles and app state in Reflex while it sends chart data and interaction work through a binary data path, so large arrays do not pass through JSON state updates.
System boundary
The adapter connects three responsibilities without moving chart ownership into Reflex. Reflex owns application state, event handlers, and component layout. xy owns chart structure, data processing, rendering, and interaction calculations. The adapter joins these parts through typed handles, chart props, and semantic events.
The integration supports three chart sources:
| Source | Main use | Runtime needs |
|---|---|---|
| Concrete chart or columns | Fixed data | A static payload asset; no chart backend |
@reflex_xy.figure handle | State changes that alter chart structure | Reflex state and the chart data plane |
Data-bound plan plus @reflex_xy.data handle | State changes that alter columns only | Reflex state and the chart data plane |
The data plane uses the app's existing socket connection. Chart buffers therefore share the app's connection life cycle and do not require a second service or route.
The adapter uses the chart model described in Python chart API and exposes the browser state behavior described in Interaction and view state.
Application setup
Plugin registration
The application enables the adapter with reflex_xy.XYPlugin() in rxconfig.py, or with reflex_xy.setup(app) after creating the Reflex app. Both forms attach the chart service once. The app must have Reflex state enabled because the adapter needs the app socket and session identity.
At startup, setup registers the chart namespace, connects registry updates to client broadcasts, and prepares chart plans for backend workers. It also starts the lifetime task that tracks the serving loop and removes idle cached chart data. Page code must be safe to evaluate more than once because plan registration can evaluate page functions during startup as well as during the frontend build.
References: python/…/app.py• L1-18 python/…/app.py• L54-84 python/…/app.py• L87-129
Shared socket namespace
The chart namespace is /_xy, which is a Socket.IO namespace inside the app's existing physical websocket rather than a new URL endpoint. The browser sends subscriptions and chart messages to this namespace while Reflex continues to use its normal application namespace.
The namespace carries small JSON metadata and binary attachments for columns. A subscription receives a full chart payload. Later messages carry interaction replies, selection masks, view changes, or streamed points. Each subscription starts a version epoch so a reconnect or worker change cannot apply messages from the prior chart generation.
sequenceDiagram
participant Browser
participant Reflex as Reflex app socket
participant XY as /_xy namespace
participant State as Reflex state
participant Cache as XY cache
Browser->>Reflex: Connect with session token
Browser->>XY: Subscribe with chart handle
XY->>Cache: Find or rebuild chart
Cache->>State: Read durable state when needed
XY-->>Browser: Payload and binary columns
Browser->>XY: View, pick, or selection message
XY-->>Browser: Versioned result
State->>Cache: State change republishes chart
Cache-->>XY: Broadcast refreshed payload
XY-->>Browser: Room-wide update
References: python/…/namespace.py• L1-34 python/…/namespace.py• L175-225 python/…/XYChart.jsx• L1-34
Component sources
Live figure sources
reflex_xy.chart(figure=...) mounts a live chart from a FigureHandle. The handle can come from an @reflex_xy.figure state variable, reflex_xy.inline(), or the development-oriented reflex_xy.register(). The component uses the handle to subscribe to the chart namespace and to connect browser interactions to the chart engine.
An @reflex_xy.figure method is the recipe for a chart whose structure depends on state. Its computed value is only a typed handle. When a dependency changes, Reflex evaluates the method again and the adapter publishes a new payload under the same chart identity, which lets the browser update the mounted chart without changing the component tree.
inline() is suited to fixed data that still needs server-side picks or drill-down. It creates a content-based handle at module scope and shares that chart across viewers. register() is not a recovery path for a multi-worker deployment because its process-local chart has no state recipe.
References: python/…/component.py• L1-16 python/…/component.py• L69-117 python/…/vars.py• L1-30 python/…/__init__.py• L336-389
Static chart sources
Passing a concrete xy.Chart to reflex_xy.chart(chart) selects the static source. The adapter compiles the chart's first-paint payload into a content-addressed .xyf asset under the Reflex app's assets directory. The browser fetches that file and renders it without a registry entry, socket subscription, or backend state.
This source keeps client-side navigation, local hover data, and client-side density refinement. It does not provide server-side row picks, selection resolution, streaming, or other kernel round-trips. The asset URL remains stable when its frame is unchanged, so browser caching and static reflex export work without a live backend.
Facet charts use the same static idea at panel level. The adapter mounts one static chart per facet panel and keeps the grid layout outside the chart payload.
References: python/…/payload_asset.py• L1-30 python/…/payload_asset.py• L60-89 python/…/component.py• L246-316 python/…/component.py• L405-429
Chart props
The component separates chart source props from layout props and event props. Live sources use figure; static sources use src; data-bound sources use plan and data. The typed handle props make an incorrect state variable fail during page evaluation instead of producing a silent browser failure.
The flat factories such as scatter_chart and line_chart turn mark and chart options into a single component. The composed form accepts xy marks, annotations, and chrome as data-free nodes. Unknown top-level names fail at page evaluation, while CSS remains explicit through style. The component defaults to a full-width mount with a 420-pixel height, and the browser fits the payload to that mount.
Static chart class names are read from the chart payload for Tailwind discovery. Live charts cannot expose their runtime payload during the build, so tailwind_classes supplies the literal class inventory that the build scan needs. A custom tooltip can be mounted as a component child or through the tooltip source configuration.
References: python/…/component.py• L80-152 python/…/component.py• L333-439 python/…/factories.py• L261-335 python/…/XYChart.jsx• L280-335
State bridge
Rebuildable chart state
The process-local chart registry is a cache, not the source of truth. A figure token records the session, state class, and variable name. If a reconnect reaches another worker or an idle cache entry was removed, the adapter reads the session state that Reflex already stores and runs the same state method again.
This design avoids a separate figure server and avoids storing chart buffers in Redis. It also means figure and data methods must be pure functions of their state. A method that depends on hidden process state can rebuild a different chart on another worker even when the token is the same.
The adapter checks the session identity embedded in state-derived tokens. A chart token from another session is rejected. Invalid tokens, missing state methods, and failed rebuilds return an error to the chart client rather than crashing the application worker.
References: python/…/state_bridge.py• L1-23 python/…/state_bridge.py• L41-115 python/…/registry.py• L1-15 python/…/namespace.py• L569-629
Handle values
FigureHandle and DataHandle are small immutable values that hold a token. Reflex serializes them as objects containing token, so state deltas carry identity rather than numeric chart data. An empty token means that hydration is not complete or that the state method currently returns no chart or data.
The two handle types have different meanings. A figure handle names a chart that can receive interaction messages. A data handle names only a column set and must be combined with a compiled chart plan before it can produce a chart subscription.
References: python/…/handles.py• L1-19 python/…/handles.py• L33-69 python/…/tokens.py• L1-28
Data-variable binding
Data methods
@reflex_xy.data declares a state method that returns only named columns. The method can be synchronous or asynchronous and can return None when no data is available. The adapter publishes the columns under a deterministic data token and returns a typed DataHandle to Reflex.
Annotate the return value with a TypedDict when possible. The chart factory then checks channel names against that schema while the page compiles. Without a usable schema annotation, the adapter still checks the mapping and array-like values when the method first runs.
Columns in one data method may have different lengths or dimensions. The mark that consumes them owns checks for related lengths and shapes, such as paired x and y rows or a two-dimensional heatmap grid.
References: python/…/data_vars.py• L1-23 python/…/data_vars.py• L55-84 python/…/data_vars.py• L177-228
Chart plans
The data-bound API keeps chart structure in the page and keeps state methods focused on columns. A flat factory binds channels such as x="time" to column names. The composed form uses the same rule for several marks that share one data handle.
At page evaluation, the adapter validates the chart structure with empty placeholder columns. It stores a content-based plan digest and the names of the columns that the chart needs. At runtime, the plan binds to the current columns and creates a fresh chart figure. This split catches bad chart options and typed column-name errors early without loading real data during page compilation.
When a data method changes, the adapter replaces the column set and rebuilds mounted charts that depend on it. The plan and its chart component stay stable. The browser receives the new columns under the same data identity, which preserves the mounted view and selection when the chart can update in place.
Data handles also work with normal Reflex control flow. A conditional can choose between data variables with the same schema, and a typed list of handles can drive repeated chart components.
References: python/…/factories.py• L1-46 python/…/factories.py• L533-580 python/…/plan.py• L1-34 python/…/plan.py• L230-239
Event handling
Semantic event props
Live component props turn chart actions into normal Reflex event handlers. The adapter sends small semantic payloads and keeps chart buffers on the data plane. Static charts can use browser-resolved events, but they cannot use events that need the server-side interaction kernel.
| Prop | Meaning | Static source |
|---|---|---|
on_point_hover | Resolved point row | Not available |
on_point_click | Resolved point row with screen and modifier data | Not available |
on_select_end | Completed selection summary or clear | Not available |
on_view_change | Viewport domains during and after navigation | Available |
on_hover | Structured browser hover payload | Available |
on_animation_start / on_animation_end | Animation lifecycle payload | Available |
Point events identify the trace and canonical row. They include x/y data coordinates and the other values encoded for that row. The structured on_hover event is resolved in the browser and can drive a custom tooltip without a backend round-trip.
References: python/…/component.py• L58-62 python/…/component.py• L104-124 python/…/component.py• L140-151 python/…/events.py• L62-116
View events
View changes are resolved in the browser and sent through on_view_change as a throttled stream. The payload contains x and y domains, the source of the navigation, and an update or final phase. The update phase supports dependent charts that should follow a pan or zoom while the final phase gives state a settled viewport.
Because the event is a normal Reflex event, a handler can store the reported domain in state. A dependent @reflex_xy.data method can then use that domain to publish only the visible rows while its chart plan remains unchanged.
References: python/…/events.py• L179-206 python/…/XYChart.jsx• L546-591 python/…/XYChart.jsx• L597-609
Selections and view state
Selection payloads
Box and lasso selection results cross the Reflex boundary as a bounded summary. The payload states the selection kind, data bounds or polygon, total selected rows, canonical row IDs, a bounded row projection, and whether the result was truncated. A clear is represented as a selection event with cleared set.
The bounded form keeps event traffic small. When a handler needs every selected row and the payload says truncated, reflex_xy.resolve_selection(event) resolves the geometry against the live figure and returns the complete canonical xy.Selection. Unknown, malformed, empty, and cleared events return no selection.
References: python/…/events.py• L118-176 python/…/selections.py• L1-48 python/…/XYChart.jsx• L882-915
Programmatic view and selection
Server code can change a live chart without rebuilding its component. set_view and reset_view send room-wide view changes. select and clear_selection send room-wide selection changes. These helpers accept a FigureHandle or a compatible figure token and use the same client mutation paths as user gestures.
The browser orders these pushes with payload refreshes and append messages. It restores durable view ranges and selection geometry after a state-driven refresh, while it suppresses callbacks caused only by restoration. This lets a state update change data without treating the restore as a new user action.
For the shared view and interaction model, see Interaction and view state.
References: python/…/app.py• L297-330 python/…/XYChart.jsx• L714-821 python/…/XYChart.jsx• L687-713
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the component's handle types, serializers, and the browser's token selection logic aligned. A handle that serializes differently can leave a chart in the not-ready state.
- Keep events.py aligned with the event envelopes produced by assets/XYChart.jsx; field drift changes the contract seen by Reflex handlers.
- When changing data-bound plan structure or channel rules, consider both frontend page evaluation and backend-only plan registration. All workers must be able to resolve the same plan digest.
- When changing transport payloads, preserve the shared Socket.IO connection contract and the browser attachment limit. A malformed or oversized packet can affect the whole app websocket.
- When changing selection or view pushes, preserve generation and version ordering so a refresh cannot apply an older mask or viewport after newer data arrives.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
Chart page uses @reflex_xy.figure or @reflex_xy.data without state-enabled Reflex setup | No app socket exists for handles or chart data | Register XYPlugin or call setup(app) on an app with state enabled |
| Static chart receives a kernel-only event prop | Page compilation fails instead of installing a handler that never fires | Use a live figure or data-bound source for point and selection events |
| Data-bound channel is absent from a typed data schema | Page compilation fails with the missing column | Update the TypedDict or use the correct channel name |
| A worker has no matching plan digest after page or code drift | The chart receives a resync error rather than binding unknown structure | Keep page evaluation repeatable and let the page recompile before reconnecting |
| Selection event is truncated but the handler reads only its row list | The handler sees only the bounded projection | Call resolve_selection(event) for the complete selection |
| State method depends on hidden process state | A reconnect or another worker can rebuild a different chart | Make figure and data methods functions of state and declared inputs |
Key files
| File | Why to read it |
|---|---|
| python/…/app.py | App setup, plugin wiring, startup plan registration, and public chart update helpers |
| python/…/component.py | Source selection, component props, static/live boundaries, and mount behavior |
| python/…/XYChart.jsx | Browser subscription, payload mounting, event dispatch, and update ordering |
| python/…/namespace.py | Shared socket namespace and chart message boundary |
| python/…/vars.py | State-backed figure handles and chart rebuild triggers |
| python/…/data_vars.py | State-backed column handles and data validation |
| python/…/plan.py | Data-free chart structure and runtime column binding |
| python/…/state_bridge.py | Recovery of figures and columns from Reflex state |
| python/…/payload_asset.py | Static binary asset generation for backend-free charts |
| python/…/events.py | Typed descriptions of the semantic event payloads |
| python/…/selections.py | Complete server-side selection resolution |
| examples/…/xy_reflex_demo.py | End-to-end examples of data binding, state-driven charts, streaming, view links, and conditional sources |