gpuicn
Theme

Theme the previews

Every preview on the site is live GPUI and follows these.

Base
Accent
Radius
gpuicn theme set --base-color neutral --radius 0.625rem

Data display

Item

Rows with media, a title, a description and actions, grouped into cards.

Added in 0.10.1 578 lines of Rust

Gallery

Starting the preview. GPUI compiles to WebAssembly, so the first load takes a few seconds. This browser has neither WebGPU nor WebGL 2, so the live preview cannot run. The code on this page still works. The preview did not start.

Installation

After the one-time setup, run the command from your app root. The CLI writes the modules and keeps src/ui/mod.rs in step.

gpuicn add item

If you prefer to copy the files by hand, declare them yourself:

// src/ui/mod.rs
pub mod theme;
pub mod item;

// src/main.rs
mod ui;

Usage

Put this in a view module and return example() from its render method.

use crate::ui::item::*;
use gpui_kit::{IntoElement, ParentElement as _, div};

fn example() -> impl IntoElement {
    ItemGroup::new("startup")
        .child(
            Item::new("open-at-login")
                .title("Open at login")
                .description("Start Matty when you sign in to this computer")
                .actions(div().child("Switch")),
        )
        .child(
            Item::new("download-folder")
                .title("Download folder")
                .description("~/Downloads")
                .actions(div().child("Change…")),
        )
}

Examples

Variants

Plain, outlined and muted rows.

Starting the preview. GPUI compiles to WebAssembly, so the first load takes a few seconds. This browser has neither WebGPU nor WebGL 2, so the live preview cannot run. The code on this page still works. The preview did not start.

With an action

Media goes before the text and actions after it.

Starting the preview. GPUI compiles to WebAssembly, so the first load takes a few seconds. This browser has neither WebGPU nor WebGL 2, so the live preview cannot run. The code on this page still works. The preview did not start.

API reference

pub fn new(id: impl Into<ElementId>) -> Self

Creates an empty row with a caller-owned ID, unique among its siblings.

pub fn variant(mut self, variant: ItemVariant) -> Self

Chooses the row's surface.

pub fn size(mut self, size: ItemSize) -> Self

Chooses the row's density.

pub fn media(mut self, media: impl IntoElement) -> Self

Sets the leading icon, avatar or image.

pub fn title(mut self, title: impl Into<SharedString>) -> Self

Sets the row's title, which is also its accessible name.

pub fn description(mut self, description: impl Into<SharedString>) -> Self

Sets the muted line under the title, clamped to two lines.

pub fn actions(mut self, actions: impl IntoElement) -> Self

Sets the controls at the trailing edge, such as a switch or a button.

pub fn stacked(mut self, stacked: bool) -> Self

Puts the actions under the title and description at full width, for wide controls such as a tag field or a row of swatches.

pub fn disabled(mut self, disabled: bool) -> Self

Disables a clickable row and applies the disabled appearance.

pub fn on_click(
        mut self,
        handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
    ) -> Self

Makes the whole row a button that runs `handler`, for rows that open something. A clickable row should not also hold actions.

pub fn new(id: impl Into<ElementId>) -> Self

Creates an empty group with a caller-owned ID.

pub fn variant(mut self, variant: ItemVariant) -> Self

Chooses the group's surface; [`ItemVariant::Outline`] by default.

pub fn new() -> Self

Creates a separator.

pub fn new(id: impl Into<ElementId>, group: impl Into<SharedString>) -> Self

Creates a reveal that shows while the element marked `.group(group)` is hovered. The ID keys its focus tracking; keep it stable.

pub fn focus_within(mut self, handle: &gpui_kit::FocusHandle) -> Self

Also shows the children while focus is on or inside the element that tracks `handle`, so a keyboard user on the row sees its actions.

Installed source, 578 lines
//! Nova item rows: a title, an optional description, media and actions, laid
//! out in a row and grouped into a card with hairline separators. A port of
//! shadcn/ui's `Item` and `ItemGroup`, for settings pages and lists.

use gpui_kit::base::Button as BaseButton;
use gpui_kit::{
    AnyElement, App, ClickEvent, ElementId, FontWeight, InteractiveElement as _, IntoElement,
    ParentElement, RenderOnce, Role, SharedString, StatefulInteractiveElement as _, Styled, Window,
    div, prelude::FluentBuilder as _, px,
};
use std::rc::Rc;

use super::theme::{
    UiTheme, apply_style,
    locale::DirectionalStyled as _,
    primitives::{disabled, text},
};

type Handler = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App)>;

