Skip to main content

gpui_base/
toggle_group.rs

1use gpui::{
2    AnyElement, App, Axis, Div, ElementId, InteractiveElement, Interactivity, IntoElement,
3    ParentElement, RenderOnce, Role, Stateful, StatefulInteractiveElement, StyleRefinement, Styled,
4    Window, accesskit, div,
5};
6use smallvec::SmallVec;
7
8/// An unstyled container for a set of toggle elements.
9#[derive(IntoElement)]
10pub struct ToggleGroup {
11    base: Stateful<Div>,
12    style: StyleRefinement,
13    axis: Axis,
14    children: SmallVec<[AnyElement; 4]>,
15}
16
17impl ToggleGroup {
18    pub fn new(id: impl Into<ElementId>) -> Self {
19        Self {
20            base: div().id(id.into()),
21            style: StyleRefinement::default(),
22            axis: Axis::Horizontal,
23            children: SmallVec::new(),
24        }
25    }
26
27    /// Sets the semantic axis of the group.
28    pub fn axis(mut self, axis: Axis) -> Self {
29        self.axis = axis;
30        self
31    }
32}
33
34impl Styled for ToggleGroup {
35    fn style(&mut self) -> &mut StyleRefinement {
36        &mut self.style
37    }
38}
39
40impl ParentElement for ToggleGroup {
41    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
42        self.children.extend(elements);
43    }
44}
45
46impl InteractiveElement for ToggleGroup {
47    fn interactivity(&mut self) -> &mut Interactivity {
48        self.base.interactivity()
49    }
50}
51
52impl StatefulInteractiveElement for ToggleGroup {}
53
54impl RenderOnce for ToggleGroup {
55    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
56        self.base
57            .role(Role::Toolbar)
58            .aria_orientation(match self.axis {
59                Axis::Horizontal => accesskit::Orientation::Horizontal,
60                Axis::Vertical => accesskit::Orientation::Vertical,
61            })
62            .children(self.children)
63            .refine_style(&self.style)
64    }
65}