A list row with media, a title, a description and actions.
use gpui::{div, prelude::*, px, App, Window};
use crate::icons::{icon, BADGE_CHECK, CHEVRON_RIGHT};
use crate::theme::ActiveTheme;
use crate::ui::button::{Button, ButtonSize, ButtonVariant};
use crate::ui::item::{Item, ItemSize, ItemVariant};
pub fn item_demo(_window: &mut Window, cx: &mut App) -> impl IntoElement {
let fg = cx.theme().foreground;
div()
.w(px(448.0))
.flex()
.flex_col()
.gap_6()
.child(
Item::new("Basic Item")
.description("A simple item with title and description.")
.variant(ItemVariant::Outline)
.actions(
Button::new("item-demo-action", "Action")
.variant(ButtonVariant::Outline)
.size(ButtonSize::Compact),
),
)
.child(
Item::new("Your profile has been verified.")
.variant(ItemVariant::Outline)
.size(ItemSize::Sm)
.media(icon(BADGE_CHECK).size(px(20.0)).text_color(fg))
.actions(icon(CHEVRON_RIGHT).text_color(fg))
.on_click(|_, _, _| {}),
)
}Installation
Copies src/ui/item.rs into your project, along with any components it depends on, and registers the module in src/ui/mod.rs.
Install the theme
Every component reads colors from
crate::theme. Follow the installation guide if you have not added it yet.Copy the source
Paste the code below into
src/ui/item.rs.src/ui/item.rs use gpui::{ div, prelude::*, px, relative, AnyElement, App, ClickEvent, ElementId, FontWeight, HighlightStyle, Pixels, SharedString, StyledText, Window, }; use crate::theme::ActiveTheme; type ClickHandler = Box<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>; #[derive(Clone, Copy, Default, PartialEq)] pub enum ItemVariant { #[default] Default, Outline, Muted, } #[derive(Clone, Copy, Default, PartialEq)] pub enum ItemSize { #[default] Md, Sm, /// The most compact row, for dense lists and menus: the description drops to 12px and sits /// right under the title. Xs, /// shadcn's rhea `sm`, used by the AI elements: 14px gap and side padding, 12px top and /// bottom, and a description on the 20px text line. Compact, } /// A list row: optional media on the left, a title and description, and actions on the right. #[derive(IntoElement)] pub struct Item { id: Option<ElementId>, title: SharedString, title_suffix: Option<SharedString>, description: Option<SharedString>, media: Option<AnyElement>, actions: Option<AnyElement>, header: Option<AnyElement>, variant: ItemVariant, size: ItemSize, radius: Option<Pixels>, padding: Option<Pixels>, /// The description's line height as a multiple of its font size. description_leading: Option<f32>, on_click: Option<ClickHandler>, } impl Item { pub fn new(title: impl Into<SharedString>) -> Self { Self { id: None, title: title.into(), title_suffix: None, description: None, media: None, actions: None, header: None, variant: ItemVariant::default(), size: ItemSize::default(), radius: None, padding: None, description_leading: None, on_click: None, } } /// Text after the title in the muted color, such as an album after a song. pub fn title_suffix(mut self, suffix: impl Into<SharedString>) -> Self { self.title_suffix = Some(suffix.into()); self } pub fn description(mut self, description: impl Into<SharedString>) -> Self { self.description = Some(description.into()); self } /// An icon, avatar or image shown before the text. pub fn media(mut self, media: impl IntoElement) -> Self { self.media = Some(media.into_any_element()); self } /// Buttons or other controls aligned to the end of the row. pub fn actions(mut self, actions: impl IntoElement) -> Self { self.actions = Some(actions.into_any_element()); self } /// Content spanning the full width above the row, such as a cover image. pub fn header(mut self, header: impl IntoElement) -> Self { self.header = Some(header.into_any_element()); self } pub fn variant(mut self, variant: ItemVariant) -> Self { self.variant = variant; self } pub fn size(mut self, size: ItemSize) -> Self { self.size = size; self } /// Overrides the corner radius, which defaults to the theme's plus 2px (shadcn's rounded-lg). pub fn radius(mut self, radius: impl Into<Pixels>) -> Self { self.radius = Some(radius.into()); self } /// Overrides the size's padding on every side, e.g. `px(0.0)` inside a menu row that /// already pads its content. pub fn padding(mut self, padding: impl Into<Pixels>) -> Self { self.padding = Some(padding.into()); self } /// Overrides the description's line height as a multiple of its font size, e.g. `1.0` for /// shadcn's `leading-none` on a dense row. pub fn description_leading(mut self, leading: f32) -> Self { self.description_leading = Some(leading); self } /// The element id of a clickable item. Defaults to the title, so give each clickable item in /// a list a unique id when titles can repeat; items that share an id share hover state. pub fn id(mut self, id: impl Into<ElementId>) -> Self { self.id = Some(id.into()); self } /// Makes the whole row a link: pointer cursor and a muted background on hover. Its element id /// comes from [`Item::id`], or the title when none is set: give each item in a list a unique /// `.id()` if any titles repeat. pub fn on_click( mut self, handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static, ) -> Self { self.on_click = Some(Box::new(handler)); self } } impl RenderOnce for Item { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let theme = cx.theme(); let (pad_x, pad_y, gap) = match self.size { // shadcn's docs give `default` and `sm` the same spacing; `sm` items just tend to // have no description. ItemSize::Md | ItemSize::Sm => (px(12.0), px(10.0), px(10.0)), ItemSize::Xs => (px(10.0), px(8.0), px(8.0)), ItemSize::Compact => (px(14.0), px(12.0), px(14.0)), }; let (pad_x, pad_y) = self.padding.map_or((pad_x, pad_y), |padding| (padding, padding)); // With a description the media sits at the top, nudged down to line up with the title. let top_media = self.description.is_some(); let xs = self.size == ItemSize::Xs; let muted = theme.muted; let title = match self.title_suffix { Some(suffix) => { let start = self.title.len(); let text = SharedString::from(format!("{}{suffix}", self.title)); let muted_fg = HighlightStyle { color: Some(theme.muted_foreground), ..Default::default() }; StyledText::new(text).with_highlights(vec![(start..start + suffix.len(), muted_fg)]).into_any_element() } None => self.title.clone().into_any_element(), }; let row = div() .w_full() .flex() .items_center() .gap(gap) .px(pad_x) .py(pad_y) // rounded-lg: the theme radius is shadcn's rounded-md, 2px tighter. .rounded(self.radius.unwrap_or(theme.radius + px(2.0))) // Every variant keeps a 1px border so rows line up when variants are mixed. .border_1() .border_color(gpui::transparent_black()) .text_sm() // A header wraps the row so it takes a line of its own above the rest. .when_some(self.header, |this, header| { this.flex_wrap().child(div().w_full().child(header)) }) .map(|this| match self.variant { ItemVariant::Default => this, ItemVariant::Outline => this.border_color(theme.border), ItemVariant::Muted => this.bg(theme.muted.opacity(0.5)), }) .when_some(self.media, |this, media| { this.child( div() .flex_none() .flex() .items_center() .when(top_media, |this| this.self_start().mt(px(2.0))) .child(media), ) }) .child( div() .flex_1() .min_w_0() .flex() .flex_col() .when(!xs, |this| this.gap_1()) .child( div() .font_weight(FontWeight::MEDIUM) // leading-snug .line_height(relative(1.375)) .text_color(theme.foreground) .child(title), ) .when_some(self.description, |this, description| { // leading-normal (1.5), except rhea's, which keeps the 20px text line. let (size, line_height) = match self.size { ItemSize::Compact => (px(14.0), px(20.0)), ItemSize::Xs => (px(12.0), px(18.0)), _ => (px(14.0), px(21.0)), }; let line_height = self.description_leading.map_or(line_height, |leading| size * leading); this.child( words(description, size, window) .text_size(size) .line_height(line_height) .text_color(theme.muted_foreground) // line-clamp-2, without the ellipsis. .max_h(line_height * 2.0) .overflow_hidden(), ) }), ) .when_some(self.actions, |this, actions| { this.child(div().flex_none().flex().items_center().gap_2().child(actions)) }); match self.on_click { Some(handler) => row .id(self.id.unwrap_or_else(|| ElementId::Name(self.title))) .cursor_pointer() .hover(move |style| style.bg(muted)) .on_click(handler) .into_any_element(), None => row.into_any_element(), } } } /// Text that wraps between words like a browser paragraph. GPUI's line wrapper adds up each /// character's width without kerning, about 1.5% more than the shaped text, so it breaks lines /// a word early. Each word here gets its shaped width, and a space's width between words on the /// same line, so a line ends where the browser's would. fn words(text: SharedString, size: Pixels, window: &mut Window) -> gpui::Div { let style = window.text_style(); let measure = |word: &str| { let run = style.to_run(word.len()); window.text_system().shape_line(SharedString::from(word.to_string()), size, &[run], None).width }; let space = measure(" "); let words: Vec<_> = text.split_whitespace().map(|word| (word.to_string(), measure(word))).collect(); div() .flex() .flex_wrap() .gap_x(space) .children(words.into_iter().map(|(word, width)| div().flex_none().w(width).whitespace_nowrap().child(word))) }Register the module
// src/ui/mod.rs pub mod item;
Usage
use crate::ui::item::*;Examples
Variant
ItemVariant::Default has no border or fill, Outline adds a border and Muted a soft background for secondary content.
use gpui::{div, prelude::*, px, App, Window};
use crate::icons::{icon, INBOX};
use crate::theme::ActiveTheme;
use crate::ui::item::{Item, ItemVariant};
const VARIANTS: [(ItemVariant, &str, &str); 3] = [
(ItemVariant::Default, "Default Variant", "Transparent background with no border."),
(ItemVariant::Outline, "Outline Variant", "Outlined style with a visible border."),
(ItemVariant::Muted, "Muted Variant", "Muted background for secondary content."),
];
pub fn item_variant(_window: &mut Window, cx: &mut App) -> impl IntoElement {
let fg = cx.theme().foreground;
div()
.w(px(448.0))
.flex()
.flex_col()
.gap_6()
.children(VARIANTS.into_iter().map(|(variant, title, description)| {
Item::new(title)
.description(description)
.variant(variant)
.media(icon(INBOX).text_color(fg))
}))
}Size
ItemSize::Md is the default; Sm and Xs trim the padding and gaps for dense layouts.
use gpui::{div, prelude::*, px, App, Window};
use crate::icons::{icon, INBOX};
use crate::theme::ActiveTheme;
use crate::ui::item::{Item, ItemSize, ItemVariant};
const SIZES: [(ItemSize, &str, &str); 3] = [
(ItemSize::Md, "Default Size", "The standard size for most use cases."),
(ItemSize::Sm, "Small Size", "A compact size for dense layouts."),
(ItemSize::Xs, "Extra Small Size", "The most compact size available."),
];
pub fn item_size(_window: &mut Window, cx: &mut App) -> impl IntoElement {
let fg = cx.theme().foreground;
div()
.w(px(448.0))
.flex()
.flex_col()
.gap_6()
.children(SIZES.into_iter().map(|(size, title, description)| {
Item::new(title)
.description(description)
.variant(ItemVariant::Outline)
.size(size)
.media(icon(INBOX).text_color(fg))
}))
}Icon
Pass an icon as the media to flag what the row is about.
use gpui::{div, prelude::*, px, App, Window};
use crate::icons::{icon, SHIELD_ALERT};
use crate::theme::ActiveTheme;
use crate::ui::button::{Button, ButtonSize, ButtonVariant};
use crate::ui::item::{Item, ItemVariant};
pub fn item_icon(_window: &mut Window, cx: &mut App) -> impl IntoElement {
let fg = cx.theme().foreground;
div().w(px(512.0)).child(
Item::new("Security Alert")
.description("New login detected from unknown device.")
.variant(ItemVariant::Outline)
.media(icon(SHIELD_ALERT).text_color(fg))
.actions(
Button::new("item-icon-review", "Review")
.variant(ButtonVariant::Outline)
.size(ButtonSize::Compact),
),
)
}Avatar
An Avatar or AvatarGroup as the media puts people at the start of the row.
use gpui::{div, prelude::*, px, App, Window};
use crate::icons::{icon, PLUS};
use crate::theme::ActiveTheme;
use crate::ui::avatar::{Avatar, AvatarGroup, AvatarSize};
use crate::ui::button::{Button, ButtonSize, ButtonVariant};
use crate::ui::item::{Item, ItemVariant};
// shadcn uses github.com/<user>.png, but that redirect sends no CORS headers, so the browser
// can't follow it; these are the avatar URLs it redirects to.
pub fn item_avatar(_window: &mut Window, cx: &mut App) -> impl IntoElement {
let fg = cx.theme().foreground;
div()
.w(px(512.0))
.flex()
.flex_col()
.gap_6()
.child(
Item::new("Evil Rabbit")
.description("Last seen 5 months ago")
.variant(ItemVariant::Outline)
.media(Avatar::new("ER").src("https://avatars.githubusercontent.com/u/6880091?v=4").size(AvatarSize::Lg))
.actions(
Button::new("item-avatar-invite", "")
.variant(ButtonVariant::Outline)
.size(ButtonSize::Compact)
.icon_only()
.rounded_full()
.leading(icon(PLUS).text_color(fg)),
),
)
.child(
Item::new("No Team Members")
.description("Invite your team to collaborate on this project.")
.variant(ItemVariant::Outline)
.media(
AvatarGroup::new()
.child(Avatar::new("CN").src("https://avatars.githubusercontent.com/u/124599?v=4").grayscale(true))
.child(Avatar::new("LR").src("https://avatars.githubusercontent.com/u/8675906?v=4").grayscale(true))
.child(Avatar::new("ER").src("https://avatars.githubusercontent.com/u/6880091?v=4").grayscale(true)),
)
.actions(
Button::new("item-avatar-team-invite", "Invite")
.variant(ButtonVariant::Outline)
.size(ButtonSize::Compact),
),
)
}Image
Use a thumbnail as the media, such as album art.
use gpui::{div, linear_color_stop, linear_gradient, prelude::*, px, rgb, App, Window};
use crate::theme::ActiveTheme;
use crate::ui::item::{Item, ItemVariant};
struct Song {
title: &'static str,
artist: &'static str,
album: &'static str,
duration: &'static str,
/// The album art's gradient, top left to bottom right.
art: (u32, u32),
}
// shadcn's art is avatar.vercel.sh/<title> in grayscale, a diagonal gradient per name. That
// service sends no CORS headers, so the browser can't load it here; these are its gradients for
// each title, already converted to gray.
const MUSIC: [Song; 3] = [
Song { title: "Midnight City Lights", artist: "Neon Dreams", album: "Electric Nights", duration: "3:45", art: (0x393939, 0xa0a0a0) },
Song { title: "Coffee Shop Conversations", artist: "The Morning Brew", album: "Urban Stories", duration: "4:05", art: (0x474747, 0xd1d1d1) },
Song { title: "Digital Rain", artist: "Cyber Symphony", album: "Binary Beats", duration: "3:30", art: (0x3c3c3c, 0xb2b2b2) },
];
pub fn item_image(_window: &mut Window, cx: &mut App) -> impl IntoElement {
let muted_fg = cx.theme().muted_foreground;
div()
.w(px(448.0))
.flex()
.flex_col()
.gap_4()
.children(MUSIC.iter().map(|song| {
Item::new(format!("{} - ", song.title))
.title_suffix(song.album)
.description(song.artist)
.variant(ItemVariant::Outline)
.media(div().size(px(40.0)).rounded(px(6.0)).bg(linear_gradient(
135.0,
linear_color_stop(rgb(song.art.0), 0.0),
linear_color_stop(rgb(song.art.1), 1.0),
)))
.actions(div().line_height(px(21.0)).text_color(muted_fg).child(song.duration))
.on_click(|_, _, _| {})
}))
}Group
Stack items with a gap to form a list.
use gpui::{div, prelude::*, px, App, Window};
use crate::icons::{icon, PLUS};
use crate::theme::ActiveTheme;
use crate::ui::avatar::Avatar;
use crate::ui::button::{Button, ButtonSize, ButtonVariant};
use crate::ui::item::{Item, ItemVariant};
// shadcn uses github.com/<user>.png, but that redirect sends no CORS headers, so the browser
// can't follow it; these are the avatar URLs it redirects to.
const PEOPLE: [(&str, &str, &str); 3] = [
("shadcn", "https://avatars.githubusercontent.com/u/124599?v=4", "shadcn@vercel.com"),
("maxleiter", "https://avatars.githubusercontent.com/u/8675906?v=4", "maxleiter@vercel.com"),
("evilrabbit", "https://avatars.githubusercontent.com/u/6880091?v=4", "evilrabbit@vercel.com"),
];
pub fn item_group(_window: &mut Window, cx: &mut App) -> impl IntoElement {
let fg = cx.theme().foreground;
div()
.w(px(384.0))
.flex()
.flex_col()
.gap_4()
.children(PEOPLE.into_iter().enumerate().map(|(ix, (username, avatar, email))| {
Item::new(username)
.description(email)
.variant(ItemVariant::Outline)
.media(Avatar::new(&username[..1]).src(avatar).grayscale(true))
.actions(
Button::new(("item-group-add", ix), "")
.variant(ButtonVariant::Ghost)
.size(ButtonSize::Sm)
.icon_only()
.rounded_full()
.leading(icon(PLUS).text_color(fg)),
)
}))
}Header
header puts full-width content, such as a cover image, on its own line above the title.
use gpui::{div, img, prelude::*, px, ObjectFit};
use crate::ui::item::{Item, ItemVariant};
// The covers are requested at twice their 149px size, so they are never drawn shrunk.
const MODELS: [(&str, &str, &str); 3] = [
(
"v0-1.5-sm",
"Everyday tasks and UI generation.",
"https://images.unsplash.com/photo-1650804068570-7fb2e3dbf888?q=80&w=298&h=298&auto=format&fit=crop",
),
(
"v0-1.5-lg",
"Advanced thinking or reasoning.",
"https://images.unsplash.com/photo-1610280777472-54133d004c8c?q=80&w=298&h=298&auto=format&fit=crop",
),
(
"v0-2.0-mini",
"Open Source model for everyone.",
"https://images.unsplash.com/photo-1602146057681-08560aee8cde?q=80&w=298&h=298&auto=format&fit=crop",
),
];
/// Each card's width: three columns of the 558px row with 16px gaps.
const CARD: f32 = (558.0 - 2.0 * 16.0) / 3.0;
pub fn item_header() -> impl IntoElement {
div().w(px(558.0)).flex().gap_4().children(MODELS.into_iter().map(|(name, description, image)| {
// A square cover: the card's width less its padding and border.
let side = px(CARD - 2.0 * 12.0 - 2.0);
div().w(px(CARD)).child(
Item::new(name)
.description(description)
.variant(ItemVariant::Outline)
// `object-cover` scales the photo past the square, so clip it to the box.
.header(
div().size(side).rounded(px(6.0)).overflow_hidden().child(
img(image).size_full().rounded(px(6.0)).object_fit(ObjectFit::Cover),
),
),
)
}))
}Link
on_click makes the whole row a link, with a pointer cursor and a muted background on hover.
use gpui::{div, prelude::*, px, App, Window};
use crate::icons::{icon, CHEVRON_RIGHT, EXTERNAL_LINK};
use crate::theme::ActiveTheme;
use crate::ui::item::{Item, ItemVariant};
pub fn item_link(_window: &mut Window, cx: &mut App) -> impl IntoElement {
let fg = cx.theme().foreground;
div()
.w(px(448.0))
.flex()
.flex_col()
.gap_4()
.child(
Item::new("Visit our documentation")
.description("Learn how to get started with our components.")
.actions(icon(CHEVRON_RIGHT).text_color(fg))
.on_click(|_, _, cx| cx.open_url("https://ui.hyuskui.com/docs")),
)
.child(
Item::new("External resource")
.description("Opens in a new tab with security attributes.")
.variant(ItemVariant::Outline)
.actions(icon(EXTERNAL_LINK).text_color(fg))
.on_click(|_, _, cx| cx.open_url("https://ui.hyuskui.com")),
)
}Dropdown
Items work as rich rows inside a menu, here a people picker. Wrap each one in a clickable row to handle selection.
use gpui::{div, prelude::*, px, Context, Window};
use crate::icons::{icon, CHEVRON_DOWN};
use crate::theme::ActiveTheme;
use crate::ui::avatar::{Avatar, AvatarSize};
use crate::ui::button::{Button, ButtonSize, ButtonVariant};
use crate::ui::item::{Item, ItemSize};
use crate::ui::popover::{Align, Popover};
// shadcn uses github.com/<user>.png, but that redirect sends no CORS headers, so the browser
// can't follow it; these are the avatar URLs it redirects to.
const PEOPLE: [(&str, &str, &str); 3] = [
("shadcn", "https://avatars.githubusercontent.com/u/124599?v=4", "shadcn@vercel.com"),
("maxleiter", "https://avatars.githubusercontent.com/u/8675906?v=4", "maxleiter@vercel.com"),
("evilrabbit", "https://avatars.githubusercontent.com/u/6880091?v=4", "evilrabbit@vercel.com"),
];
#[derive(Default)]
pub struct ItemDropdown {
open: bool,
}
impl Render for ItemDropdown {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
let (fg, accent) = (theme.foreground, theme.accent);
let rows = PEOPLE.into_iter().enumerate().map(|(ix, (username, avatar, email))| {
// A menu row pads its content, so the item inside drops its own padding.
div()
.id(("item-dropdown-row", ix))
.px(px(6.0))
.py_1()
.rounded(px(8.0))
.cursor_pointer()
.hover(move |style| style.bg(accent))
.on_click(cx.listener(|this, _, _, cx| {
this.open = false;
cx.notify();
}))
.child(
Item::new(username)
.description(email)
.size(ItemSize::Xs)
.padding(px(0.0))
.description_leading(1.0)
.media(Avatar::new(&username[..1]).src(avatar).grayscale(true).size(AvatarSize::Custom(px(26.0)))),
)
});
div().h(px(300.0)).w(px(256.0)).flex().items_start().justify_end().child(
Popover::new("item-dropdown", self.open)
.trigger(
Button::new("item-dropdown-trigger", "Select")
.variant(ButtonVariant::Outline)
.size(ButtonSize::Sm)
.trailing(icon(CHEVRON_DOWN).text_color(fg)),
)
.align(Align::End)
.width(px(192.0))
.padded(false)
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
}))
.child(div().p_1().flex().flex_col().children(rows)),
)
}
}API Reference
ItemVariant
ItemVariant::DefaultItemVariant::OutlineItemVariant::MutedItemSize
ItemSize::MdItemSize::SmItemSize::XsThe most compact row, for dense lists and menus: the description drops to 12px and sits right under the title.
ItemSize::Compactshadcn's rhea sm, used by the AI elements: 14px gap and side padding, 12px top and bottom, and a description on the 20px text line.
Item
A list row: optional media on the left, a title and description, and actions on the right.
Item::new(title: impl Into<SharedString>) -> Self.title_suffix(suffix: impl Into<SharedString>)Text after the title in the muted color, such as an album after a song.
.description(description: impl Into<SharedString>).media(media: impl IntoElement)An icon, avatar or image shown before the text.
.actions(actions: impl IntoElement)Buttons or other controls aligned to the end of the row.
.header(header: impl IntoElement)Content spanning the full width above the row, such as a cover image.
.variant(variant: ItemVariant).size(size: ItemSize).radius(radius: impl Into<Pixels>)Overrides the corner radius, which defaults to the theme's plus 2px (shadcn's rounded-lg).
.padding(padding: impl Into<Pixels>)Overrides the size's padding on every side, e.g. px(0.0) inside a menu row that already pads its content.
.description_leading(leading: f32)Overrides the description's line height as a multiple of its font size, e.g. 1.0 for shadcn's leading-none on a dense row.
.id(id: impl Into<ElementId>)The element id of a clickable item. Defaults to the title, so give each clickable item in a list a unique id when titles can repeat; items that share an id share hover state.
.on_click(handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static)Makes the whole row a link: pointer cursor and a muted background on hover. Its element id comes from [Item::id], or the title when none is set: give each item in a list a unique .id() if any titles repeat.