/// The surface an [`Item`] or [`ItemGroup`] draws.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ItemVariant {
    /// No border or background; rows sit on the page.
    #[default]
    Default,
    /// A bordered card with large corners.
    Outline,
    /// A muted background without a border.
    Muted,
}

/// The density of an [`Item`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ItemSize {
    /// At least 48px tall with 10px by 16px padding.
    #[default]
    Default,
    /// At least 36px tall with 6px by 12px padding.
    Sm,
}

/// One row: media, a title with an optional description, and actions at the
/// trailing edge (or under the copy when [`Item::stacked`]).
#[derive(IntoElement)]
pub struct Item {
    id: ElementId,
    style: gpui_kit::StyleRefinement,
    variant: ItemVariant,
    size: ItemSize,
    media: Option<AnyElement>,
    title: Option<SharedString>,
    description: Option<SharedString>,
    actions: Option<AnyElement>,
    children: Vec<AnyElement>,
    stacked: bool,
    disabled: bool,
    on_click: Option<Handler>,
}

impl Item {
    /// Creates an empty row with a caller-owned ID, unique among its siblings.
    pub fn new(id: impl Into<ElementId>) -> Self {
        Self {
            id: id.into(),
            style: Default::default(),
            variant: ItemVariant::Default,
            size: ItemSize::Default,
            media: None,
            title: None,
            description: None,
            actions: None,
            children: Vec::new(),
            stacked: false,
            disabled: false,
            on_click: None,
        }
    }

    /// Chooses the row's surface.
    pub fn variant(mut self, variant: ItemVariant) -> Self {
        self.variant = variant;
        self
    }

    /// Chooses the row's density.
    pub fn size(mut self, size: ItemSize) -> Self {
        self.size = size;
        self
    }

    /// Sets the leading icon, avatar or image.
    pub fn media(mut self, media: impl IntoElement) -> Self {
        self.media = Some(media.into_any_element());
        self
    }

