A stack of collapsible sections whose open items are owned by the parent view.
use gpui::{div, prelude::*, px, Context, Window};
use crate::ui::accordion::Accordion;
pub struct Faq {
open: Option<usize>,
}
impl Default for Faq {
fn default() -> Self {
Self { open: Some(0) }
}
}
impl Render for Faq {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div().w(px(420.0)).child(
Accordion::new("faq")
.item(
"Can more than one item be open?",
"Your view decides. The accordion only reports which header was clicked.",
)
.item(
"Is it styled?",
"Yes. It reads its colors from your theme, so it matches the other components.",
)
.item(
"Is it animated?",
"The panel slides open and the chevron turns, on the same spring.",
)
.open(self.open)
.on_toggle(cx.listener(|this, ix: &usize, _, cx| {
// One item open at a time; clicking the open one closes it.
this.open = if this.open == Some(*ix) { None } else { Some(*ix) };
cx.notify();
})),
)
}
}Installation
Copies src/ui/accordion.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/accordion.rs.src/ui/accordion.rs use std::{f32::consts::PI, rc::Rc, sync::Arc}; use gpui::{ canvas, div, point, prelude::*, px, AnimationExt, AnyElement, App, ElementId, FontWeight, Hsla, PathBuilder, Pixels, SharedString, SpringAnimation, SpringConfig, Window, }; use crate::theme::ActiveTheme; type ToggleHandler = Rc<dyn Fn(&usize, &mut Window, &mut App) + 'static>; /// Critically damped (damping = 2 * sqrt(stiffness)), so the chevron and the panel settle in /// ~250ms without bouncing. const CHEVRON_SPRING: SpringConfig = SpringConfig::new(400.0, 40.0, 1.0); /// A vertically stacked set of collapsible sections. The parent view owns which items are /// open and updates them in `on_toggle`, so it decides whether one or many can be open. #[derive(IntoElement)] pub struct Accordion { id: ElementId, items: Vec<(SharedString, AnyElement)>, open: Vec<usize>, disabled: Vec<usize>, on_toggle: Option<ToggleHandler>, } impl Accordion { pub fn new(id: impl Into<ElementId>) -> Self { Self { id: id.into(), items: Vec::new(), open: Vec::new(), disabled: Vec::new(), on_toggle: None, } } pub fn item(mut self, title: impl Into<SharedString>, content: impl IntoElement) -> Self { self.items.push((title.into(), content.into_any_element())); self } /// Indices of the expanded items. An `Option<usize>` works for single-open accordions. pub fn open(mut self, open: impl IntoIterator<Item = usize>) -> Self { self.open = open.into_iter().collect(); self } /// Indices of items that can't be toggled. They are dimmed and ignore clicks. pub fn disabled(mut self, disabled: impl IntoIterator<Item = usize>) -> Self { self.disabled = disabled.into_iter().collect(); self } /// Receives the index of the item whose header was clicked. pub fn on_toggle(mut self, handler: impl Fn(&usize, &mut Window, &mut App) + 'static) -> Self { self.on_toggle = Some(Rc::new(handler)); self } } impl RenderOnce for Accordion { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let (border, fg, icon) = { let theme = cx.theme(); (theme.border, theme.foreground, theme.muted_foreground) }; let last = self.items.len().saturating_sub(1); // Each panel's natural height, measured after layout, so it can grow from 0 to it. let heights: Vec<_> = (0..self.items.len()) .map(|ix| { let key = ElementId::NamedChild(Arc::new(self.id.clone()), format!("panel-{ix}").into()); window.use_keyed_state(key, cx, |_, _| None::<Pixels>) }) .collect(); div() .id(self.id) .w_full() .flex() .flex_col() .text_sm() .text_color(fg) .children(self.items.into_iter().enumerate().map(|(ix, (title, content))| { let open = self.open.contains(&ix); let disabled = self.disabled.contains(&ix); let handler = self.on_toggle.clone().filter(|_| !disabled); let trigger = div() .id(ix) .flex() .items_center() .justify_between() .gap_4() .py_4() .font_weight(FontWeight::MEDIUM) .when(disabled, |this| this.opacity(0.5).cursor_not_allowed()) .when(!disabled, |this| this.cursor_pointer().hover(|style| style.underline())) .when_some(handler, |this, handler| { this.on_click(move |_, window, cx| handler(&ix, window, cx)) }) .child(title) .child( // A spring keeps the turn smooth when the item is toggled mid-turn, and // a freshly mounted spring starts at its target, so nothing spins on load. div().flex_none().size(px(16.0)).with_spring( ("chevron", ix), SpringAnimation::new(CHEVRON_SPRING).to(open), move |this, phase| { this.child(chevron_down(icon, phase.interpolate_clamped(0.0, PI))) }, ), ); let height = heights[ix].clone(); let measured = *height.read(cx); let panel = 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().pb_4().child(content)) .with_spring( ("panel-spring", ix), SpringAnimation::new(CHEVRON_SPRING).to(open), move |this, phase| match measured { Some(full) => this.h(phase.interpolate_clamped(px(0.0), full)), // Not measured yet: show open panels at their natural height. None if open => this, None => this.h(px(0.0)), }, ); div() .flex() .flex_col() .when(ix != last, |this| this.border_b_1().border_color(border)) .child(trigger) .child(panel) })) } } /// Lucide's chevron-down, drawn as a path because the preview fonts carry no icon glyphs. /// `angle` turns it clockwise around its center, in radians. fn chevron_down(color: Hsla, angle: f32) -> impl IntoElement { canvas( |_, _, _| {}, move |bounds, _, window, _| { let center = bounds.center(); let unit = bounds.size.width / 24.0; let (sin, cos) = angle.sin_cos(); let at = |x: f32, y: f32| { // Lucide paths live on a 24x24 grid centered on (12, 12). let (dx, dy) = (x - 12.0, y - 12.0); point( center.x + unit * (dx * cos - dy * sin), center.y + unit * (dx * sin + dy * cos), ) }; let mut path = PathBuilder::stroke(unit * 2.0); path.move_to(at(6.0, 9.0)); path.line_to(at(12.0, 15.0)); path.line_to(at(18.0, 9.0)); if let Ok(path) = path.build() { window.paint_path(path, color); } }, ) .size_full() }Register the module
// src/ui/mod.rs pub mod accordion;
Usage
use crate::ui::accordion::*;Examples
Multiple
Keep a list of open items instead of one, so several can stay open at once.
use gpui::{div, prelude::*, px, Context, Window};
use crate::ui::accordion::Accordion;
pub struct AccordionMultiple {
open: Vec<usize>,
}
impl Default for AccordionMultiple {
fn default() -> Self {
Self { open: vec![0, 1] }
}
}
impl Render for AccordionMultiple {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div().w(px(420.0)).child(
Accordion::new("accordion-multiple")
.item("Notifications", "Choose which builds and deploys send you a message.")
.item("Privacy", "Decide who can see your projects and activity.")
.item("Billing", "Update your plan, payment method and invoices.")
.open(self.open.clone())
.on_toggle(cx.listener(|this, ix: &usize, _, cx| {
match this.open.iter().position(|open| open == ix) {
Some(pos) => {
this.open.remove(pos);
}
None => this.open.push(*ix),
}
cx.notify();
})),
)
}
}Disabled
Pass indices to disabled to dim items and ignore clicks on them.
use gpui::{div, prelude::*, px, Context, Window};
use crate::ui::accordion::Accordion;
#[derive(Default)]
pub struct AccordionDisabled {
open: Option<usize>,
}
impl Render for AccordionDisabled {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div().w(px(420.0)).child(
Accordion::new("accordion-disabled")
.item("Can I change my username?", "Yes, once every 30 days from your profile settings.")
.item("Can I delete my account?", "Contact support. This option is turned off for team accounts.")
.item("Can I export my data?", "Yes. Exports arrive by email within an hour.")
.open(self.open)
.disabled([1])
.on_toggle(cx.listener(|this, ix: &usize, _, cx| {
this.open = if this.open == Some(*ix) { None } else { Some(*ix) };
cx.notify();
})),
)
}
}Borders
Wrap the accordion in a bordered, rounded container and pad it to frame the items.
use gpui::{div, prelude::*, px, Context, Window};
use crate::theme::ActiveTheme;
use crate::ui::accordion::Accordion;
#[derive(Default)]
pub struct AccordionBorders {
open: Option<usize>,
}
impl Render for AccordionBorders {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
div()
.w(px(420.0))
.px_4()
.rounded(theme.radius)
.border_1()
.border_color(theme.border)
.child(
Accordion::new("accordion-borders")
.item("What is GPUI?", "The GPU-accelerated UI framework behind the Zed editor.")
.item("Does it run on the web?", "Yes. These previews are GPUI compiled to WebAssembly.")
.item("Which platforms?", "macOS, Linux, Windows and the browser.")
.open(self.open)
.on_toggle(cx.listener(|this, ix: &usize, _, cx| {
this.open = if this.open == Some(*ix) { None } else { Some(*ix) };
cx.notify();
})),
)
}
}Card
Put the accordion inside a Card for a settings or FAQ panel.
use gpui::{div, prelude::*, px, Context, Window};
use crate::ui::accordion::Accordion;
use crate::ui::card::Card;
pub struct AccordionCard {
open: Option<usize>,
}
impl Default for AccordionCard {
fn default() -> Self {
Self { open: Some(0) }
}
}
impl Render for AccordionCard {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div().w(px(420.0)).child(
Card::new()
.title("Subscription")
.description("Answers to common billing questions.")
.child(
Accordion::new("accordion-card")
.item("When am I charged?", "On the first day of each billing period.")
.item("Can I switch plans?", "Yes. Changes apply right away and are prorated.")
.open(self.open)
.on_toggle(cx.listener(|this, ix: &usize, _, cx| {
this.open = if this.open == Some(*ix) { None } else { Some(*ix) };
cx.notify();
})),
),
)
}
}API Reference
Accordion
A vertically stacked set of collapsible sections. The parent view owns which items are open and updates them in on_toggle, so it decides whether one or many can be open.
Accordion::new(id: impl Into<ElementId>) -> Self.item(title: impl Into<SharedString>, content: impl IntoElement).open(open: impl IntoIterator<Item = usize>)Indices of the expanded items. An Option<usize> works for single-open accordions.
.disabled(disabled: impl IntoIterator<Item = usize>)Indices of items that can't be toggled. They are dimmed and ignore clicks.
.on_toggle(handler: impl Fn(&usize, &mut Window, &mut App) + 'static)Receives the index of the item whose header was clicked.