Skip to main content

gpui_component/
accordion.rs

1use std::{cell::RefCell, collections::HashSet, rc::Rc, sync::Arc};
2
3use gpui::{
4    AnyElement, App, ElementId, InteractiveElement as _, IntoElement, ParentElement, RenderOnce,
5    SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled, Window, div,
6    percentage, prelude::FluentBuilder as _, rems,
7};
8
9use crate::{ActiveTheme as _, Icon, IconName, Sizable, Size, StyledExt as _, h_flex};
10use gpui_base::LogicalStyledExt as _;
11use gpui_base::{
12    Accordion as BaseAccordion, AccordionHeader as BaseAccordionHeader,
13    AccordionItem as BaseAccordionItem, AccordionPanel as BaseAccordionPanel, AccordionTrigger,
14    MotionReveal, spring,
15};
16
17/// Accordion element.
18#[derive(IntoElement)]
19pub struct Accordion {
20    id: ElementId,
21    style: StyleRefinement,
22    multiple: bool,
23    size: Size,
24    bordered: bool,
25    disabled: bool,
26    children: Vec<AccordionItem>,
27    on_toggle_click: Option<Rc<dyn Fn(&[usize], &mut Window, &mut App)>>,
28}
29
30impl Accordion {
31    /// Create a new Accordion with the given ID.
32    pub fn new(id: impl Into<ElementId>) -> Self {
33        Self {
34            id: id.into(),
35            style: StyleRefinement::default(),
36            multiple: false,
37            size: Size::default(),
38            bordered: true,
39            children: Vec::new(),
40            disabled: false,
41            on_toggle_click: None,
42        }
43    }
44
45    /// Set whether multiple accordion items can be opened simultaneously, default: false
46    pub fn multiple(mut self, multiple: bool) -> Self {
47        self.multiple = multiple;
48        self
49    }
50
51    /// Set whether the accordion items have borders, default: true
52    pub fn bordered(mut self, bordered: bool) -> Self {
53        self.bordered = bordered;
54        self
55    }
56
57    /// Set whether the accordion is disabled, default: false
58    pub fn disabled(mut self, disabled: bool) -> Self {
59        self.disabled = disabled;
60        self
61    }
62
63    /// Adds an AccordionItem to the Accordion.
64    pub fn item<F>(mut self, child: F) -> Self
65    where
66        F: FnOnce(AccordionItem) -> AccordionItem,
67    {
68        let item = child(AccordionItem::new());
69        self.children.push(item);
70        self
71    }
72
73    /// Sets the on_toggle_click callback for the AccordionGroup.
74    ///
75    /// The first argument `Vec<usize>` is the indices of the open accordions.
76    pub fn on_toggle_click(
77        mut self,
78        on_toggle_click: impl Fn(&[usize], &mut Window, &mut App) + 'static,
79    ) -> Self {
80        self.on_toggle_click = Some(Rc::new(on_toggle_click));
81        self
82    }
83}
84
85impl Sizable for Accordion {
86    fn with_size(mut self, size: impl Into<Size>) -> Self {
87        self.size = size.into();
88        self
89    }
90}
91
92impl Styled for Accordion {
93    fn style(&mut self) -> &mut StyleRefinement {
94        &mut self.style
95    }
96}
97
98impl RenderOnce for Accordion {
99    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
100        let open_indices = Rc::new(RefCell::new(HashSet::new()));
101        let multiple = self.multiple;
102        let last_ix = self.children.len().saturating_sub(1);
103
104        BaseAccordion::new(self.id)
105            .v_flex()
106            .size_full()
107            // The bordered accordion is a single rounded card, the items are
108            // joined by their separators.
109            .when(self.bordered, |this| {
110                this.border_1()
111                    .border_color(cx.theme().border)
112                    .rounded(cx.theme().radius_lg)
113                    .overflow_hidden()
114            })
115            .refine_style(&self.style)
116            .children(
117                self.children
118                    .into_iter()
119                    .enumerate()
120                    .map(|(ix, accordion)| {
121                        if accordion.open {
122                            open_indices.borrow_mut().insert(ix);
123                        }
124                        let disabled = self.disabled || accordion.disabled;
125
126                        accordion
127                            .index(ix)
128                            .last(ix == last_ix)
129                            .with_size(self.size)
130                            .disabled(disabled)
131                            .on_toggle_click({
132                                let open_indices = open_indices.clone();
133                                move |open, _, _| {
134                                    let mut open_indices = open_indices.borrow_mut();
135                                    if *open {
136                                        if !multiple {
137                                            open_indices.clear();
138                                        }
139                                        open_indices.insert(ix);
140                                    } else {
141                                        open_indices.remove(&ix);
142                                    }
143                                }
144                            })
145                    }),
146            )
147            .when_some(
148                self.on_toggle_click.filter(|_| !self.disabled),
149                |this, on_toggle| {
150                    this.on_click(move |_, window, cx| {
151                        let open_indices =
152                            open_indices.borrow().iter().copied().collect::<Vec<_>>();
153                        on_toggle(&open_indices, window, cx)
154                    })
155                },
156            )
157    }
158}
159
160/// An Accordion is a vertically stacked list of items, each of which can be expanded to reveal the content associated with it.
161#[derive(IntoElement)]
162pub struct AccordionItem {
163    index: usize,
164    last: bool,
165    style: StyleRefinement,
166    hover_style: Option<StyleRefinement>,
167    title_style: StyleRefinement,
168    content_style: StyleRefinement,
169    icon: Option<Icon>,
170    title: AnyElement,
171    children: Vec<AnyElement>,
172    open: bool,
173    size: Size,
174    disabled: bool,
175    on_toggle_click: Option<Arc<dyn Fn(&bool, &mut Window, &mut App)>>,
176}
177
178impl AccordionItem {
179    /// Create a new AccordionItem.
180    pub fn new() -> Self {
181        Self {
182            index: 0,
183            last: false,
184            style: StyleRefinement::default(),
185            hover_style: None,
186            title_style: StyleRefinement::default(),
187            content_style: StyleRefinement::default(),
188            icon: None,
189            title: SharedString::default().into_any_element(),
190            children: Vec::new(),
191            open: false,
192            disabled: false,
193            on_toggle_click: None,
194            size: Size::default(),
195        }
196    }
197
198    /// Set the icon for the accordion item.
199    pub fn icon(mut self, icon: impl Into<Icon>) -> Self {
200        self.icon = Some(icon.into());
201        self
202    }
203
204    /// Set the title for the accordion item.
205    pub fn title(mut self, title: impl IntoElement) -> Self {
206        self.title = title.into_any_element();
207        self
208    }
209
210    pub fn open(mut self, open: bool) -> Self {
211        self.open = open;
212        self
213    }
214
215    pub fn disabled(mut self, disabled: bool) -> Self {
216        self.disabled = disabled;
217        self
218    }
219
220    /// Set extra style for the title row.
221    pub fn title_style(mut self, style: StyleRefinement) -> Self {
222        self.title_style = style;
223        self
224    }
225
226    /// Set the style of the title row while the mouse is over it.
227    ///
228    /// There is no hover style by default. The title row is the part that
229    /// toggles the item, so the hover feedback belongs there, not on the
230    /// whole item.
231    pub fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
232        self.hover_style = Some(f(StyleRefinement::default()));
233        self
234    }
235
236    /// Set extra style for the content below the title.
237    pub fn content_style(mut self, style: StyleRefinement) -> Self {
238        self.content_style = style;
239        self
240    }
241
242    fn index(mut self, index: usize) -> Self {
243        self.index = index;
244        self
245    }
246
247    fn last(mut self, last: bool) -> Self {
248        self.last = last;
249        self
250    }
251
252    fn on_toggle_click(
253        mut self,
254        on_toggle_click: impl Fn(&bool, &mut Window, &mut App) + 'static,
255    ) -> Self {
256        self.on_toggle_click = Some(Arc::new(on_toggle_click));
257        self
258    }
259}
260
261impl ParentElement for AccordionItem {
262    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
263        self.children.extend(elements);
264    }
265}
266
267impl Sizable for AccordionItem {
268    fn with_size(mut self, size: impl Into<Size>) -> Self {
269        self.size = size.into();
270        self
271    }
272}
273
274impl Styled for AccordionItem {
275    fn style(&mut self) -> &mut StyleRefinement {
276        &mut self.style
277    }
278}
279
280impl RenderOnce for AccordionItem {
281    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
282        let text_size = match self.size {
283            Size::XSmall => rems(0.75),
284            Size::Large => rems(1.0),
285            _ => rems(0.875),
286        };
287        let progress = spring(
288            (self.index, "accordion-panel"),
289            if self.open { 1. } else { 0. },
290            cx.theme().motion_tokens().spring_control,
291            window,
292            cx,
293        );
294        let trigger = AccordionTrigger::new(("trigger", self.index))
295            .open(self.open)
296            .disabled(self.disabled)
297            .h_flex()
298            .flex_row_dir(cx)
299            .justify_between()
300            .gap_3()
301            .font_medium()
302            .map(|this| match self.size {
303                Size::XSmall => this.py_1().px_1p5(),
304                Size::Small => this.py_1p5().px_2(),
305                Size::Large => this.py_3().px_4(),
306                _ => this.py_2().px_3(),
307            })
308            .when(self.open, |this| this.text_color(cx.theme().foreground))
309            .refine_style(&self.title_style)
310            .child(
311                h_flex()
312                    .flex_row_dir(cx)
313                    .flex_1()
314                    .min_w_0()
315                    .items_center()
316                    .map(|this| match self.size {
317                        Size::XSmall | Size::Small => this.gap_1(),
318                        _ => this.gap_2(),
319                    })
320                    .when_some(self.icon, |this, icon| {
321                        this.child(icon.with_size(self.size))
322                    })
323                    .child(self.title),
324            )
325            .when(!self.disabled, |this| {
326                this.when_some(self.hover_style, |this, hover_style| {
327                    this.hover(move |this| this.refine_style(&hover_style))
328                })
329                .child(
330                    Icon::new(IconName::ChevronDown)
331                        .xsmall()
332                        .flex_none()
333                        .text_color(cx.theme().muted_foreground)
334                        .rotate(percentage(if self.open { 0.5 } else { 0. })),
335                )
336                .when_some(self.on_toggle_click, |this, on_toggle_click| {
337                    this.on_change(move |open, _, window, cx| {
338                        on_toggle_click(&open, window, cx);
339                    })
340                })
341            });
342
343        div().flex_1().child(
344            BaseAccordionItem::new()
345                .open(self.open)
346                .disabled(self.disabled)
347                .header(
348                    BaseAccordionHeader::new(trigger)
349                        .id(("header", self.index))
350                        .w_full(),
351                )
352                .panel(
353                    BaseAccordionPanel::new()
354                        .id(("panel", self.index))
355                        .open(self.open)
356                        // Mounted while the reveal moves; a settled closed panel
357                        // unmounts, so its content costs no layout or paint. A
358                        // settled spring returns exactly 0, and `!=` keeps a
359                        // bouncy theme spring mounted while it dips below 0.
360                        // Reduced motion reopens straight to full progress, which
361                        // needs the reveal's height from a mounted frame.
362                        .keep_mounted(progress != 0. || cx.reduce_motion())
363                        .w_full()
364                        .child(MotionReveal::new(
365                            ("content", self.index),
366                            progress,
367                            div()
368                                .map(|this| match self.size {
369                                    Size::XSmall => this.pb_1().px_1p5(),
370                                    Size::Small => this.pb_1p5().px_2(),
371                                    Size::Large => this.pb_3().px_4(),
372                                    _ => this.pb_2().px_3(),
373                                })
374                                .refine_style(&self.content_style)
375                                .children(self.children)
376                                .into_any_element(),
377                        )),
378                )
379                .v_flex()
380                .w_full()
381                .bg(cx.theme().tokens.accordion)
382                .overflow_hidden()
383                .when(!self.last, |this| {
384                    this.border_b_1().border_color(cx.theme().border)
385                })
386                .text_size(text_size)
387                .refine_style(&self.style),
388        )
389    }
390}
391
392#[cfg(test)]
393mod tests {
394    use std::time::Duration;
395
396    use gpui::{Context, Render, TestAppContext, div, px};
397
398    use super::*;
399
400    struct Harness;
401
402    impl Render for Harness {
403        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
404            Accordion::new("accordion-layout")
405                .w(px(240.))
406                .h(px(100.))
407                .item(|item| {
408                    item.open(true)
409                        .title(div().debug_selector(|| "first-title".into()).child("First"))
410                        .child(div().debug_selector(|| "first-content".into()).h(px(60.)))
411                })
412                .item(|item| {
413                    item.title(
414                        div()
415                            .debug_selector(|| "second-title".into())
416                            .child("Second"),
417                    )
418                })
419        }
420    }
421
422    #[gpui::test]
423    fn expanded_panel_keeps_content_between_its_header_and_the_next_item(cx: &mut TestAppContext) {
424        cx.update(crate::theme::init);
425        let (_, cx) = cx.add_window_view(|_, _| Harness);
426        cx.update(|window, cx| crate::test_redraw(window, cx));
427
428        let first = cx.debug_bounds("first-title").unwrap();
429        let content = cx.debug_bounds("first-content").unwrap();
430        let second = cx.debug_bounds("second-title").unwrap();
431        assert!(first.origin.y < content.origin.y);
432        assert!(content.origin.y + content.size.height <= second.origin.y);
433    }
434
435    struct Toggle(bool);
436
437    impl Render for Toggle {
438        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
439            Accordion::new("accordion-toggle")
440                .w(px(240.))
441                .item(|item| {
442                    item.open(self.0)
443                        .title("Item")
444                        .child(div().debug_selector(|| "toggle-content".into()).h(px(60.)))
445                })
446                .item(|item| item.title("Next"))
447        }
448    }
449
450    fn content_height(cx: &mut gpui::VisualTestContext) -> Option<gpui::Pixels> {
451        cx.update(|window, cx| crate::test_redraw(window, cx));
452        cx.debug_bounds("toggle-content")
453            .map(|bounds| bounds.size.height)
454    }
455
456    #[gpui::test]
457    fn settled_closed_panel_unmounts_its_content(cx: &mut TestAppContext) {
458        cx.update(crate::theme::init);
459        let (view, cx) = cx.add_window_view(|_, _| Toggle(false));
460        assert_eq!(content_height(cx), None);
461
462        view.update(cx, |view, cx| {
463            view.0 = true;
464            cx.notify();
465        });
466        assert_eq!(content_height(cx), Some(px(60.)));
467        for _ in 0..100 {
468            cx.executor().advance_clock(Duration::from_millis(16));
469            assert_eq!(content_height(cx), Some(px(60.)));
470        }
471
472        // The closing reveal keeps the content until the spring settles.
473        view.update(cx, |view, cx| {
474            view.0 = false;
475            cx.notify();
476        });
477        let mut closing_frames = 0;
478        while content_height(cx).is_some() {
479            closing_frames += 1;
480            assert!(closing_frames < 100, "closed content stayed mounted");
481            cx.executor().advance_clock(Duration::from_millis(16));
482        }
483        assert!(
484            closing_frames > 1,
485            "content unmounted before the reveal ran"
486        );
487    }
488}