Skip to main content

gpui_material_extras/disclosure/
collapsible.rs

1use std::rc::Rc;
2
3use gpui::{
4    AccessibleAction, AnyElement, App, ElementId, Entity, FocusHandle, Hsla, InteractiveElement,
5    IntoElement, ParentElement, RenderOnce, Role, SharedString, StatefulInteractiveElement, Styled,
6    Window, div, prelude::FluentBuilder, px,
7};
8use gpui_base::{Button as BaseButton, Collapsible as BaseCollapsible, TestSupportExt};
9use gpui_material_components::{Divider, Text};
10use gpui_material_foundation::{
11    FocusRingPlacement, InteractionSource, Surface, SurfaceBorder, ThemeScope, color,
12    control_feedback::{activate_feedback, feedback_target},
13    current_material_theme, resolve_edges,
14};
15use gpui_material_theme::{ColorRole, CornerRole, CornerShape, Direction, LogicalEdges, TypeRole};
16
17use super::{
18    disclosure_chevron, disclosure_motion, feedback_overlay, keyed_feedback, keyed_focus,
19    top_only_corners,
20};
21
22type OpenChangeHandler = Rc<dyn Fn(bool, &mut Window, &mut App)>;
23
24/// Per-instance color overrides for [`Collapsible`]. Omitted fields use the window theme.
25#[derive(Clone, Copy, Debug, Default)]
26pub struct CollapsibleColors {
27    /// Background color for the collapsible container surface.
28    pub container: Option<Hsla>,
29    /// Optional background color override for the header trigger row.
30    pub header: Option<Hsla>,
31    /// Foreground color for the header title.
32    pub title: Option<Hsla>,
33    /// Foreground color for the optional supporting text.
34    pub supporting: Option<Hsla>,
35    /// Foreground color for leading, trailing, and disclosure indicator icons.
36    pub icon: Option<Hsla>,
37    /// Border color when [`Collapsible::bordered`] is enabled.
38    pub border: Option<Hsla>,
39    /// Divider color between the header and expanded body.
40    pub divider: Option<Hsla>,
41    /// Title color when disabled.
42    pub disabled_title: Option<Hsla>,
43    /// Icon and indicator color when disabled.
44    pub disabled_icon: Option<Hsla>,
45}
46
47/// Material 3 single expandable/collapsible container wrapping `gpui_base::Collapsible`.
48///
49/// The application owns the `open` state and applies requests reported through
50/// [`Self::on_open_change`].
51#[derive(IntoElement)]
52pub struct Collapsible {
53    id: ElementId,
54    title: SharedString,
55    open: bool,
56    supporting: Option<SharedString>,
57    leading: Option<AnyElement>,
58    trailing: Option<AnyElement>,
59    header_content: Option<AnyElement>,
60    indicator: Option<AnyElement>,
61    show_indicator: bool,
62    content: Option<AnyElement>,
63    keep_mounted: bool,
64    disabled: bool,
65    bordered: bool,
66    divider: bool,
67    shape: Option<CornerShape>,
68    colors: CollapsibleColors,
69    content_padding: LogicalEdges,
70    focus: Option<FocusHandle>,
71    interaction_source: Option<Entity<InteractionSource>>,
72    on_open_change: Option<OpenChangeHandler>,
73}
74
75impl Collapsible {
76    /// Creates a controlled Material 3 collapsible container with stable `id`, accessible
77    /// `title`, and current `open` state.
78    pub fn new(id: impl Into<ElementId>, title: impl Into<SharedString>, open: bool) -> Self {
79        Self {
80            id: id.into(),
81            title: title.into(),
82            open,
83            supporting: None,
84            leading: None,
85            trailing: None,
86            header_content: None,
87            indicator: None,
88            show_indicator: true,
89            content: None,
90            keep_mounted: false,
91            disabled: false,
92            bordered: true,
93            divider: true,
94            shape: None,
95            colors: CollapsibleColors::default(),
96            content_padding: LogicalEdges::all(16.),
97            focus: None,
98            interaction_source: None,
99            on_open_change: None,
100        }
101    }
102
103    /// Sets optional supporting text displayed beneath the header title.
104    pub fn supporting(mut self, text: impl Into<SharedString>) -> Self {
105        self.supporting = Some(text.into());
106        self
107    }
108
109    /// Places a decorative leading icon or element at the logical start of the header.
110    pub fn leading(mut self, element: impl IntoElement) -> Self {
111        self.leading = Some(element.into_any_element());
112        self
113    }
114
115    /// Places a decorative trailing element before the disclosure chevron.
116    pub fn trailing(mut self, element: impl IntoElement) -> Self {
117        self.trailing = Some(element.into_any_element());
118        self
119    }
120
121    /// Replaces the visible header title/supporting block while retaining the constructor
122    /// `title` as the accessible button name.
123    pub fn header_content(mut self, element: impl IntoElement) -> Self {
124        self.header_content = Some(element.into_any_element());
125        self
126    }
127
128    /// Replaces the default rotating disclosure chevron with custom decorative content.
129    pub fn indicator(mut self, element: impl IntoElement) -> Self {
130        self.indicator = Some(element.into_any_element());
131        self
132    }
133
134    /// Shows or hides the trailing disclosure indicator (defaults to `true`).
135    pub fn show_indicator(mut self, show: bool) -> Self {
136        self.show_indicator = show;
137        self
138    }
139
140    /// Sets the collapsible body content displayed when expanded.
141    pub fn content(mut self, element: impl IntoElement) -> Self {
142        self.content = Some(element.into_any_element());
143        self
144    }
145
146    /// Keeps the collapsible body mounted at zero height while collapsed.
147    pub fn keep_mounted(mut self, keep_mounted: bool) -> Self {
148        self.keep_mounted = keep_mounted;
149        self
150    }
151
152    /// Disables user toggling, skips keyboard focus, and applies disabled styling.
153    pub fn disabled(mut self, disabled: bool) -> Self {
154        self.disabled = disabled;
155        self
156    }
157
158    /// Draws a 1 px `OutlineVariant` perimeter border (defaults to `true`).
159    pub fn bordered(mut self, bordered: bool) -> Self {
160        self.bordered = bordered;
161        self
162    }
163
164    /// Draws a horizontal divider between the header and expanded body (defaults to `true`).
165    pub fn divider(mut self, divider: bool) -> Self {
166        self.divider = divider;
167        self
168    }
169
170    /// Overrides the container corner shape (defaults to `CornerRole::Medium`).
171    pub fn shape(mut self, shape: CornerShape) -> Self {
172        self.shape = Some(shape);
173        self
174    }
175
176    /// Overrides individual container, text, icon, border, and divider colors.
177    pub fn colors(mut self, colors: CollapsibleColors) -> Self {
178        self.colors = colors;
179        self
180    }
181
182    /// Sets logical inner padding for the expanded content region (defaults to 16 dp on all sides).
183    pub fn content_padding(mut self, padding: LogicalEdges) -> Self {
184        self.content_padding = padding;
185        self
186    }
187
188    /// Attaches a caller-owned [`FocusHandle`] to the collapsible header trigger.
189    pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
190        self.focus = Some(focus.clone());
191        self
192    }
193
194    /// Observes trigger hover, press, keyboard focus, and disabled state in `source`.
195    pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
196        self.interaction_source = Some(source.clone());
197        self
198    }
199
200    /// Handles a user request to toggle the controlled `open` state.
201    pub fn on_open_change(
202        mut self,
203        handler: impl Fn(bool, &mut Window, &mut App) + 'static,
204    ) -> Self {
205        self.on_open_change = Some(Rc::new(handler));
206        self
207    }
208}
209
210impl RenderOnce for Collapsible {
211    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
212        let theme = current_material_theme(window, cx);
213        let direction = theme.layout.direction;
214        let rtl = direction == Direction::Rtl;
215        let density = theme.layout.density;
216        let reduced_motion = cx.reduce_motion();
217
218        let on_surface = color(theme.colors.color(ColorRole::OnSurface));
219        let on_surface_variant = color(theme.colors.color(ColorRole::OnSurfaceVariant));
220        let outline_variant = color(theme.colors.color(ColorRole::OutlineVariant));
221        let focus_ring = color(theme.colors.color(ColorRole::Secondary));
222
223        let disabled_fg = on_surface.opacity(0.38);
224        let title_color = if self.disabled {
225            self.colors.disabled_title.unwrap_or(disabled_fg)
226        } else {
227            self.colors.title.unwrap_or(on_surface)
228        };
229        let supporting_color = if self.disabled {
230            self.colors.disabled_title.unwrap_or(disabled_fg)
231        } else {
232            self.colors.supporting.unwrap_or(on_surface_variant)
233        };
234        let icon_color = if self.disabled {
235            self.colors.disabled_icon.unwrap_or(disabled_fg)
236        } else {
237            self.colors.icon.unwrap_or(on_surface_variant)
238        };
239        let border_color = self.colors.border.unwrap_or(outline_variant);
240        let divider_color = self.colors.divider.unwrap_or(outline_variant);
241        let shape = self.shape.unwrap_or_else(|| CornerRole::Medium.shape());
242
243        let motion = disclosure_motion(
244            ElementId::from((self.id.clone(), "motion")),
245            self.open,
246            window,
247            cx,
248        );
249
250        let trigger_id = ElementId::from((self.id.clone(), "trigger"));
251        let content_id = ElementId::from((self.id.clone(), "content"));
252        let reveal_id = ElementId::from((self.id.clone(), "reveal"));
253
254        let focus = keyed_focus(&self.id, "trigger", self.focus, window, cx);
255        let feedback = keyed_feedback(&self.id, "trigger", window, cx);
256        let tracker = self
257            .interaction_source
258            .as_ref()
259            .map(|source| InteractionSource::track(source, &trigger_id, window, cx));
260        let enabled = !self.disabled;
261        let interaction = {
262            let mut state = feedback.borrow_mut();
263            state.cancel_unavailable(enabled, window);
264            state.track(enabled, &focus, tracker, window, cx)
265        };
266
267        let next_open = !self.open;
268        let toggle = (enabled)
269            .then_some(self.on_open_change)
270            .flatten()
271            .map(|handler| {
272                Rc::new(ThemeScope::bind_action(
273                    move |window, cx| handler(next_open, window, cx),
274                    window,
275                    cx,
276                ))
277            });
278
279        let header_corners = if self.open || motion.value > 0.01 {
280            top_only_corners(shape)
281        } else {
282            shape
283        };
284
285        let header_min_h = px(density.interactive_size(if self.supporting.is_some() {
286            56.0
287        } else {
288            48.0
289        }));
290
291        let header_label_block = match self.header_content {
292            Some(custom) => div().flex_1().min_w_0().child(custom),
293            None => div()
294                .flex_1()
295                .min_w_0()
296                .flex()
297                .flex_col()
298                .gap(px(2.))
299                .when(rtl, Styled::items_end)
300                .child(
301                    Text::new(self.title.clone())
302                        .role(TypeRole::TitleMedium)
303                        .color_override(title_color)
304                        .wrap(),
305                )
306                .children(self.supporting.map(|supporting| {
307                    Text::new(supporting)
308                        .role(TypeRole::BodySmall)
309                        .color_override(supporting_color)
310                        .wrap()
311                })),
312        };
313
314        let indicator = self.show_indicator.then(|| {
315            let glyph = self
316                .indicator
317                .unwrap_or_else(|| disclosure_chevron(motion.value).into_any_element());
318            div()
319                .flex_none()
320                .flex()
321                .items_center()
322                .justify_center()
323                .text_color(icon_color)
324                .child(glyph)
325        });
326
327        let mut trigger = BaseButton::new(trigger_id)
328            .accessibility_label(self.title)
329            .disabled(!enabled)
330            .track_focus(&focus)
331            .relative()
332            .w_full()
333            .min_h(header_min_h)
334            .px(px(16.))
335            .py(px(10.))
336            .flex()
337            .flex_row()
338            .items_center()
339            .justify_start()
340            .gap(px(12.))
341            .when(rtl, Styled::flex_row_reverse)
342            .when_some(self.colors.header, |this, bg| this.bg(bg))
343            .aria_expanded(self.open)
344            .when(enabled, Styled::cursor_pointer)
345            .child(feedback_overlay(
346                feedback.clone(),
347                header_corners,
348                direction,
349                interaction,
350                on_surface,
351                focus_ring,
352                FocusRingPlacement::Inset,
353                reduced_motion,
354            ))
355            .children(self.leading.map(|leading| {
356                div()
357                    .flex_none()
358                    .flex()
359                    .items_center()
360                    .justify_center()
361                    .text_color(icon_color)
362                    .child(leading)
363            }))
364            .child(header_label_block)
365            .children(self.trailing.map(|trailing| {
366                div()
367                    .flex_none()
368                    .flex()
369                    .items_center()
370                    .justify_center()
371                    .text_color(icon_color)
372                    .child(trailing)
373            }))
374            .children(indicator);
375
376        if enabled {
377            trigger = feedback_target(trigger, feedback.clone(), true, Some(focus.clone()));
378            if let Some(toggle) = toggle {
379                let click_toggle = toggle.clone();
380                let click_feedback = feedback.clone();
381                let a11y_toggle = toggle;
382                trigger = trigger
383                    .on_click(move |event, window, cx| {
384                        if click_feedback.borrow().blocks_activation(event) {
385                            return;
386                        }
387                        activate_feedback(event, &click_feedback, window, cx);
388                        click_toggle(window, cx);
389                        cx.stop_propagation();
390                    })
391                    .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
392                        a11y_toggle(window, cx);
393                    });
394            }
395        }
396
397        let padding = resolve_edges(self.content_padding, direction);
398        let body = self.content.map(|content| {
399            div()
400                .id(content_id)
401                .test_support()
402                .role(Role::Region)
403                .w_full()
404                .flex()
405                .flex_col()
406                .when(self.divider, |this| {
407                    this.child(Divider::horizontal().color_override(divider_color))
408                })
409                .child(
410                    div()
411                        .w_full()
412                        .pt(padding.top)
413                        .pr(padding.right)
414                        .pb(padding.bottom)
415                        .pl(padding.left)
416                        .child(content),
417                )
418        });
419
420        let mut base = BaseCollapsible::new().open(self.open).child(trigger);
421        if let Some(body) = body {
422            base = base.content(body);
423        }
424        if motion.is_running() || (self.keep_mounted && !self.open) {
425            base = base.reveal(reveal_id, motion.value);
426        }
427
428        let mut surface = Surface::new(ColorRole::SurfaceContainerLow)
429            .w_full()
430            .flex()
431            .flex_col()
432            .shape(shape);
433        if let Some(container) = self.colors.container {
434            surface = surface.container_color(container);
435        }
436        if self.bordered {
437            surface = surface.border(SurfaceBorder {
438                width: px(1.),
439                color: border_color,
440            });
441        }
442
443        div()
444            .id(self.id)
445            .test_support()
446            .w_full()
447            .child(surface.child(base))
448    }
449}