Skip to main content

gpui_material_extras/disclosure/
accordion.rs

1use std::rc::Rc;
2
3use gpui::{
4    AccessibleAction, AnyElement, App, Axis, ElementId, Entity, FocusHandle, Hsla,
5    InteractiveElement, IntoElement, ParentElement, Pixels, RenderOnce, SharedString,
6    StatefulInteractiveElement, Styled, Window, div, prelude::FluentBuilder, px,
7};
8use gpui_base::{
9    Accordion as BaseAccordion, AccordionHeader as BaseAccordionHeader,
10    AccordionItem as BaseAccordionItem, AccordionPanel as BaseAccordionPanel,
11    AccordionTrigger as BaseAccordionTrigger, MotionReveal,
12};
13use gpui_material_components::{Divider, Text};
14use gpui_material_foundation::{
15    FocusRingPlacement, InteractionSource, Surface, SurfaceBorder, ThemeScope, color,
16    control_feedback::{activate_feedback, feedback_target},
17    current_material_theme, move_roving_focus, resolve_edges,
18};
19use gpui_material_theme::{ColorRole, CornerRole, CornerShape, Direction, LogicalEdges, TypeRole};
20
21use super::{
22    bottom_only_corners, disclosure_chevron, disclosure_motion, feedback_overlay, keyed_feedback,
23    keyed_focus, top_only_corners,
24};
25
26type ExpandedChangeHandler = Rc<dyn Fn(Vec<SharedString>, &mut Window, &mut App)>;
27type ToggleCallback = Rc<dyn Fn(&mut Window, &mut App)>;
28
29/// Expansion policy for [`Accordion`].
30#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
31pub enum AccordionMode {
32    /// At most one item can be expanded at a time; activating the open item collapses it.
33    #[default]
34    Single,
35    /// Exactly one item remains expanded; activating the currently open item is ignored.
36    SingleRequired,
37    /// Any number of items can be expanded independently.
38    Multiple,
39}
40
41/// Visual grouping treatment for [`Accordion`].
42#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
43pub enum AccordionVariant {
44    /// Contiguous surface container with horizontal dividers between items.
45    #[default]
46    Standard,
47    /// Material 3 Expressive segmented surfaces with grouped outer/inner corners and a 2 dp gap.
48    Segmented,
49}
50
51/// Per-instance color overrides for [`Accordion`]. Omitted fields use the window theme.
52#[derive(Clone, Copy, Debug, Default)]
53pub struct AccordionColors {
54    /// Surface container color for collapsed items (and the standard outer container).
55    pub container: Option<Hsla>,
56    /// Optional container color override for expanded items.
57    pub expanded_container: Option<Hsla>,
58    /// Foreground color for item titles.
59    pub title: Option<Hsla>,
60    /// Foreground color for optional item supporting text.
61    pub supporting: Option<Hsla>,
62    /// Foreground color for leading, trailing, and chevron icons.
63    pub icon: Option<Hsla>,
64    /// Perimeter border color when [`Accordion::bordered`] is enabled.
65    pub border: Option<Hsla>,
66    /// Divider color between items and between headers and panels.
67    pub divider: Option<Hsla>,
68    /// Title color when disabled.
69    pub disabled_title: Option<Hsla>,
70    /// Icon color when disabled.
71    pub disabled_icon: Option<Hsla>,
72}
73
74/// One controlled section inside an [`Accordion`].
75pub struct AccordionItem {
76    id: SharedString,
77    title: SharedString,
78    supporting: Option<SharedString>,
79    leading: Option<AnyElement>,
80    trailing: Option<AnyElement>,
81    header_content: Option<AnyElement>,
82    content: Option<AnyElement>,
83    disabled: bool,
84    keep_mounted: bool,
85    heading_level: usize,
86    focus: Option<FocusHandle>,
87    interaction_source: Option<Entity<InteractionSource>>,
88}
89
90impl AccordionItem {
91    /// Creates an accordion section with a stable `id` and accessible `title`.
92    pub fn new(id: impl Into<SharedString>, title: impl Into<SharedString>) -> Self {
93        Self {
94            id: id.into(),
95            title: title.into(),
96            supporting: None,
97            leading: None,
98            trailing: None,
99            header_content: None,
100            content: None,
101            disabled: false,
102            keep_mounted: false,
103            heading_level: 3,
104            focus: None,
105            interaction_source: None,
106        }
107    }
108
109    /// Sets optional supporting text displayed beneath the item title.
110    pub fn supporting(mut self, text: impl Into<SharedString>) -> Self {
111        self.supporting = Some(text.into());
112        self
113    }
114
115    /// Places a decorative leading icon or element at the logical start of the header.
116    pub fn leading(mut self, element: impl IntoElement) -> Self {
117        self.leading = Some(element.into_any_element());
118        self
119    }
120
121    /// Places a decorative trailing element before the disclosure chevron.
122    pub fn trailing(mut self, element: impl IntoElement) -> Self {
123        self.trailing = Some(element.into_any_element());
124        self
125    }
126
127    /// Replaces the visible header title block while preserving `title` as the accessible name.
128    pub fn header_content(mut self, element: impl IntoElement) -> Self {
129        self.header_content = Some(element.into_any_element());
130        self
131    }
132
133    /// Sets the panel body displayed while this item is expanded.
134    pub fn content(mut self, element: impl IntoElement) -> Self {
135        self.content = Some(element.into_any_element());
136        self
137    }
138
139    /// Disables this item's trigger and skips it during roving keyboard navigation.
140    pub fn disabled(mut self, disabled: bool) -> Self {
141        self.disabled = disabled;
142        self
143    }
144
145    /// Keeps the panel mounted in the element tree while collapsed.
146    pub fn keep_mounted(mut self, keep_mounted: bool) -> Self {
147        self.keep_mounted = keep_mounted;
148        self
149    }
150
151    /// Sets the heading accessibility level (defaults to `3`).
152    pub fn heading_level(mut self, level: usize) -> Self {
153        self.heading_level = level.max(1);
154        self
155    }
156
157    /// Attaches a caller-owned [`FocusHandle`] to this item's trigger.
158    pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
159        self.focus = Some(focus.clone());
160        self
161    }
162
163    /// Observes this trigger's interaction state under `ElementId::from((accordion_id, item_id))`.
164    pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
165        self.interaction_source = Some(source.clone());
166        self
167    }
168}
169
170/// Material 3 controlled single- or multi-expand accordion wrapping `gpui_base::Accordion`.
171#[derive(IntoElement)]
172pub struct Accordion {
173    id: ElementId,
174    items: Vec<AccordionItem>,
175    accessible_label: Option<SharedString>,
176    mode: AccordionMode,
177    variant: AccordionVariant,
178    expanded: Vec<SharedString>,
179    on_change: Option<ExpandedChangeHandler>,
180    disabled: bool,
181    bordered: bool,
182    spacing: Option<Pixels>,
183    content_padding: LogicalEdges,
184    colors: AccordionColors,
185}
186
187impl Accordion {
188    /// Creates an accordion container from an ordered collection of [`AccordionItem`] entries.
189    pub fn new(id: impl Into<ElementId>, items: impl IntoIterator<Item = AccordionItem>) -> Self {
190        Self {
191            id: id.into(),
192            items: items.into_iter().collect(),
193            accessible_label: None,
194            mode: AccordionMode::Single,
195            variant: AccordionVariant::Standard,
196            expanded: Vec::new(),
197            on_change: None,
198            disabled: false,
199            bordered: true,
200            spacing: None,
201            content_padding: LogicalEdges::all(16.),
202            colors: AccordionColors::default(),
203        }
204    }
205
206    /// Sets an optional accessible label on the `Role::Group` accordion root.
207    pub fn accessible_label(mut self, label: impl Into<SharedString>) -> Self {
208        self.accessible_label = Some(label.into());
209        self
210    }
211
212    /// Sets the expansion mode (`Single`, `SingleRequired`, or `Multiple`).
213    pub fn mode(mut self, mode: AccordionMode) -> Self {
214        self.mode = mode;
215        self
216    }
217
218    /// Sets the visual variant (`Standard` or `Segmented`).
219    pub fn variant(mut self, variant: AccordionVariant) -> Self {
220        self.variant = variant;
221        self
222    }
223
224    /// Sets the controlled list of currently expanded item IDs.
225    pub fn expanded<I, S>(mut self, ids: I) -> Self
226    where
227        I: IntoIterator<Item = S>,
228        S: Into<SharedString>,
229    {
230        self.expanded = ids.into_iter().map(Into::into).collect();
231        self
232    }
233
234    /// Sets a single controlled expanded item ID (convenience for `Single`/`SingleRequired` modes).
235    pub fn expanded_id(mut self, id: Option<impl Into<SharedString>>) -> Self {
236        self.expanded = id.into_iter().map(Into::into).collect();
237        self
238    }
239
240    /// Handles requested updates to the controlled expanded item IDs.
241    pub fn on_change(
242        mut self,
243        handler: impl Fn(Vec<SharedString>, &mut Window, &mut App) + 'static,
244    ) -> Self {
245        self.on_change = Some(Rc::new(handler));
246        self
247    }
248
249    /// Convenience callback for single-expand modes reporting the requested active item ID.
250    pub fn on_single_change(
251        mut self,
252        handler: impl Fn(Option<SharedString>, &mut Window, &mut App) + 'static,
253    ) -> Self {
254        if self.mode == AccordionMode::Multiple {
255            self.mode = AccordionMode::Single;
256        }
257        self.on_change = Some(Rc::new(move |ids, window, cx| {
258            handler(ids.into_iter().next(), window, cx);
259        }));
260        self
261    }
262
263    /// Disables all items in the accordion (combined with per-item [`AccordionItem::disabled`]).
264    pub fn disabled(mut self, disabled: bool) -> Self {
265        self.disabled = disabled;
266        self
267    }
268
269    /// Draws a 1 px `OutlineVariant` border on the accordion surface(s) (defaults to `true`).
270    pub fn bordered(mut self, bordered: bool) -> Self {
271        self.bordered = bordered;
272        self
273    }
274
275    /// Overrides vertical spacing between items in [`AccordionVariant::Segmented`] (defaults to 2 dp).
276    pub fn spacing(mut self, spacing: Pixels) -> Self {
277        if f32::from(spacing).is_finite() {
278            self.spacing = Some(spacing.max(px(0.)));
279        }
280        self
281    }
282
283    /// Sets logical inner padding for expanded item panels (defaults to 16 dp on all sides).
284    pub fn content_padding(mut self, padding: LogicalEdges) -> Self {
285        self.content_padding = padding;
286        self
287    }
288
289    /// Overrides container, title, supporting text, icon, border, and divider colors.
290    pub fn colors(mut self, colors: AccordionColors) -> Self {
291        self.colors = colors;
292        self
293    }
294}
295
296fn next_expanded_ids(
297    mode: AccordionMode,
298    current: &[SharedString],
299    item_order: &[SharedString],
300    toggled: &SharedString,
301) -> Option<Vec<SharedString>> {
302    let is_open = current.iter().any(|id| id == toggled);
303    match mode {
304        AccordionMode::Single => Some(if is_open {
305            Vec::new()
306        } else {
307            vec![toggled.clone()]
308        }),
309        AccordionMode::SingleRequired => {
310            if is_open {
311                None
312            } else {
313                Some(vec![toggled.clone()])
314            }
315        }
316        AccordionMode::Multiple => {
317            let mut next = Vec::with_capacity(current.len() + 1);
318            for id in item_order {
319                let currently_open = current.iter().any(|open| open == id);
320                let should_be_open = if id == toggled {
321                    !currently_open
322                } else {
323                    currently_open
324                };
325                if should_be_open {
326                    next.push(id.clone());
327                }
328            }
329            Some(next)
330        }
331    }
332}
333
334fn segmented_corners(index: usize, count: usize) -> CornerShape {
335    let outer = 16.0;
336    let inner = 4.0;
337    if count <= 1 {
338        CornerShape::uniform(outer)
339    } else if index == 0 {
340        CornerShape::Radii([outer, outer, inner, inner])
341    } else if index + 1 == count {
342        CornerShape::Radii([inner, inner, outer, outer])
343    } else {
344        CornerShape::uniform(inner)
345    }
346}
347
348impl RenderOnce for Accordion {
349    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
350        let theme = current_material_theme(window, cx);
351        let direction = theme.layout.direction;
352        let rtl = direction == Direction::Rtl;
353        let density = theme.layout.density;
354        let reduced_motion = cx.reduce_motion();
355
356        let on_surface = color(theme.colors.color(ColorRole::OnSurface));
357        let on_surface_variant = color(theme.colors.color(ColorRole::OnSurfaceVariant));
358        let outline_variant = color(theme.colors.color(ColorRole::OutlineVariant));
359        let focus_ring = color(theme.colors.color(ColorRole::Secondary));
360        let disabled_fg = on_surface.opacity(0.38);
361        let border_color = self.colors.border.unwrap_or(outline_variant);
362        let divider_color = self.colors.divider.unwrap_or(outline_variant);
363
364        let item_count = self.items.len();
365        let item_order: Vec<SharedString> = self.items.iter().map(|item| item.id.clone()).collect();
366        let padding = resolve_edges(self.content_padding, direction);
367
368        let mut focus_entries: Vec<(FocusHandle, bool, bool)> = Vec::with_capacity(item_count);
369        for item in &self.items {
370            let enabled = !self.disabled && !item.disabled;
371            let open = self.expanded.iter().any(|id| id == &item.id);
372            let handle = keyed_focus(&self.id, item.id.clone(), item.focus.clone(), window, cx);
373            focus_entries.push((handle, enabled, open));
374        }
375
376        let active_tab_stop = focus_entries
377            .iter()
378            .position(|(focus, enabled, _)| *enabled && focus.is_focused(window))
379            .or_else(|| {
380                focus_entries
381                    .iter()
382                    .position(|(_, enabled, open)| *enabled && *open)
383            })
384            .or_else(|| focus_entries.iter().position(|(_, enabled, _)| *enabled));
385
386        let roving_handles: Vec<(FocusHandle, bool)> = focus_entries
387            .iter()
388            .map(|(focus, enabled, _)| (focus.clone(), *enabled))
389            .collect();
390
391        let mut base = BaseAccordion::new(self.id.clone())
392            .w_full()
393            .flex()
394            .flex_col()
395            .when_some(self.accessible_label.clone(), |this, label| {
396                this.aria_label(label)
397            })
398            .when(self.variant == AccordionVariant::Segmented, |this| {
399                this.gap(self.spacing.unwrap_or(px(2.)))
400            });
401
402        if !roving_handles.is_empty() {
403            let roving = roving_handles.clone();
404            base = base.on_key_down(move |event, window, cx| {
405                if event.keystroke.modifiers.modified() {
406                    return;
407                }
408                if !roving
409                    .iter()
410                    .any(|(focus, enabled)| *enabled && focus.is_focused(window))
411                {
412                    return;
413                }
414                let refs: Vec<(&FocusHandle, bool)> = roving
415                    .iter()
416                    .map(|(focus, enabled)| (focus, *enabled))
417                    .collect();
418                if move_roving_focus(
419                    &refs,
420                    event.keystroke.key.as_str(),
421                    Axis::Vertical,
422                    direction,
423                    window,
424                    cx,
425                )
426                .is_some()
427                {
428                    cx.stop_propagation();
429                }
430            });
431        }
432
433        let standard_shape = CornerRole::Medium.shape();
434        let mode = self.mode;
435        let expanded_ids = Rc::new(self.expanded);
436        let order_rc = Rc::new(item_order);
437        let on_change = self.on_change;
438
439        for (ix, item) in self.items.into_iter().enumerate() {
440            let (focus, enabled, open) = focus_entries[ix].clone();
441            let is_tab_stop = active_tab_stop == Some(ix);
442            let trigger_id = ElementId::from((self.id.clone(), item.id.clone()));
443            let header_id = ElementId::from((self.id.clone(), format!("{}-header", item.id)));
444            let panel_id = ElementId::from((self.id.clone(), format!("{}-panel", item.id)));
445            let motion_id = ElementId::from((self.id.clone(), format!("{}-motion", item.id)));
446            let reveal_id = ElementId::from((self.id.clone(), format!("{}-reveal", item.id)));
447
448            let motion = disclosure_motion(motion_id, open, window, cx);
449            let feedback = keyed_feedback(&self.id, item.id.clone(), window, cx);
450            let tracker = item
451                .interaction_source
452                .as_ref()
453                .map(|source| InteractionSource::track(source, &trigger_id, window, cx));
454            let interaction = {
455                let mut state = feedback.borrow_mut();
456                state.cancel_unavailable(enabled, window);
457                state.track(enabled, &focus, tracker, window, cx)
458            };
459
460            let title_color = if !enabled {
461                self.colors.disabled_title.unwrap_or(disabled_fg)
462            } else {
463                self.colors.title.unwrap_or(on_surface)
464            };
465            let supporting_color = if !enabled {
466                self.colors.disabled_title.unwrap_or(disabled_fg)
467            } else {
468                self.colors.supporting.unwrap_or(on_surface_variant)
469            };
470            let icon_color = if !enabled {
471                self.colors.disabled_icon.unwrap_or(disabled_fg)
472            } else {
473                self.colors.icon.unwrap_or(on_surface_variant)
474            };
475
476            let item_shape = match self.variant {
477                AccordionVariant::Standard => {
478                    if item_count <= 1 {
479                        standard_shape
480                    } else if ix == 0 {
481                        top_only_corners(standard_shape)
482                    } else if ix + 1 == item_count {
483                        bottom_only_corners(standard_shape)
484                    } else {
485                        CornerShape::uniform(0.0)
486                    }
487                }
488                AccordionVariant::Segmented => segmented_corners(ix, item_count),
489            };
490            let trigger_corners = if open || motion.value > 0.01 {
491                top_only_corners(item_shape)
492            } else {
493                item_shape
494            };
495
496            let request_toggle: Option<ToggleCallback> = (enabled)
497                .then_some(on_change.as_ref())
498                .flatten()
499                .map(|handler| {
500                    let handler = handler.clone();
501                    let current = expanded_ids.clone();
502                    let order = order_rc.clone();
503                    let toggled_id = item.id.clone();
504                    let action: ToggleCallback = Rc::new(ThemeScope::bind_action(
505                        move |window, cx| {
506                            if let Some(next) =
507                                next_expanded_ids(mode, &current, &order, &toggled_id)
508                            {
509                                handler(next, window, cx);
510                            }
511                        },
512                        window,
513                        cx,
514                    ));
515                    action
516                });
517
518            let header_min_h = px(density.interactive_size(if item.supporting.is_some() {
519                56.0
520            } else {
521                48.0
522            }));
523
524            let header_label_block = match item.header_content {
525                Some(custom) => div().flex_1().min_w_0().child(custom),
526                None => div()
527                    .flex_1()
528                    .min_w_0()
529                    .flex()
530                    .flex_col()
531                    .gap(px(2.))
532                    .when(rtl, Styled::items_end)
533                    .child(
534                        Text::new(item.title.clone())
535                            .role(TypeRole::TitleMedium)
536                            .color_override(title_color)
537                            .wrap(),
538                    )
539                    .children(item.supporting.map(|supporting| {
540                        Text::new(supporting)
541                            .role(TypeRole::BodySmall)
542                            .color_override(supporting_color)
543                            .wrap()
544                    })),
545            };
546
547            let mut trigger = BaseAccordionTrigger::new(trigger_id)
548                .open(open)
549                .disabled(!enabled)
550                .relative()
551                .w_full()
552                .min_h(header_min_h)
553                .px(px(16.))
554                .py(px(10.))
555                .flex()
556                .flex_row()
557                .items_center()
558                .gap(px(12.))
559                .when(rtl, Styled::flex_row_reverse)
560                .aria_label(item.title.clone())
561                .when(enabled, |this| {
562                    this.cursor_pointer()
563                        .track_focus(&focus)
564                        .tab_stop(is_tab_stop)
565                })
566                .when(!enabled, |this| {
567                    this.a11y_synthetic_children(|tree| tree.parent_node().set_disabled())
568                })
569                .child(feedback_overlay(
570                    feedback.clone(),
571                    trigger_corners,
572                    direction,
573                    interaction,
574                    on_surface,
575                    focus_ring,
576                    FocusRingPlacement::Inset,
577                    reduced_motion,
578                ))
579                .children(item.leading.map(|leading| {
580                    div()
581                        .flex_none()
582                        .flex()
583                        .items_center()
584                        .justify_center()
585                        .text_color(icon_color)
586                        .child(leading)
587                }))
588                .child(header_label_block)
589                .children(item.trailing.map(|trailing| {
590                    div()
591                        .flex_none()
592                        .flex()
593                        .items_center()
594                        .justify_center()
595                        .text_color(icon_color)
596                        .child(trailing)
597                }))
598                .child(
599                    div()
600                        .flex_none()
601                        .flex()
602                        .items_center()
603                        .justify_center()
604                        .text_color(icon_color)
605                        .child(disclosure_chevron(motion.value)),
606                );
607
608            if enabled {
609                trigger = feedback_target(trigger, feedback.clone(), true, Some(focus.clone()));
610                if let Some(toggle) = request_toggle {
611                    let click_toggle = toggle.clone();
612                    let click_feedback = feedback.clone();
613                    let a11y_toggle = toggle;
614                    trigger = trigger
615                        .on_change(move |_, event, window, cx| {
616                            if click_feedback.borrow().blocks_activation(event) {
617                                return;
618                            }
619                            activate_feedback(event, &click_feedback, window, cx);
620                            click_toggle(window, cx);
621                            cx.stop_propagation();
622                        })
623                        .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
624                            a11y_toggle(window, cx);
625                        });
626                }
627            }
628
629            let header = BaseAccordionHeader::new(trigger)
630                .id(header_id)
631                .level(item.heading_level)
632                .w_full();
633
634            let panel = item.content.map(|content| {
635                let inner = div()
636                    .w_full()
637                    .flex()
638                    .flex_col()
639                    .child(Divider::horizontal().color_override(divider_color))
640                    .child(
641                        div()
642                            .w_full()
643                            .pt(padding.top)
644                            .pr(padding.right)
645                            .pb(padding.bottom)
646                            .pl(padding.left)
647                            .child(content),
648                    );
649                let panel_child: AnyElement = if motion.is_running() || (item.keep_mounted && !open)
650                {
651                    MotionReveal::new(reveal_id, motion.value, inner.into_any_element())
652                        .into_any_element()
653                } else {
654                    inner.into_any_element()
655                };
656                BaseAccordionPanel::new()
657                    .id(panel_id)
658                    .open(open)
659                    .keep_mounted(item.keep_mounted || motion.is_running())
660                    .w_full()
661                    .child(panel_child)
662            });
663
664            let mut base_item = BaseAccordionItem::new()
665                .open(open)
666                .disabled(!enabled)
667                .w_full()
668                .flex()
669                .flex_col()
670                .header(header);
671            if let Some(panel) = panel {
672                base_item = base_item.panel(panel);
673            }
674
675            match self.variant {
676                AccordionVariant::Standard => {
677                    if ix > 0 {
678                        base = base.child(Divider::horizontal().color_override(divider_color));
679                    }
680                    let expanded_bg = if open {
681                        self.colors.expanded_container
682                    } else {
683                        None
684                    };
685                    base = base.child(
686                        div()
687                            .w_full()
688                            .when_some(expanded_bg, Styled::bg)
689                            .child(base_item),
690                    );
691                }
692                AccordionVariant::Segmented => {
693                    let mut card = Surface::new(ColorRole::SurfaceContainerLow)
694                        .w_full()
695                        .flex()
696                        .flex_col()
697                        .shape(item_shape);
698                    let custom_bg = if open {
699                        self.colors.expanded_container.or(self.colors.container)
700                    } else {
701                        self.colors.container
702                    };
703                    if let Some(bg) = custom_bg {
704                        card = card.container_color(bg);
705                    }
706                    if self.bordered {
707                        card = card.border(SurfaceBorder {
708                            width: px(1.),
709                            color: border_color,
710                        });
711                    }
712                    base = base.child(card.child(base_item));
713                }
714            }
715        }
716
717        match self.variant {
718            AccordionVariant::Standard => {
719                let mut container = Surface::new(ColorRole::SurfaceContainerLow)
720                    .w_full()
721                    .flex()
722                    .flex_col()
723                    .shape(standard_shape);
724                if let Some(bg) = self.colors.container {
725                    container = container.container_color(bg);
726                }
727                if self.bordered {
728                    container = container.border(SurfaceBorder {
729                        width: px(1.),
730                        color: border_color,
731                    });
732                }
733                container.child(base).into_any_element()
734            }
735            AccordionVariant::Segmented => base.into_any_element(),
736        }
737    }
738}
739
740#[cfg(test)]
741mod tests {
742    use super::*;
743
744    fn ids(list: &[&str]) -> Vec<SharedString> {
745        list.iter().map(|s| SharedString::from(*s)).collect()
746    }
747
748    #[test]
749    fn single_mode_switches_and_collapses_active_item() {
750        let order = ids(&["a", "b", "c"]);
751        assert_eq!(
752            next_expanded_ids(AccordionMode::Single, &[], &order, &"b".into()),
753            Some(ids(&["b"]))
754        );
755        assert_eq!(
756            next_expanded_ids(AccordionMode::Single, &ids(&["b"]), &order, &"c".into()),
757            Some(ids(&["c"]))
758        );
759        assert_eq!(
760            next_expanded_ids(AccordionMode::Single, &ids(&["c"]), &order, &"c".into()),
761            Some(Vec::new())
762        );
763    }
764
765    #[test]
766    fn single_required_mode_keeps_active_item_open() {
767        let order = ids(&["a", "b"]);
768        assert_eq!(
769            next_expanded_ids(
770                AccordionMode::SingleRequired,
771                &ids(&["a"]),
772                &order,
773                &"a".into()
774            ),
775            None
776        );
777        assert_eq!(
778            next_expanded_ids(
779                AccordionMode::SingleRequired,
780                &ids(&["a"]),
781                &order,
782                &"b".into()
783            ),
784            Some(ids(&["b"]))
785        );
786    }
787
788    #[test]
789    fn multiple_mode_toggles_items_preserving_accordion_order() {
790        let order = ids(&["a", "b", "c"]);
791        assert_eq!(
792            next_expanded_ids(AccordionMode::Multiple, &ids(&["c"]), &order, &"a".into()),
793            Some(ids(&["a", "c"]))
794        );
795        assert_eq!(
796            next_expanded_ids(
797                AccordionMode::Multiple,
798                &ids(&["a", "c"]),
799                &order,
800                &"c".into()
801            ),
802            Some(ids(&["a"]))
803        );
804    }
805}