    /// Sets the row's title, which is also its accessible name.
    pub fn title(mut self, title: impl Into<SharedString>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Sets the muted line under the title, clamped to two lines.
    pub fn description(mut self, description: impl Into<SharedString>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Sets the controls at the trailing edge, such as a switch or a button.
    pub fn actions(mut self, actions: impl IntoElement) -> Self {
        self.actions = Some(actions.into_any_element());
        self
    }

    /// Puts the actions under the title and description at full width, for
    /// wide controls such as a tag field or a row of swatches.
    pub fn stacked(mut self, stacked: bool) -> Self {
        self.stacked = stacked;
        self
    }

    /// Disables a clickable row and applies the disabled appearance.
    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    /// Makes the whole row a button that runs `handler`, for rows that open
    /// something. A clickable row should not also hold actions.
    pub fn on_click(
        mut self,
        handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_click = Some(Rc::new(handler));
        self
    }
}

impl ParentElement for Item {
    /// Adds content under the description, inside the copy column.
    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
        self.children.extend(elements);
    }
}

impl Styled for Item {
    fn style(&mut self) -> &mut gpui_kit::StyleRefinement {
        &mut self.style
    }
}

fn surface<T: Styled>(element: T, variant: ItemVariant, theme: &UiTheme) -> T {
    match variant {
        ItemVariant::Default => element,
        ItemVariant::Outline => element
            .border_1()
            .border_color(theme.colors.border)
            .rounded(theme.radius.lg)
            .bg(theme.colors.card),
        ItemVariant::Muted => element.rounded(theme.radius.lg).bg(theme.colors.muted),
    }
}

impl Item {
    fn lay_out<T: Styled + ParentElement + gpui_kit::prelude::FluentBuilder>(
        self,
        element: T,
        theme: &UiTheme,
    ) -> T {
        let (min_h, px_, py) = match self.size {
            ItemSize::Default => (48., 16., 10.),
            ItemSize::Sm => (36., 12., 6.),
        };
        let copy = div()
            .flex_1()
            .min_w_0()
            .flex()
            .flex_col()
            .gap(px(2.))
            .when_some(self.title, |copy, title| {
                copy.child(
                    text::control(div(), theme, theme.text(13.5))
                        .debug_selector(|| "item-title".into())
                        .font_weight(FontWeight::NORMAL)
                        .text_color(theme.colors.foreground)
                        .child(title),
                )
            })
            .when_some(self.description, |copy, description| {
                copy.child(
                    text::control(div(), theme, theme.text(12.))
                        .debug_selector(|| "item-description".into())
                        .text_color(theme.colors.muted_foreground)
                        .line_clamp(2)
                        .child(description),
                )
            })
            .children(self.children);
        let head = div()
            .flex_row_in(theme.direction)
            .items_center()
            .gap(theme.space(3.))
            .min_w_0()
            .w_full()
            .when_some(self.media, |head, media| {
                head.child(div().flex_shrink_0().flex().items_center().child(media))
            })
            .child(copy);
        let element = surface(element, self.variant, theme)
            .w_full()
            .min_h(px(min_h))
            .px(px(px_))
            .py(px(py))
            .font_family(theme.fonts.body.clone())
            .text_color(theme.colors.foreground);
        let actions = self.actions.map(|actions| {
            div()
                .flex_shrink_0()
                .flex()
                .items_center()
                .gap(theme.space(2.))
                .child(actions)
        });
        if self.stacked {
            element
                .flex()
                .flex_col()
                .gap(theme.space(2.5))
                .child(head)
                .when_some(actions, |el, actions| el.child(actions.w_full()))
        } else {
            element
                .flex_row_in(theme.direction)
                .items_center()
                .gap(theme.space(4.))
                .child(head.flex_1())
                .when_some(actions, |el, actions| el.child(actions))
        }
    }
}

impl RenderOnce for Item {
    fn render(mut self, _: &mut Window, cx: &mut App) -> impl IntoElement {
        let theme = UiTheme::read(cx).clone();
        let style = std::mem::take(&mut self.style);
        let label = self.title.clone().unwrap_or_default();
        match self.on_click.take() {
            Some(handler) => {
                let disabled = self.disabled;
                let accent = theme.colors.accent;
                let ring = theme.colors.ring;
                let button = BaseButton::new(self.id.clone())
                    .accessibility_label(label)
                    .disabled(disabled)
                    .when(!disabled, |el| {
                        el.cursor_pointer()
                            .hover(move |style| style.bg(accent))
                            .focus_visible(move |style| style.border_color(ring))
                    })
                    .map(|el| disabled::dim(el, disabled))
                    .border_1()
                    .border_color(theme.colors.border.opacity(0.))
                    .rounded(theme.radius.lg)
                    .on_click(move |event, window, cx| handler(event, window, cx));
                apply_style(self.lay_out(button, &theme), &style).into_any_element()
            }
            None => {
                let root = div()
                    .id(self.id.clone())
                    .role(Role::Group)
                    .when(!label.is_empty(), |el| el.aria_label(label));
                apply_style(self.lay_out(root, &theme), &style).into_any_element()
            }
        }
    }
}

/// A column of [`Item`]s with hairline separators between them. In the
/// [`ItemVariant::Outline`] variant it is one bordered card, the way settings
/// pages group rows.
#[derive(IntoElement)]
pub struct ItemGroup {
    id: ElementId,
    style: gpui_kit::StyleRefinement,
    variant: ItemVariant,
    children: Vec<AnyElement>,
}

impl ItemGroup {
    /// Creates an empty group with a caller-owned ID.
    pub fn new(id: impl Into<ElementId>) -> Self {
        Self {
            id: id.into(),
            style: Default::default(),
            variant: ItemVariant::Outline,
            children: Vec::new(),
        }
    }

    /// Chooses the group's surface; [`ItemVariant::Outline`] by default.
    pub fn variant(mut self, variant: ItemVariant) -> Self {
        self.variant = variant;
        self
    }
}

impl ParentElement for ItemGroup {
    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
        self.children.extend(elements);
    }
}

impl Styled for ItemGroup {
    fn style(&mut self) -> &mut gpui_kit::StyleRefinement {
        &mut self.style
    }
}

impl RenderOnce for ItemGroup {
    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
        let theme = UiTheme::read(cx);
        let mut root = surface(
            div()
                .id(self.id)
                .role(Role::List)
                .flex()
                .flex_col()
                .w_full(),
            self.variant,
            theme,
        )
        .overflow_hidden();
        for (index, child) in self.children.into_iter().enumerate() {
            if index > 0 {
                root = root.child(ItemSeparator::new());
            }
            root = root.child(child);
        }
        apply_style(root, &self.style)
    }
}

/// A one-pixel rule between items, inset to the group's edges.
#[derive(IntoElement, Default)]
pub struct ItemSeparator;

impl ItemSeparator {
    /// Creates a separator.
    pub fn new() -> Self {
        Self
    }
}

impl RenderOnce for ItemSeparator {
    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
        let theme = UiTheme::read(cx);
        div()
            .flex_shrink_0()
            .w_full()
            .h(px(1.))
            .bg(theme.colors.border)
    }
}

