A section with a clickable trigger that shows or hides extra content.
use gpui::{div, prelude::*, px, App, Context, FontWeight, Window};
use crate::theme::ActiveTheme;
use crate::ui::button::{Button, ButtonSize, ButtonVariant};
use crate::ui::collapsible::Collapsible;
#[derive(Default)]
pub struct StarredRepos {
open: bool,
}
impl Render for StarredRepos {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let header = div()
.flex()
.items_center()
.justify_between()
.gap_4()
.px_4()
.child(
div()
.text_sm()
.font_weight(FontWeight::SEMIBOLD)
.child("@hyuskui starred 3 repositories"),
)
.child(
Button::new("toggle", if self.open { "Hide" } else { "Show all" })
.variant(ButtonVariant::Ghost)
.size(ButtonSize::Sm),
);
div().w(px(350.0)).child(
Collapsible::new("starred", self.open)
.trigger(header)
.child(repo("zed-industries/zed", cx))
.content(repo("hyuskui/ui", cx))
.content(repo("rust-lang/rust", cx))
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
})),
)
}
}
fn repo(name: &'static str, cx: &App) -> impl IntoElement {
let theme = cx.theme();
div()
.mt_2()
.px_4()
.py_2()
.rounded(theme.radius)
.border_1()
.border_color(theme.border)
.font_family("Geist Mono")
.text_sm()
.child(name)
}Installation
Copies src/ui/collapsible.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/collapsible.rs.src/ui/collapsible.rs use std::sync::Arc; use gpui::{ div, prelude::*, px, AnimationExt, AnyElement, App, ElementId, Pixels, SpringAnimation, SpringConfig, Window, }; /// Stands in for Radix's `collapsible-down/up` (200ms ease-out): critically damped (damping = /// 2 * sqrt(stiffness)), so the content grows and shrinks without bouncing, and a toggle /// mid-animation turns around smoothly. const HEIGHT_SPRING: SpringConfig = SpringConfig::new(625.0, 50.0, 1.0); type OpenChangeHandler = Box<dyn Fn(&bool, &mut Window, &mut App) + 'static>; /// A section that shows or hides its content. The parent view owns `open` and updates it in /// `on_open_change`. Children added with `.child(...)` stay visible; `.content(...)` is only /// shown while open; it slides open and closed by animating its height. #[derive(IntoElement)] pub struct Collapsible { id: ElementId, open: bool, trigger: Option<AnyElement>, children: Vec<AnyElement>, content: Vec<AnyElement>, on_open_change: Option<OpenChangeHandler>, } impl Collapsible { pub fn new(id: impl Into<ElementId>, open: bool) -> Self { Self { id: id.into(), open, trigger: None, children: Vec::new(), content: Vec::new(), on_open_change: None, } } /// The element that toggles the section when clicked, e.g. a header row. pub fn trigger(mut self, trigger: impl IntoElement) -> Self { self.trigger = Some(trigger.into_any_element()); self } /// Shown below the always-visible children while the section is open. pub fn content(mut self, content: impl IntoElement) -> Self { self.content.push(content.into_any_element()); self } /// Receives the *next* open value. pub fn on_open_change( mut self, handler: impl Fn(&bool, &mut Window, &mut App) + 'static, ) -> Self { self.on_open_change = Some(Box::new(handler)); self } } impl ParentElement for Collapsible { fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) { self.children.extend(elements); } } impl RenderOnce for Collapsible { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let open = self.open; let handler = self.on_open_change; // The content stays laid out while closed, clipped to no height, so its natural height // is known before it opens and the panel can grow from 0 to it. let panel = (!self.content.is_empty()).then(|| { let child_id = |name: &str| ElementId::NamedChild(Arc::new(self.id.clone()), name.into()); let height = window.use_keyed_state(child_id("content-height"), cx, |_, _| None::<Pixels>); let measured = *height.read(cx); div() .flex() .flex_col() .overflow_hidden() .on_children_prepainted(move |bounds, _, cx| { let natural = bounds.first().map(|b| b.size.height); height.update(cx, |height, cx| { if *height != natural { *height = natural; cx.notify(); } }); }) .child(div().flex_none().flex().flex_col().children(self.content)) .with_spring( child_id("content-spring"), SpringAnimation::new(HEIGHT_SPRING).to(open), move |this, phase| match measured { // Fully open, the height is left to layout so content that grows (such // as a nested collapsible opening) isn't clipped to last frame's size. Some(_) if phase.0 >= 1.0 => this, Some(full) => this.h(phase.interpolate_clamped(px(0.0), full)), None if open => this, None => this.h(px(0.0)), }, ) }); div() .flex() .flex_col() .when_some(self.trigger, |this, trigger| { this.child( div() .id(self.id) .cursor_pointer() .when_some(handler, |this, handler| { this.on_click(move |_, window, cx| handler(&!open, window, cx)) }) .child(trigger), ) }) .children(self.children) .children(panel) } }Register the module
// src/ui/mod.rs pub mod collapsible;
Usage
use crate::ui::collapsible::*;Examples
Controlled State
The view owns open and flips it in on_open_change, so anything else can read or set it too.
use gpui::{div, prelude::*, px, Context, Window};
use crate::theme::ActiveTheme;
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::collapsible::Collapsible;
#[derive(Default)]
pub struct CollapsibleControlled {
open: bool,
}
impl Render for CollapsibleControlled {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
div()
.flex()
.flex_col()
.gap_3()
.w(px(320.0))
.child(
div()
.text_sm()
.text_color(theme.muted_foreground)
.child(if self.open { "State: open" } else { "State: closed" }),
)
.child(
Collapsible::new("collapsible-controlled", self.open)
.trigger(Button::new("collapsible-controlled-trigger", "Toggle").variant(ButtonVariant::Outline))
.content(
div()
.mt_3()
.p_4()
.rounded(theme.radius)
.border_1()
.border_color(theme.border)
.text_sm()
.child("Content"),
)
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
})),
)
}
}Basic
A card whose header row is the trigger. The chevron flips to show which way the section will move.
use gpui::{div, prelude::*, px, svg, Context, FontWeight, Window};
use crate::theme::ActiveTheme;
use crate::ui::button::{Button, ButtonSize};
use crate::ui::collapsible::Collapsible;
use crate::icons::{CHEVRON_DOWN, CHEVRON_UP};
#[derive(Default)]
pub struct CollapsibleBasic {
open: bool,
}
impl Render for CollapsibleBasic {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
let header = div()
.flex()
.items_center()
.justify_between()
.child(
div()
.flex()
.flex_col()
.gap_1()
.child(div().text_sm().font_weight(FontWeight::SEMIBOLD).child("Product details"))
.child(
div()
.text_sm()
.text_color(theme.muted_foreground)
.child("Walnut desk organizer, 3 compartments"),
),
)
.child(
svg()
.data(if self.open { CHEVRON_UP } else { CHEVRON_DOWN })
.size(px(16.0))
.text_color(theme.muted_foreground),
);
let row = |label: &'static str, value: &'static str| {
div()
.flex()
.justify_between()
.text_sm()
.child(div().text_color(theme.muted_foreground).child(label))
.child(value)
};
div()
.w(px(350.0))
.p_4()
.rounded(theme.radius)
.border_1()
.border_color(theme.border)
.bg(theme.background)
.child(
Collapsible::new("collapsible-basic", self.open)
.trigger(header)
.content(
div()
.flex()
.flex_col()
.gap_2()
.mt_4()
.pt_4()
.border_t_1()
.border_color(theme.border)
.child(row("Material", "Solid walnut"))
.child(row("Dimensions", "32 x 12 x 8 cm"))
.child(row("Ships in", "2-3 business days"))
.child(div().mt_2().child(Button::new("collapsible-basic-cart", "Add to cart").size(ButtonSize::Sm))),
)
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
})),
)
}
}Settings Panel
Advanced fields stay out of the way until asked for. The radius input is always shown; "More options" reveals separate X and Y radii.
use gpui::{div, prelude::*, px, svg, Context, FontWeight, Window};
use crate::theme::ActiveTheme;
use crate::ui::collapsible::Collapsible;
use crate::ui::input::TextInput;
use crate::icons::{CHEVRON_DOWN, CHEVRON_RIGHT};
#[derive(Default)]
pub struct CollapsibleSettingsPanel {
open: bool,
}
impl Render for CollapsibleSettingsPanel {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
// Each TextInput owns its text and focus, so it lives in keyed state across renders.
let radius = window.use_keyed_state("settings-radius", cx, |_, cx| {
TextInput::new(cx).default_value("8")
});
let radius_x = window.use_keyed_state("settings-radius-x", cx, |_, cx| {
TextInput::new(cx).default_value("8")
});
let radius_y = window.use_keyed_state("settings-radius-y", cx, |_, cx| {
TextInput::new(cx).default_value("8")
});
let theme = cx.theme();
let field = |label: &'static str, input| {
div()
.flex()
.flex_col()
.gap_2()
.flex_1()
.child(div().text_sm().font_weight(FontWeight::MEDIUM).child(label))
.child(input)
};
let trigger = div()
.flex()
.items_center()
.gap_1()
.mt_4()
.text_sm()
.text_color(theme.muted_foreground)
.hover(|style| style.text_color(theme.foreground))
.child(
svg()
.data(if self.open { CHEVRON_DOWN } else { CHEVRON_RIGHT })
.size(px(16.0))
.text_color(theme.muted_foreground),
)
.child(if self.open { "Fewer options" } else { "More options" });
div()
.w(px(320.0))
.p_4()
.rounded(theme.radius)
.border_1()
.border_color(theme.border)
.bg(theme.background)
.flex()
.flex_col()
.gap_4()
.child(
div()
.flex()
.flex_col()
.gap_1()
.child(div().text_sm().font_weight(FontWeight::SEMIBOLD).child("Radius"))
.child(
div()
.text_sm()
.text_color(theme.muted_foreground)
.child("Set the corner radius of the element."),
),
)
.child(field("Radius", radius))
.child(
Collapsible::new("settings-more", self.open)
.trigger(trigger)
.content(
div()
.flex()
.gap_3()
.mt_3()
.child(field("Radius X", radius_x))
.child(field("Radius Y", radius_y)),
)
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
})),
)
}
}File Tree
Nested collapsibles make a file explorer. Each folder is its own section, and the view keeps the set of open folders.
use std::collections::HashSet;
use gpui::{div, prelude::*, px, svg, AnyElement, Context, FontWeight, Window};
use crate::theme::ActiveTheme;
use crate::ui::collapsible::Collapsible;
use crate::icons::{CHEVRON_DOWN, CHEVRON_RIGHT, FILE, FOLDER};
enum Node {
Folder(&'static str, &'static [Node]),
File(&'static str),
}
const TREE: &[Node] = &[
Node::Folder(
"components",
&[
Node::Folder("ui", &[Node::File("button.rs"), Node::File("card.rs")]),
Node::File("header.rs"),
Node::File("footer.rs"),
],
),
Node::Folder("lib", &[Node::File("utils.rs")]),
Node::Folder("hooks", &[Node::File("use_theme.rs")]),
Node::Folder("types", &[Node::File("index.rs")]),
Node::Folder("public", &[Node::File("favicon.ico")]),
Node::File("app.rs"),
Node::File("layout.rs"),
Node::File("Cargo.toml"),
Node::File("README.md"),
Node::File(".gitignore"),
];
pub struct CollapsibleFileTree {
open: HashSet<&'static str>,
}
// The components folder starts expanded, so `Default` is written out instead of derived.
impl Default for CollapsibleFileTree {
fn default() -> Self {
Self { open: HashSet::from(["components"]) }
}
}
impl CollapsibleFileTree {
fn nodes(&self, nodes: &'static [Node], depth: usize, cx: &mut Context<Self>) -> Vec<AnyElement> {
let theme = cx.theme();
let (fg, muted, hover_bg) = (theme.foreground, theme.muted_foreground, theme.accent);
let indent = px(8.0 + 16.0 * depth as f32);
let icon = move |data: &'static [u8]| svg().data(data).flex_none().size(px(16.0)).text_color(muted);
let row = move || {
div()
.flex()
.items_center()
.gap_1p5()
.h(px(28.0))
.pl(indent)
.pr_2()
.rounded(px(4.0))
.text_sm()
.text_color(fg)
.hover(move |style| style.bg(hover_bg))
};
nodes
.iter()
.map(|node| match node {
Node::File(name) => row()
// Lines files up with folder names, past the chevron's column.
.child(div().flex_none().w(px(16.0)))
.child(icon(FILE))
.child(*name)
.into_any_element(),
Node::Folder(name, children) => {
let name: &'static str = name;
let open = self.open.contains(name);
Collapsible::new(name, open)
.trigger(
row()
.child(icon(if open { CHEVRON_DOWN } else { CHEVRON_RIGHT }))
.child(icon(FOLDER))
.child(name),
)
.content(div().flex().flex_col().children(self.nodes(children, depth + 1, cx)))
.on_open_change(cx.listener(move |this, open: &bool, _, cx| {
if *open {
this.open.insert(name);
} else {
this.open.remove(name);
}
cx.notify();
}))
.into_any_element()
}
})
.collect()
}
}
impl Render for CollapsibleFileTree {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
let (border, muted, background) = (theme.border, theme.muted_foreground, theme.background);
let tab = |label: &'static str, active: bool| {
div()
.text_xs()
.font_weight(FontWeight::MEDIUM)
.text_color(muted)
.when(active, |this| this.text_color(theme.foreground))
.child(label)
};
let header = div()
.flex()
.gap_4()
.px_3()
.py_2()
.border_b_1()
.border_color(border)
.child(tab("EXPLORER", true))
.child(tab("OUTLINE", false));
let rows = self.nodes(TREE, 0, cx);
div()
.w(px(260.0))
.rounded(px(8.0))
.border_1()
.border_color(border)
.bg(background)
.child(header)
.child(div().flex().flex_col().p_1().children(rows))
}
}API Reference
Collapsible
A section that shows or hides its content. The parent view owns open and updates it in on_open_change. Children added with .child(...) stay visible; .content(...) is only shown while open; it slides open and closed by animating its height.
Collapsible::new(id: impl Into<ElementId>, open: bool) -> Self.trigger(trigger: impl IntoElement)The element that toggles the section when clicked, e.g. a header row.
.content(content: impl IntoElement)Shown below the always-visible children while the section is open.
.on_open_change(handler: impl Fn(&bool, &mut Window, &mut App) + 'static)Receives the *next* open value.