Introduction
gpui-table turns a Rust row struct into the delegate and column
metadata required by gpui-kit’s DataTable. Opt-in
attributes add typed filter controls, incremental loading, localized labels,
registry metadata, and MCP query tools while the application keeps ownership of
its rows and query execution.
Who this guide is for
This guide is for Rust application developers who already have a GPUI application, window, and view. It assumes familiarity with GPUI entities and render methods.
Use the gpui-table facade for derives and table contracts, and
gpui-table-component for built-in filter widgets. Applications render
gpui_kit::component::table::DataTable directly.
Mental model
For a row type named User,
#[derive(GpuiTable)] generates
UserTableDelegate and UserTableColumn. Adding
#[gpui_table(filters)] also generates
UserFilterEntities and UserFilterValues.
The generated delegate owns table-facing sorting and visibility over the source rows. The application still decides:
- where rows come from and when they change
- how
DataTableand filter controls are laid out - how loading and backend queries run
- whether table metadata or rows are exposed to external tooling
Continue with Getting started to render a table. Use Typed filters for generated filter state, Filter components and custom shapes for direct widgets or domain value types, and MCP query tools when non-GPUI clients should query rows.
Getting started
This path produces a DataTable backed by typed application rows and generated
filter controls.
The development branch uses GPUI Kit 0.11 and Storybook 0.9. The published gpui-table 0.9 line uses Kit 0.9 and Storybook 0.8, and the gpui-table 0.8 line targets Kit 0.8. Keep these public GPUI type families together.
Prerequisites
Use Rust 1.100 or later to build the development branch. The dependency block below is for the published gpui-table 0.9 line and uses its matching Kit:
[dependencies]
gpui-kit = "0.9.0"
gpui-table = "0.9"
gpui-table-component = "0.9"
Generated table code refers to gpui_kit directly, so keep it as a direct
dependency using the version or source selected by the application. See
Features and integration crates when a row uses numeric range
filters, Fluent labels, SpacetimeDB values, or MCP.
Initialize gpui-kit during application startup, then initialize localization
for the built-in table filters:
gpui_kit::component::init(cx);
gpui_table_component::i18n::init(cx)?;
Define the rows
Derive GpuiTable on a named struct. Every visible field type must implement
TableCell; built-in scalar and date types already do. This faceted enum
derives both Filterable for its filter options and TableCell for rendering:
use gpui_table::{Filterable, GpuiTable, TableCell};
#[derive(Clone, Eq, Filterable, Hash, PartialEq, TableCell)]
enum UserStatus {
Active,
Suspended,
}
#[derive(Clone, GpuiTable)]
#[gpui_table(filters)]
struct User {
#[gpui_table(
sortable,
width = 160.,
filter(gpui_table_component::TextFilter)
)]
name: String,
#[gpui_table(
width = 120.,
filter(gpui_table_component::FacetedFilter::<UserStatus>.searchable(true))
)]
status: UserStatus,
}
Create and render the table
Construct the generated delegate from a Vec<User>, put it in TableState,
and build the generated filters against that state. Store the table entity and
filter collection on the owning view:
use gpui_kit::component::table::{DataTable, TableState};
let delegate = UserTableDelegate::new(rows);
let table = cx.new(|cx| TableState::new(delegate, window, cx));
let filters = UserFilterEntities::build_for_table(table.clone(), cx);
let element = DataTable::new(&table)
.stripe(true)
.scrollbar_visible(true, true);
Keep the TableState entity on the owning view. Observe it when delegate
updates should rerender parent controls such as status bars or filter badges.
Render the entries returned by filters.filter_sidebar_data(cx) to make the
filter widgets visible; Typed filters shows that flow.
Verify the result
The table should display one row for each item passed to
UserTableDelegate::new. Clicking the name header should change the sort
order, and changing a rendered filter should narrow the visible rows without
replacing delegate.rows.
If the derive reports that a field does not implement TableCell, derive it on
an application value object or use a custom cell renderer. If rendering panics
because localization state is missing, run both initialization calls above
before creating or rendering the filters.
Columns and rows
Each non-skipped field becomes a column in source order. Attributes control the
initial column configuration, while the generated delegate owns sorting and
maps visible rows back to the source rows vector.
#[derive(Clone, gpui_table::GpuiTable)]
#[gpui_table(
id = "build-history",
context_menu_route = "/builds/{id}",
context_menu_label = "Open build"
)]
struct BuildRow {
#[gpui_table(skip, context_menu_id)]
internal_id: u64,
#[gpui_table(width = 220., sortable)]
package: String,
#[gpui_table(width = 100., resizable = false)]
status: String,
#[gpui_table(width = 140., movable = false, sortable, ascending)]
started_at: jiff::Timestamp,
}
Common field options are:
| Option | Effect |
|---|---|
skip | Excludes the field from generated columns |
title = "Label" | Overrides the displayed column label |
col = "stable-key" | Overrides the column key |
width = 160. | Sets the initial width; the default is 100. |
sortable | Enables delegate sorting for the field |
ascending or descending | Selects the initial sort direction |
fixed = "left" or "right" | Pins the column to that side |
text_right | Right-aligns cell text |
resizable = false or movable = false | Disables that interaction |
style = path::to_fn | Replaces the default renderer for this field |
sort_key = path::to_fn | Supplies a typed optional calculated ordering key |
ascending and descending cannot be combined. Initial directions also enable sorting. See
Order rows and calculated keys for multiple keys, stable row
identity, null placement and calculated keys.
Date and time cells
Built-in Jiff dates and times use localized ICU formatting. A bare
jiff::Timestamp displays in the system timezone (the browser’s timezone on
WebAssembly), while a jiff::ZonedDateTime displays in its own zone. Valid
offsets outside ICU’s 18-hour range use the original Jiff representation. Date
filters have a separate contract: civil and zoned datetimes retain their
calendar date, and bare Jiff instants and SpacetimeDB timestamps match by UTC
date.
Jiff civil years are limited to −9999 through 9999. A leap-second input with
second 60 is interpreted by Jiff as second 59; it is not stored literally as
60. If the exact original text must be displayed, use DisplayCell<String>
instead of a typed date or time cell. That text is not a typed date filter
value.
Render application value objects
#[derive(TableCell)] delegates a single-field wrapper to the inner field’s
existing renderer:
#[derive(Clone, gpui_table::TableCell)]
struct Revision(String);
Use #[table_cell(display)] only when the wrapper itself implements
std::fmt::Display. Use #[table_cell(format = path::to::formatter)] when a
function taking &Revision should produce its label. For a complete custom
GPUI element, use the style hook described in
Loading and custom cells.
Keep row visibility current
The generated delegate keeps source rows in delegate.rows. Its visible row
view composes generated filters with an optional application-owned row scope.
Call refresh_filtered_rows() after in-place row mutations that may change
visibility.
The table ID defaults to the row type in snake case. Set
#[gpui_table(id = "build-history")] when external tools or saved state need a
stable value. Explicit IDs must be nonempty and contain only lowercase ASCII
letters, digits, _, or -.
Add a row context-menu link
The example marks internal_id as the context-menu value and substitutes it
for {id} in the route. context_menu_route requires either one field marked
context_menu_id or the equivalent
context_menu_row_id = "internal_id" struct option. Use
context_menu_route_fn and context_menu_label_fn when routing or
localization is owned by helper functions. Add custom_context_menu and
implement TableRowContextMenu only when generated and application-owned menu
items must be composed.
Order rows and calculated keys
Use one SortOrder for table controls, saved preferences, and query handlers.
Clauses are evaluated in priority order. Each clause names a stable column key,
its direction, and null placement; null placement is independent of direction.
Declare sortable columns and row identity
use gpui_table::GpuiTable;
#[derive(Clone, GpuiTable)]
#[gpui_table(row_id = "id")]
struct Record {
#[gpui_table(skip)]
id: u64,
#[gpui_table(sortable, col = "category_key")]
category: String,
#[gpui_table(sortable)]
score: Option<i64>,
}
row_id names a unique, stable field. It supplies ascending tie-breaking and
lets selection follow records across sorting and refreshes. The generated
column enum’s key() returns the public key, including a col override.
Registry metadata keeps field_name for Rust access and key for ordering.
When row_id is omitted, ties retain source order and the delegate uses source
positions for selection identity. Use explicit IDs when replacing, inserting,
or removing source rows. ascending and descending declare initial clauses
in field order and also enable sorting for those columns.
Apply ordered clauses
use gpui_table::sort::{NullPlacement, SortClause, SortDirection, SortOrder};
let ordering = SortOrder::new(vec![
SortClause::new("category_key", SortDirection::Ascending),
SortClause::new("score", SortDirection::Descending)
.with_nulls(NullPlacement::Last),
])?;
Ok::<(), gpui_table::sort::SortError>(())
Call gpui_table::runtime::set_table_ordering(table, ordering, cx) inside a
TableState update to retain row or cell selection. A standalone delegate
supports set_ordering(ordering) and ordering().
The delegate orders its loaded rows and keeps rows in source order.
visible_row_indices() is the ordered, filtered source-index view. For remote
pagination, send the same order to the backend and execute it before selecting
pages. Sorting a partial loaded buffer does not order the complete result.
SortOrder serializes as an array of clauses. Deserialization rejects duplicate
keys, unknown clause fields, invalid directions/null policies and more than 32
clauses. Row validation also rejects unknown or unsortable column keys, even
for an empty result. Comparison errors leave a requested order unapplied.
Share calculated keys with cell presentation
Declare #[gpui_table(sortable, sort_key = score_key, style = score_cell)].
The key function accepts &Record and returns either Option<Key> or
Result<Option<Key>, SortError>, where Key: PartialOrd. Use that same function
from the cell renderer so the displayed calculation and its ordering agree.
Keep display formatting separate from the comparable typed value.
Null results use the clause’s null policy. Failed calculations and unordered
values such as NaN produce SortError; they are not silently converted to ties.
The row owner defines expression vocabulary, units, evaluation limits and
backend translation. The table API accepts typed keys without imposing a
formula language or report engine.
After an in-place row change, call refresh_filtered_rows() to recompute the
ordered view. Check sort_error() if changed inputs can fail. A refresh failure
exposes the error and the filtered source order until the owner repairs the
input or changes the ordering. Capture TableRowSelection::capture(table)
before replacing or editing source rows, refresh, then call
selection.restore(table, cx) to retain selection by ID; removed records clear
selection.
The ordered_sort example uses real SpacetimeDB Timestamp and TimeDuration
values, a calculated key shared with a cell renderer, and an MCP query. Enable
spacetimedb, mcp, and rust_decimal to run it. Duration cells use the SDK’s
Display representation, while comparisons use the typed duration.
Compose sort controls
gpui-table-component::SortEditor takes a caller-owned SortOrder,
SortColumnOption values with localized titles, and an on_change callback.
It provides key selection, direction/null policy, priority changes and removal.
The owner applies each requested value and notifies its view. Programmatic
controlled updates do not emit a user-change callback.
Use a stable editor ID. Clause controls use stable column keys, so changing
priority retains their identity. disabled(true) prevents editing. Place the
component in the existing toolbar, panel or sheet; it owns no query, dialog,
persistence or authorization. Initialize the component’s i18n as for filters.
Declare source capabilities
Call delegate.set_allowed_sort_columns(["category_key", "score"]) before
presenting a generated delegate when the source supports a subset of its sortable
keys. Excluded headers become unsortable and direct order changes reject excluded
keys. An empty list disables ordering. Unknown keys, duplicate keys, and a
restriction excluding the current order fail atomically.
Resolve application-owned columns
Use sort::ResolvedSortColumn::new(key, extract) for a source-resolved key.
The extractor returns Result<Option<Key>, SortError> with Key: PartialOrd.
Keep the same extractor available to the owning cell renderer. The application
resolves the definition, source readiness, units and permissions before supplying
this context.
use gpui_table::sort::{ResolvedSortColumn, ResolvedSortColumns, SortError};
use gpui_table::GpuiTable;
#[derive(Clone, GpuiTable)]
#[gpui_table(row_id = "id")]
struct Record {
#[gpui_table(skip)]
id: u64,
#[gpui_table(sortable, col = "category_key")]
category: String,
score: Option<i64>,
}
fn scaled_score(row: &Record) -> Result<Option<i64>, SortError> {
row.score.map(|score| score.checked_mul(2).ok_or_else(|| SortError::Calculation {
column: "scaled_score".into(),
message: "overflow".into(),
})).transpose()
}
let columns = ResolvedSortColumns::new([
ResolvedSortColumn::new("scaled_score", scaled_score)?,
])?;
let mut delegate = RecordTableDelegate::new(Vec::new());
delegate.set_resolved_sort_columns(columns)?;
delegate.set_allowed_sort_columns(["category_key", "scaled_score"])?;
Ok::<(), SortError>(())
Resolved keys are distinct from native sortable keys and from each other. The retained
context validates empty sources, preflights single-row errors and compares only
included rows. Native and resolved clauses share null placement, direction,
identity tie-breaking and atomic error handling. ResolvedSortColumns also
provides complete-source sorted_indices, sort_indices and sort_rows for
application query owners.
Use runtime::set_table_resolved_sort_columns(table, columns, cx) for a generated
table state. It preserves selection by stable row identity. Context replacement
checks the current order, source capability restriction and visible values before
applying the change. Clear an order and its capability restriction before retiring
keys that it uses. Remote query owners execute the same resolved calculation over
the complete source before pagination.
Attach runtime::ResolvedTableColumn<Record> to display a resolved key. Pass a
gpui_kit::component::table::Column with that key and a renderer reading the
current &Record. Use the same calculation as the comparison extractor and
keep formatting separate. runtime::set_table_resolved_columns replaces these
presentation columns while following selected column keys; removing a selected
cell’s column leaves its row selected, and removing a selected column clears it.
Remove presentation before retiring its executable key.
For temporary filtering or pagination, clone TableRowSelection::capture(table)
before changing the source. row_id() identifies the retained record. Restoring
while it is absent clears the visible selection; retain another clone and
restore it once the record returns. Table-wired client filters preserve visible
record selection and clear it when the selected record is filtered out.
Snapshots retain column positions; use set_table_resolved_columns to follow
column keys during a presentation change. Restoring a snapshot whose column no
longer exists selects its row for a cell snapshot or clears a column snapshot.
Typed filters
Generated filters keep filter values typed and apply them to the table’s
in-memory rows. Enable the facade’s rust_decimal feature before using any
numeric range filter, including one over an integer field:
This example follows the development branch. Use a sibling gpui-table
checkout and GPUI Kit 0.11:
[dependencies]
gpui-kit = "0.11.0"
jiff = "1.0"
gpui-table = { path = "../gpui-table/crates/gpui-table", features = ["rust_decimal"] }
gpui-table-component = { path = "../gpui-table/crates/gpui-table-component", features = ["rust_decimal"] }
Add #[gpui_table(filters)] and declare each filtered field’s shape:
#[derive(Clone, gpui_table::GpuiTable)]
#[gpui_table(filters)]
struct Order {
#[gpui_table(filter(gpui_table_component::TextFilter))]
customer: String,
#[gpui_table(filter(gpui_table_component::NumberRangeFilter))]
total: u32,
#[gpui_table(filter(gpui_table_component::DateRangeFilter))]
placed_at: jiff::Timestamp,
}
Built-in shapes cover text, faceted, numeric range, and date range filters.
Civil and zoned datetimes keep their own date for matching. A bare Jiff
Timestamp or SpacetimeDB timestamp matches by UTC date. See
Date and time cells for how cells display those
values separately.
Configured expressions such as TextFilter.alphanumeric_only() and
FacetedFilter::<T>.searchable(true) customize generated widget construction.
NumberRangeFilter.range(...).step(...) accepts
rust_decimal::Decimal bounds and steps.
Wire and render generated filters
Build filter entities against the same table state that renders the
DataTable. Each widget change snapshots the generated values, updates the
delegate, and notifies the table:
let filters = OrderFilterEntities::build_for_table(table.clone(), cx);
let filter_elements = filters
.filter_sidebar_data(cx)
.into_groups()
.into_iter()
.flat_map(|group| group.into_items())
.map(|item| item.into_element())
.collect::<Vec<_>>();
The sidebar data groups nonempty filters in Text, Faceted, Number Range, and Date Range order. Each item also carries its stable field ID, label, filter type, and active state for custom application shells.
For loader-backed tables, use
OrderFilterEntities::build_for_table_loader(table, window, cx). It clears
rows, resets eof, stores the new filter values, and calls load_data on the
initial build and after each filter change.
Control and save filter state
Generated delegate state can add an application-owned scope to the generated filter values:
delegate.set_filter_values(values);
delegate.clear_filter_values();
delegate.set_row_scope(|row| row.total > 0);
delegate.clear_row_scope();
Save and restore a complete widget snapshot through the generated values type:
let preset = filters.read_values(cx).to_preset_json();
let values = OrderFilterValues::from_preset_json(&preset)?;
filters.apply_values(values, window, cx);
filters.active_filter_count(cx) supports badges,
filters.reset_filters(window, cx) resets all widgets with one change
notification, and filters.reset_button() creates a bound reset control.
If a field-level filter produces a derive error, first confirm that the struct
has filters, the shape supports the field type, and the facade feature named
by the diagnostic is enabled.
Filter components and custom shapes
Use a built-in shape for supported strings, facets, numeric ranges, and date ranges. Adapter shapes let domain value types reuse those widgets. Implement a new runtime shape when the widget or matching semantics need to change.
| Need | Use |
|---|---|
| A standard filter on a supported field | TextFilter, FacetedFilter<T>, NumberRangeFilter, or DateRangeFilter |
| A standard widget over an application value object | TextFilterAdapter, NumberRangeFilterAdapter, or DateRangeFilterAdapter |
| A different raw value over an existing shape | #[derive(GpuiTableFilterShape)] |
| A new widget or matching model | Implement the runtime shape contracts |
Use a filter component directly
Construct components directly when the application owns a manual filter
collection rather than generated FilterEntities. Initialize table
component localization before rendering them.
use gpui_kit::{StyleRefinement, px};
use gpui_table_component::{TextFilter, TextFilterExt};
let filter = TextFilter::new(
"Name",
String::new(),
move |value, _window, _cx| {
update_query(value);
},
cx,
)
.alphanumeric_only(cx)
.container_style(StyleRefinement::default().w_full(), cx)
.input_style(StyleRefinement::default().w(px(280.)), cx);
TableStatusBar::new(row_count, loading, eof) provides the matching
row-count and loading indicator. ResetFilters is available for
manual collections; generated filter collections provide their own
reset_filters(window, cx) method.
Adapt an application value type
Use a built-in adapter when a domain wrapper should keep the built-in widget, raw value, preset behavior, and MCP schema. Implement the matching field trait:
#[derive(Clone, gpui_table::TableCell)]
struct AccountCode(String);
impl gpui_table_component::TextFilterField for AccountCode {
fn to_filter_text(&self) -> String {
self.0.clone()
}
}
#[derive(Clone, gpui_table::GpuiTable)]
#[gpui_table(filters)]
struct Account {
#[gpui_table(filter(gpui_table_component::TextFilterAdapter))]
code: AccountCode,
}
TextFilterAdapter supports T and
Option<T> when T: TextFilterField. The number and date
adapters follow the same pattern with NumberRangeFilterField and
DateRangeFilterField, subject to their feature flags. On the development
branch a date adapter returns a jiff::civil::Date from to_filter_date.
Adapt an existing shape
Derive GpuiTableFilterShape when the base widget and matching
behavior are correct but its component-facing value needs conversion:
#[derive(Clone, Debug, Default, PartialEq)]
struct PrefixText(String);
#[derive(gpui_table::GpuiTableFilterShape)]
#[gpui_table_filter_shape(
base = gpui_table_component::TextFilter,
raw_value = PrefixText,
field = String,
into_base = |value: PrefixText| value.0,
from_base = PrefixText
)]
struct PrefixTextFilter;
The generated shape delegates UI construction, matching, reset, and preset
application to the base shape. Use fields(A, B, ...) instead of
field = A when the adapter supports several field types. Use
koruma_newtype when a Koruma newtype should filter and validate its
inner value.
For MCP tables, the adapted raw value must implement
gpui_table::mcp::McpToolValue for the derive to provide the default
MCP decoder and schema.
Implement a new shape
A fully custom filter connects a component to generated table state through:
ComponentShapeMetadataandDeclaredComponentShapeGpuiTableFilterShapeandDeclaredGpuiTableFilterShapeComponentShapeFor<Field>andGpuiTableFilterShapeFor<Field>for each supported field type
The runtime shape defines its component, raw value, typed filter value, semantic filter category, construction, value reading, wrapping, reset, and field matching. Inactive filter values must match every row.
Generated saved presets require the typed filter value to implement
gpui_table::FilterPresetValue. Override unwrap_value and set_silent so
applying a preset restores the value without firing each component callback.
The default unwrap_value panics; the default set_silent resets the component.
For MCP tables, derive gpui_table::McpFilterShape when the raw value
implements McpToolValue, or implement McpFilterShape
directly for a custom schema or decoder. Add
McpFilterShapeValidation when field-level Koruma validation must be
supported.
Loading and custom cells
#[gpui_table(load_more)] lets DataTable request more rows as the viewport
approaches the end. The application implements the fetch and must keep the
generated delegate’s loading and eof flags accurate.
Implement load-more behavior
use gpui_kit::{Context, Window};
use gpui_kit::component::table::TableState;
use gpui_table::runtime::TableLoader;
#[derive(Clone, gpui_table::GpuiTable)]
#[gpui_table(load_more)]
struct EventRow {
message: String,
}
#[gpui_table::gpui_table_impl]
impl TableLoader for EventRowTableDelegate {
const THRESHOLD: usize = 20;
fn load_more(
&mut self,
_window: &mut Window,
cx: &mut Context<TableState<Self>>,
) {
if self.loading || self.eof {
return;
}
self.loading = true;
// Start the application request. When it completes, append rows,
// clear loading, set eof if no more pages exist, and notify again.
cx.notify();
}
}
THRESHOLD defaults to 10. The guard prevents duplicate requests while a
load is active and stops requests after the backend reaches the end.
Trigger the initial request after constructing TableState:
table.update(cx, |table, cx| {
use gpui_table::runtime::TableDataLoader as _;
table.delegate_mut().load_data(window, cx);
});
When generated filters should reload backend data, build them with
<Row>FilterEntities::build_for_table_loader(...) instead. That method also
performs the initial load and resets rows and eof before a filter-driven
reload.
TableStatusBar::new(delegate.rows.len(), delegate.loading, delegate.eof)
provides a matching row-count and loading indicator.
Render a custom cell
Use field-level style = path::to_fn when one column needs a custom GPUI
element:
#[gpui_table(width = 120., style = render_duration)]
duration_ms: u64,
fn render_duration(
_row: &EventRow,
value: &u64,
_window: &mut gpui_kit::Window,
_cx: &mut gpui_kit::App,
) -> impl gpui_kit::IntoElement {
use gpui_kit::{ParentElement as _, Styled as _};
gpui_kit::div().px_2().child(format!("{value} ms"))
}
The style function receives the full row, the field value, and the active GPUI contexts. Keep renderer-specific presentation in this hook while the generated delegate continues to own sorting, filtering, and row access.
If loading repeatedly fires without adding rows, confirm that loading is set
before starting asynchronous work and remains true until the completion update.
If it never fires again after a request, confirm that completion clears
loading; set eof only when no later page exists.
Localization
The fluent feature lets generated table titles, column labels, and facet
labels use the application’s typed es-fluent resources. The application must
own and link those resources; gpui-table-component only supplies resources
for its built-in controls.
This example follows the development branch. Use a sibling gpui-table
checkout and GPUI Kit 0.11:
[dependencies]
gpui-kit = "0.11.0"
gpui-table = { path = "../gpui-table/crates/gpui-table", features = ["fluent"] }
gpui-table-component = { path = "../gpui-table/crates/gpui-table-component" }
es-fluent = "0.22.0"
Derive localized labels
Derive message metadata on the row and faceted value types:
use es_fluent::{EsFluentLabel, EsFluentVariants};
use gpui_table::{Filterable, GpuiTable, TableCell};
#[derive(
Clone,
Eq,
Hash,
PartialEq,
es_fluent::EsFluent,
Filterable,
TableCell,
)]
#[filter(fluent)]
enum Status {
Active,
Suspended,
}
#[derive(Clone, EsFluentLabel, EsFluentVariants, GpuiTable)]
#[fluent_variants(keys = ["label"])]
#[gpui_table(fluent = "label", filters)]
struct User {
#[gpui_table(filter(gpui_table_component::FacetedFilter::<Status>))]
status: Status,
}
#[gpui_table(fluent = "label")] selects the label key generated by
EsFluentVariants. Keep those row and facet messages in the same application
localization module as the rest of the GPUI interface.
Initialize and select the locale
After gpui_kit::component::init(cx), initialize table localization from the active
component locale:
gpui_table_component::i18n::init(cx)?;
To change locales later, synchronize the built-in component and table-core contexts together:
gpui_table_component::i18n::set_locale(cx, "en")?;
An application with its own embedded resource manager must apply the same
resolved language to that manager before rendering typed row labels. The
canonical
some-lib locale adapter
shows one complete resource-linking and synchronization path.
Initialization and locale selection return typed errors. Ordinary typed label and message rendering treats a missing localization global or missing resource as a hard failure, so perform locale setup before constructing or rendering generated filters.
MCP query tools
The experimental mcp feature exposes application-owned rows through
typed MCP query tools. Generated code validates and decodes filter, ordering and
pagination arguments; the application still owns data access, authorization,
filter execution, and totals.
This example follows the development branch. Use a sibling gpui-table
checkout and GPUI Kit 0.11:
[dependencies]
gpui-kit = "0.11.0"
gpui-table = { path = "../gpui-table/crates/gpui-table", features = ["mcp"] }
gpui-table-component = { path = "../gpui-table/crates/gpui-table-component", features = ["mcp"] }
serde = { version = "1", features = ["derive"] }
Enable gpui-table-component/mcp when a table uses the built-in
filter shapes. Match the facade and component rust_decimal,
jiff, or spacetimedb features required by those
shapes.
Register a local row source
Opt the row into MCP metadata, register a row source, and serve the inventory-backed tools over stdio:
#[derive(
Clone,
gpui_table::GpuiTable,
gpui_table::mcp::McpJsonSchema,
serde::Serialize,
)]
#[gpui_table(mcp(row_schema))]
struct User {
#[gpui_table(filter(gpui_table_component::TextFilter))]
name: String,
}
#[gpui_table::mcp_query]
fn rows() -> Vec<User> {
load_users()
}
fn main() -> gpui_table::mcp::ServeStdioResult {
gpui_table::mcp::serve_stdio_blocking()
}
#[gpui_table(mcp)] is sufficient for an MCP-only filtered table;
it does not also need struct-level filters. A zero-argument
Vec<Row> or Result<Vec<Row>, E> handler is called for
each query. The generated tool accepts the declared filter field names plus
optional sort, limit and offset.
Rows must implement serde::Serialize. The row_schema
option additionally requires McpJsonSchema and publishes the
precise row object beneath rows.items. Without that option, row
items remain unconstrained in the output schema.
Use an application backend
A handler whose first argument is TableQuery<Row> receives decoded
arguments for backend-owned execution:
#[gpui_table::mcp_query]
async fn rows(
query: gpui_table::mcp::TableQuery<User>,
) -> Result<gpui_table::mcp::TableQueryResult<User>, QueryError> {
let (rows, total) = query_users(&query).await?;
Ok(query.result(rows, total))
}
The backend must apply the decoded query and return the total number of matching
rows with the requested page. Use query.filter_rows(rows) instead
when the application supplies an in-memory collection and wants generated
filtering, ordering, offset and limit. This returns
Result<TableQueryResult<Row>, SortError>. The backend must execute
query.ordering over all matches before pagination and use a cursor consistent
with that order. See Order rows and calculated keys.
Describe the tool
Set generated tool metadata on the row:
#[gpui_table(mcp(
row_schema,
name = "query_users",
title = "Query users",
description = "Query users visible to the current application.",
read_only = true,
destructive = false,
idempotent = true,
open_world = false
))]
struct User {
// fields
}
When description is omitted, the row type’s Rust doc comment is
used. Generated query tools default to read-only, non-destructive, and
idempotent annotations. read_only = true and
destructive = true cannot be combined.
Faceted arguments are unique sets of
Filterable::to_filter_string() values. Their schemas include the
valid strings and display labels. Range arguments use
{ "min": ..., "max": ... } objects.
Field-level #[koruma(...)] validators on filtered fields run after
decoding and before the handler. Add koruma and the crate that owns
the selected validator to the application dependencies. For a filter over a
Koruma newtype’s inner value, use a shape derived with
koruma_newtype; see
Filter components and custom shapes.
Compose a server
gpui_table::mcp::server()? registers inventory-discovered table
handlers with default package metadata. Use
server_named(name, version)? for application-owned metadata, or the
builder helpers when setup is deferred.
Use the shared McpServer builder to combine table query tools with
other component-shape integrations:
let server = gpui_table::mcp::McpServer::builder(
"my-app",
env!("CARGO_PKG_VERSION"),
)
.register(gpui_table::mcp::register)
.register(gpui_form::mcp::register)
.build()?;
Manual table registration supports backend handlers, fixed rows, synchronous row
sources, and asynchronous row sources through
table::<Row>(&mut server).
Use gpui_table::mcp::tool_registry()? when a host assembles the
inventory-discovered MCP definitions and handlers independently from the
server. The MCP server continues serving its registry until EOF, cancellation,
or another application-owned shutdown signal.
Every registered table publishes descriptor and schema resources:
gpui-table://tables/{tool_name}/descriptorgpui-table://tables/{tool_name}/schema
Use register_inventory_table_resources when a composed server
should publish inventory-discovered resources without registering their query
handlers. Query prompt templates are opt-in through
register_prompt_templates for inventory tables or
register_table_prompt_templates::<Row> for one table.
Verify the tool
In a repository checkout, run:
cargo run -p mcp-query
The example exposes mcp_query_issues and returns rows,
total, offset, and limit. If registration
fails, check for duplicate tool names. If a built-in filter shape fails its MCP
trait bound, enable the component crate’s mcp feature in addition
to the facade feature.
Send ordered clauses
{
"sort": [
{ "column": "category_key", "direction": "ascending" },
{ "column": "score", "direction": "descending", "nulls": "last" }
],
"offset": 20,
"limit": 10
}
The schema enumerates sortable column keys. Unknown, unsortable, duplicate or malformed clauses fail before the query handler runs. An empty order retains source order. Local row sources filter, sort all matches, then page; custom backends receive the same validated order and own its execution. Query a calculated key only when that backend implements its declared semantics.
Construct manual queries with TableQuery::new(filters, limit, offset) and
with_ordering(ordering). Manual MCP row implementations also implement the
UI-neutral SortableRow contract and publish their sortable keys on the
descriptor with with_sort_columns(...).
Features and integration crates
Start with the gpui-table facade and enable only the contracts required by
the row types.
| Facade feature | Default | Use it for |
|---|---|---|
derive | Yes | GpuiTable, Filterable, TableCell, GpuiTableFilterShape, and gpui_table_impl |
jiff | Yes | Jiff cells and date-range filter support |
rust_decimal | No | Numeric range filters, including filters over integer fields |
fluent | No | Typed localized table and facet labels |
spacetimedb | No | Supported SpacetimeDB temporal range filtering |
inventory | No | GpuiTableShape registration for tooling and code generation |
mcp | No | Experimental generated MCP query tools; this also enables inventory |
Use gpui-table-component for rendered filters, TableStatusBar, reset
controls, and manual filter composition. Its jiff and rust_decimal
features are enabled by default. Enable its mcp feature when an MCP-enabled
row declares a built-in filter shape.
Choose an integration crate
Use the lower-level crates for reusable integrations and tooling:
| Crate | Use it when |
|---|---|
gpui-table-core | Typed filter semantics must run without GPUI |
gpui-table-runtime | Generic code targets row, loader, cell, or generated-filter runtime traits |
gpui-table-schema | UI-neutral table registry metadata is consumed by tooling |
gpui-table-derive | Proc macros must be integrated without the facade |
gpui-table-mcp | A custom MCP server or lower-level query registry is required |
gpui-table-prototyping-core | Inventory metadata drives story or scaffold generation |
Filter-shape feature errors identify the field and missing facade capability.
Match the facade feature first, then match the corresponding component feature
when the shape is implemented by gpui-table-component.
Generate table stories from metadata
Use gpui-table-schema and gpui-table-prototyping-core when a tool needs
Rust scaffolding for registered row types. Enable the facade’s inventory
feature on the row-model crate and link that crate into the generator so its
GpuiTableShape registrations are available.
The reference generator
implements TableLayout to assemble TableParts into a Storybook view. It
passes each registered shape to TableShapeAdapter::new(shape, true) and
calls try_generate_file(&layout). Use try_parts() instead when the tool
needs individual fragments for its own template. Handle TableCodegenError
for invalid identifiers, source paths, or imports instead of using the
panicking convenience methods.
From a repository checkout with the example’s dependencies available, run:
cargo run -p prototyping --locked
This replaces generated Rust stories in examples/prototyping/output and
writes their module index. Preserve any manual work before running it; make
lasting changes in the row metadata or StorybookLayout, then regenerate.
Successful output names each generated file and ends with
Table story generation complete. Compile the application that consumes the
generated files to check their imports and feature requirements; generating a
syntax tree alone does not prove that its referenced types are available.