/// Row actions that appear only while their row is hovered or keyboard focus
/// is inside it, like the "+" and "⋯" on a sidebar section header.
///
/// The children stay in layout, in the tab order and in the accessibility
/// tree the whole time; they are only drawn at zero opacity. Tabbing onto one
/// reveals it, and so does focus anywhere inside the element whose
/// [`gpui_kit::FocusHandle`] is passed to [`Reveal::focus_within`]. Mark the
/// row with `.group(name)` and pass the same name to [`Reveal::new`].
#[derive(IntoElement)]
pub struct Reveal {
    id: ElementId,
    group: SharedString,
    within: Option<gpui_kit::FocusHandle>,
    style: gpui_kit::StyleRefinement,
    children: Vec<AnyElement>,
}

impl Reveal {
    /// Creates a reveal that shows while the element marked `.group(group)` is
    /// hovered. The ID keys its focus tracking; keep it stable.
    pub fn new(id: impl Into<ElementId>, group: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            group: group.into(),
            within: None,
            style: Default::default(),
            children: Vec::new(),
        }
    }

    /// Also shows the children while focus is on or inside the element that
    /// tracks `handle`, so a keyboard user on the row sees its actions.
    pub fn focus_within(mut self, handle: &gpui_kit::FocusHandle) -> Self {
        self.within = Some(handle.clone());
        self
    }
}

impl ParentElement for Reveal {
    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
        self.children.extend(elements);
    }
}

impl Styled for Reveal {
    fn style(&mut self) -> &mut gpui_kit::StyleRefinement {
        &mut self.style
    }
}

/// Keyboard focus on a child or inside the row shows the actions. A pointer
/// click that leaves focus there (a collapsed header's trigger, a menu that
/// closed) does not: hover already covers the pointer.
fn revealed_by_focus(
    own: &gpui_kit::FocusHandle,
    within: Option<&gpui_kit::FocusHandle>,
    window: &Window,
    cx: &App,
) -> bool {
    window.last_input_was_keyboard()
        && (own.contains_focused(window, cx)
            || within.is_some_and(|handle| handle.contains_focused(window, cx)))
}

impl RenderOnce for Reveal {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        // Not a tab stop: it only notices focus on its own children.
        let own = window
            .use_keyed_state((self.id.clone(), "reveal-focus"), cx, |_, cx| {
                cx.focus_handle().tab_stop(false)
            })
            .read(cx)
            .clone();
        let focused = revealed_by_focus(&own, self.within.as_ref(), window, cx);
        let root = div()
            .id(self.id)
            .track_focus(&own)
            .flex()
            .items_center()
            .opacity(if focused { 1. } else { 0. })
            .group_hover(self.group, |style| style.opacity(1.))
            .children(self.children);
        apply_style(root, &self.style)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use gpui_kit::{Context, Render, size};

    struct Rows {
        stacked: bool,
    }
    impl Render for Rows {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            div().w(px(320.)).child(
                ItemGroup::new("group").child(
                    Item::new("row")
                        .title("Reduce motion")
                        .description("Turns off animations")
                        .stacked(self.stacked)
                        .actions(
                            div()
                                .debug_selector(|| "control".into())
                                .w(px(36.))
                                .h(px(20.)),
                        )
                        .child(div().debug_selector(|| "copy-end".into())),
                ),
            )
        }
    }

    fn layout(
        stacked: bool,
        cx: &mut gpui_kit::TestAppContext,
    ) -> (
        gpui_kit::Bounds<gpui_kit::Pixels>,
        gpui_kit::Bounds<gpui_kit::Pixels>,
    ) {
        cx.update(super::super::theme::init);
        let (_, cx) = cx.add_window_view(|_, _| Rows { stacked });
        cx.simulate_resize(size(px(800.), px(600.)));
        cx.update(|window, cx| window.draw(cx).clear(cx));
        (
            cx.debug_bounds("control").expect("the control is drawn"),
            cx.debug_bounds("copy-end").expect("the copy is drawn"),
        )
    }

    #[gpui_kit::test]
    fn the_control_stays_on_the_title_row_at_320px(cx: &mut gpui_kit::TestAppContext) {
        let (control, copy) = layout(false, cx);
        // The control is at the trailing edge, beside the copy, not under it.
        assert!(control.left() > copy.left(), "{control:?} {copy:?}");
        assert!(control.top() < copy.bottom(), "{control:?} {copy:?}");
        assert!(control.right() <= px(320.), "{control:?}");
    }

    #[gpui_kit::test]
    fn stacked_puts_the_control_under_the_copy(cx: &mut gpui_kit::TestAppContext) {
        let (control, copy) = layout(true, cx);
        assert!(control.top() >= copy.bottom(), "{control:?} {copy:?}");
        assert!(control.left() <= px(17.), "{control:?}");
    }

    struct Header {
        row: gpui_kit::FocusHandle,
        own: gpui_kit::FocusHandle,
        child: gpui_kit::FocusHandle,
    }
    impl Render for Header {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            div()
                .w(px(240.))
                .group("head")
                .track_focus(&self.row)
                .child(
                    // Stands in for the reveal's own handle around its children.
                    div().track_focus(&self.own).child(
                        div()
                            .debug_selector(|| "action".into())
                            .track_focus(&self.child)
                            .size(px(16.)),
                    ),
                )
                .child(
                    Reveal::new("reveal", "head")
                        .child(div().debug_selector(|| "revealed".into()).size(px(16.))),
                )
        }
    }

    #[gpui_kit::test]
    fn keyboard_focus_on_an_action_or_its_row_reveals_it(cx: &mut gpui_kit::TestAppContext) {
        cx.update(super::super::theme::init);
        let (view, cx) = cx.add_window_view(|_, cx| Header {
            row: cx.focus_handle().tab_stop(true),
            own: cx.focus_handle(),
            child: cx.focus_handle().tab_stop(true),
        });
        cx.update(|window, cx| window.draw(cx).clear(cx));
        // Hidden children keep their place in layout.
        assert!(cx.debug_bounds("revealed").is_some());
        let shown = |cx: &mut gpui_kit::VisualTestContext| {
            cx.update(|window, cx| {
                window.draw(cx).clear(cx);
                let view = view.read(cx);
                revealed_by_focus(&view.own, Some(&view.row), window, cx)
            })
        };
        assert!(!shown(cx), "nothing is focused yet");

        // A pointer focus (no key pressed yet) leaves the actions to hover.
        let child = view.read_with(cx, |view, _| view.child.clone());
        cx.update(|window, cx| window.focus(&child, cx));
        assert!(!shown(cx), "a pointer focus does not reveal");

        cx.simulate_keystrokes("shift");
        cx.update(|window, cx| window.focus(&child, cx));
        assert!(shown(cx), "keyboard focus on the action reveals it");

        let row = view.read_with(cx, |view, _| view.row.clone());
        cx.update(|window, cx| window.focus(&row, cx));
        assert!(shown(cx), "keyboard focus on the row reveals its actions");

        let outside = cx.update(|_, cx| cx.focus_handle());
        cx.update(|window, cx| window.focus(&outside, cx));
        assert!(!shown(cx), "focus elsewhere hides them");
    }
}

Platform notes

Visual reference: shadcn/ui 4.19.0, Neutral Nova (item.tsx). Implementation: crates/ui/registry/item/item.rs, using GPUI Kit 0.9.0.

Item is one row: optional media, a title with a muted description (clamped to two lines) and actions at the trailing edge. .stacked(true) puts the actions under the copy at full width, for wide controls such as a tag field. ItemGroup lays items in a column with ItemSeparator hairlines between them; its default Outline variant is one bordered card with lg corners, the way settings pages group rows. Variants Default, Outline and Muted and sizes Default (min 48px, 10px by 16px padding) and Sm follow shadcn.

Differences from shadcn: shadcn composes ItemMedia, ItemContent, ItemTitle, ItemDescription and ItemActions as children; gpuicn takes them as builder slots (media, title, description, actions) and puts any extra children inside the copy column. A row with .on_click is a button whose accessible name is its title; a row without one is a group named by its title, so a control inside it is announced in context. The application still labels each control.

The Rust source and Usage example define the supported API. Verified: the control stays on the title's row at 320px wide, and stacked rows put it under the copy (unit tests in item.rs).

Reveal has no shadcn counterpart (shadcn reaches for Tailwind's group-hover:opacity-100 group-focus-within:opacity-100). It draws row actions at zero opacity until the row marked .group(name) is hovered or keyboard focus is on an action or inside the element whose focus handle is passed to Reveal::focus_within. The actions stay in layout, in the tab order and in the accessibility tree while hidden. A pointer click that leaves focus behind does not keep them shown; hover covers the pointer. Verified: keyboard focus on an action or on its row reveals it, pointer focus and focus elsewhere do not (unit test in item.rs).