Skip to main content

gpui_component/button/
toggle.rs

1use gpui_base::LogicalStyledExt as _;
2use std::{cell::Cell, rc::Rc, time::Duration};
3
4use gpui::{
5    AnyElement, App, Axis, Corners, Edges, ElementId, InteractiveElement, IntoElement,
6    ParentElement, RenderOnce, SharedString, StatefulInteractiveElement, StyleRefinement, Styled,
7    Window, prelude::FluentBuilder as _, relative,
8};
9use gpui_base::{Toggle as BaseToggle, ToggleGroup as BaseToggleGroup};
10use smallvec::{SmallVec, smallvec};
11
12use crate::{ActiveTheme, Disableable, Icon, Sizable, Size, StyledExt, tooltip::ComponentTooltip};
13
14#[derive(Default, Copy, Debug, Clone, PartialEq, Eq, Hash)]
15pub enum ToggleVariant {
16    #[default]
17    Ghost,
18    Outline,
19}
20
21pub trait ToggleVariants: Sized {
22    /// Set the variant of the toggle.
23    fn with_variant(self, variant: ToggleVariant) -> Self;
24    /// Set the variant to ghost.
25    fn ghost(self) -> Self {
26        self.with_variant(ToggleVariant::Ghost)
27    }
28    /// Set the variant to outline.
29    fn outline(self) -> Self {
30        self.with_variant(ToggleVariant::Outline)
31    }
32}
33
34#[derive(IntoElement)]
35pub struct Toggle {
36    id: ElementId,
37    style: StyleRefinement,
38    checked: bool,
39    size: Size,
40    variant: ToggleVariant,
41    disabled: bool,
42    border_corners: Corners<bool>,
43    border_edges: Edges<bool>,
44    children: SmallVec<[AnyElement; 1]>,
45    on_click: Option<Box<dyn Fn(&bool, &mut Window, &mut App) + 'static>>,
46    tooltip: ComponentTooltip,
47}
48
49impl Toggle {
50    /// Create a new Toggle element.
51    pub fn new(id: impl Into<ElementId>) -> Self {
52        Self {
53            id: id.into(),
54            style: StyleRefinement::default(),
55            checked: false,
56            size: Size::default(),
57            variant: ToggleVariant::default(),
58            disabled: false,
59            border_corners: Corners {
60                top_left: true,
61                top_right: true,
62                bottom_left: true,
63                bottom_right: true,
64            },
65            border_edges: Edges::all(true),
66            children: smallvec![],
67            on_click: None,
68            tooltip: ComponentTooltip::default(),
69        }
70    }
71
72    /// Set tooltip text for the toggle.
73    pub fn tooltip(mut self, tooltip: impl Into<SharedString>) -> Self {
74        self.tooltip.text = Some((tooltip.into(), None));
75        self
76    }
77
78    /// Overrides how long the pointer must rest before the tooltip shows.
79    ///
80    /// Defaults to [`gpui_base::TooltipDefaults::show_delay`].
81    pub fn tooltip_show_delay(mut self, delay: Duration) -> Self {
82        self.tooltip.show_delay = Some(delay);
83        self
84    }
85
86    /// Add a label to the toggle.
87    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
88        let label: SharedString = label.into();
89        self.children.push(label.into_any_element());
90        self
91    }
92
93    /// Add icon to the toggle.
94    pub fn icon(mut self, icon: impl Into<Icon>) -> Self {
95        let icon: Icon = icon.into();
96        self.children.push(icon.into());
97        self
98    }
99
100    /// Set the checked state of the toggle, default: false
101    pub fn checked(mut self, checked: bool) -> Self {
102        self.checked = checked;
103        self
104    }
105
106    /// Set the callback to be called when the toggle is clicked.
107    ///
108    /// The `&bool` parameter represents the new checked state of the toggle.
109    pub fn on_click(mut self, handler: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self {
110        self.on_click = Some(Box::new(handler));
111        self
112    }
113
114    pub(crate) fn border_corners(mut self, corners: impl Into<Corners<bool>>) -> Self {
115        self.border_corners = corners.into();
116        self
117    }
118
119    pub(crate) fn border_edges(mut self, edges: impl Into<Edges<bool>>) -> Self {
120        self.border_edges = edges.into();
121        self
122    }
123}
124
125impl ToggleVariants for Toggle {
126    fn with_variant(mut self, variant: ToggleVariant) -> Self {
127        self.variant = variant;
128        self
129    }
130}
131
132impl ParentElement for Toggle {
133    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
134        self.children.extend(elements);
135    }
136}
137
138impl Disableable for Toggle {
139    fn disabled(mut self, disabled: bool) -> Self {
140        self.disabled = disabled;
141        self
142    }
143}
144
145impl Sizable for Toggle {
146    fn with_size(mut self, size: impl Into<Size>) -> Self {
147        self.size = size.into();
148        self
149    }
150}
151
152impl Styled for Toggle {
153    fn style(&mut self) -> &mut StyleRefinement {
154        &mut self.style
155    }
156}
157
158impl RenderOnce for Toggle {
159    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
160        let checked = self.checked;
161        let disabled = self.disabled;
162        let hoverable = !disabled && !checked;
163        let rounding = cx.theme().radius;
164        let pressed_background = cx.theme().tokens.accent;
165        let pressed_foreground = cx.theme().accent_foreground;
166        let instance_style = self.style.clone();
167        let (border_corners, border_edges) =
168            super::logical_corners_edges(self.border_corners, self.border_edges, cx);
169
170        BaseToggle::new(self.id)
171            .pressed(checked)
172            .disabled(disabled)
173            .when_some(
174                self.tooltip.text.as_ref().map(|(text, _)| text.clone()),
175                |this, label| this.accessibility_label(label),
176            )
177            .when_some(self.on_click, |this, on_click| {
178                this.on_change(move |next, _, window, cx| on_click(&next, window, cx))
179            })
180            .flex_row_dir(cx)
181            .line_height(relative(1.25))
182            .items_center()
183            .justify_center()
184            .map(|this| match self.size {
185                Size::XSmall => this.min_w_5().h_5().px_0p5().text_xs(),
186                Size::Small => this.min_w_6().h_6().px_1().text_sm(),
187                Size::Large => this.min_w_9().h_9().px_3().text_base(),
188                _ => this.min_w_8().h_8().px_2().text_sm(),
189            })
190            .when(border_corners.top_left, |this| this.rounded_tl(rounding))
191            .when(border_corners.top_right, |this| this.rounded_tr(rounding))
192            .when(border_corners.bottom_left, |this| this.rounded_bl(rounding))
193            .when(border_corners.bottom_right, |this| {
194                this.rounded_br(rounding)
195            })
196            .when(self.variant == ToggleVariant::Outline, |this| {
197                this.when(border_edges.left, |this| this.border_l_1())
198                    .when(border_edges.right, |this| this.border_r_1())
199                    .when(border_edges.top, |this| this.border_t_1())
200                    .when(border_edges.bottom, |this| this.border_b_1())
201                    .border_color(cx.theme().border)
202                    .bg(cx.theme().tokens.background)
203            })
204            // Always register the hover style: GPUI only refreshes the cached
205            // hover state while one is present. If a checked toggle skipped it,
206            // the stale state would paint its label in the hover color once
207            // something else unchecks it while the pointer rests elsewhere.
208            .hover(|this| {
209                if !hoverable {
210                    return this;
211                }
212                this.bg(cx.theme().tokens.accent)
213                    .text_color(cx.theme().accent_foreground)
214            })
215            .styles(|styles| {
216                styles.pressed(|style| {
217                    style
218                        .bg(pressed_background)
219                        .text_color(pressed_foreground)
220                        .refine_style(&instance_style)
221                })
222            })
223            .refine_style(&self.style)
224            .children(self.children)
225            .map(|this| self.tooltip.apply(this))
226    }
227}
228
229/// A group of toggles.
230#[derive(IntoElement)]
231pub struct ToggleGroup {
232    id: ElementId,
233    style: StyleRefinement,
234    size: Size,
235    variant: ToggleVariant,
236    disabled: bool,
237    segmented: bool,
238    single: bool,
239    items: Vec<Toggle>,
240    on_click: Option<Rc<dyn Fn(&Vec<bool>, &mut Window, &mut App) + 'static>>,
241}
242
243impl ToggleGroup {
244    /// Create a new ToggleGroup element.
245    pub fn new(id: impl Into<ElementId>) -> Self {
246        Self {
247            id: id.into(),
248            style: StyleRefinement::default(),
249            size: Size::default(),
250            variant: ToggleVariant::default(),
251            disabled: false,
252            segmented: false,
253            single: false,
254            items: Vec::new(),
255            on_click: None,
256        }
257    }
258
259    /// Add a child [`Toggle`] to the group.
260    pub fn child(mut self, toggle: impl Into<Toggle>) -> Self {
261        self.items.push(toggle.into());
262        self
263    }
264
265    /// Add multiple [`Toggle`]s to the group.
266    pub fn children(mut self, children: impl IntoIterator<Item = impl Into<Toggle>>) -> Self {
267        self.items.extend(children.into_iter().map(Into::into));
268        self
269    }
270
271    /// Set the callback to be called when the toggle group changes.
272    ///
273    /// The `&Vec<bool>` parameter represents the new check state of each [`Toggle`] in the group.
274    /// In a [`single`](Self::single) group at most one of them is `true`.
275    pub fn on_click(
276        mut self,
277        on_click: impl Fn(&Vec<bool>, &mut Window, &mut App) + 'static,
278    ) -> Self {
279        self.on_click = Some(Rc::new(on_click));
280        self
281    }
282
283    /// Render the group as a connected segmented control.
284    ///
285    /// This only changes the look: it removes the default gap and joins
286    /// adjacent item borders into a single segmented outline. Pair it with
287    /// [`single`](Self::single) for an exclusive choice.
288    pub fn segmented(mut self) -> Self {
289        self.segmented = true;
290        self
291    }
292
293    /// Let at most one item be checked at a time.
294    ///
295    /// A click on an unchecked item checks it and clears the others. A click
296    /// on the checked item clears it, so the group can also hold no selection.
297    /// The caller keeps at most one item `checked`; the group does not
298    /// reconcile a state in which several are.
299    pub fn single(mut self) -> Self {
300        self.single = true;
301        self
302    }
303}
304
305impl Sizable for ToggleGroup {
306    fn with_size(mut self, size: impl Into<Size>) -> Self {
307        self.size = size.into();
308        self
309    }
310}
311
312impl ToggleVariants for ToggleGroup {
313    fn with_variant(mut self, variant: ToggleVariant) -> Self {
314        self.variant = variant;
315        self
316    }
317}
318
319impl Disableable for ToggleGroup {
320    fn disabled(mut self, disabled: bool) -> Self {
321        self.disabled = disabled;
322        self
323    }
324}
325
326impl Styled for ToggleGroup {
327    fn style(&mut self) -> &mut StyleRefinement {
328        &mut self.style
329    }
330}
331
332impl RenderOnce for ToggleGroup {
333    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
334        let disabled = self.disabled;
335        let single = self.single;
336        let items_len = self.items.len();
337        let checks = self
338            .items
339            .iter()
340            .map(|item| item.checked)
341            .collect::<Vec<bool>>();
342        let clicked_index = Rc::new(Cell::new(None));
343
344        BaseToggleGroup::new(self.id)
345            .axis(Axis::Horizontal)
346            .child(
347                crate::h_flex()
348                    .flex_row_dir(cx)
349                    .items_center()
350                    .when(!self.segmented, |this| this.gap_2())
351                    .refine_style(&self.style)
352                    .children(self.items.into_iter().enumerate().map({
353                        {
354                            let clicked_index = clicked_index.clone();
355                            move |(ix, item)| {
356                                let item = if !self.segmented || items_len == 1 {
357                                    item
358                                } else if ix == 0 {
359                                    item.border_corners(Corners {
360                                        top_left: true,
361                                        top_right: false,
362                                        bottom_left: true,
363                                        bottom_right: false,
364                                    })
365                                    .border_edges(Edges {
366                                        left: true,
367                                        top: true,
368                                        right: true,
369                                        bottom: true,
370                                    })
371                                } else if ix == items_len - 1 {
372                                    item.border_corners(Corners {
373                                        top_left: false,
374                                        top_right: true,
375                                        bottom_left: false,
376                                        bottom_right: true,
377                                    })
378                                    .border_edges(Edges {
379                                        left: false,
380                                        top: true,
381                                        right: true,
382                                        bottom: true,
383                                    })
384                                } else {
385                                    item.border_corners(Corners {
386                                        top_left: false,
387                                        top_right: false,
388                                        bottom_left: false,
389                                        bottom_right: false,
390                                    })
391                                    .border_edges(Edges {
392                                        left: false,
393                                        top: true,
394                                        right: true,
395                                        bottom: true,
396                                    })
397                                };
398
399                                let effective_disabled = disabled || item.disabled;
400                                let clicked_index = clicked_index.clone();
401                                item.disabled(effective_disabled)
402                                    .with_size(self.size)
403                                    .with_variant(self.variant)
404                                    .on_click(move |_, _, cx| {
405                                        clicked_index.set(Some(ix));
406                                        cx.propagate();
407                                    })
408                            }
409                        }
410                    })),
411            )
412            .when_some(
413                (!disabled).then_some(self.on_click).flatten(),
414                |this, on_click| {
415                    this.on_click(move |_, window, cx| {
416                        let Some(ix) = clicked_index.take() else {
417                            return;
418                        };
419                        // A single group clears every other item; clicking its
420                        // checked item still flips that one off.
421                        let mut next = if single {
422                            vec![false; checks.len()]
423                        } else {
424                            checks.clone()
425                        };
426                        next[ix] = !checks[ix];
427                        on_click(&next, window, cx);
428                    })
429                },
430            )
431    }
432}
433
434#[cfg(test)]
435mod tests {
436    use super::*;
437    use crate::{IconName, Theme, h_flex};
438    use gpui::{
439        Context, Hsla, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, Render,
440        StatefulInteractiveElement, TestAppContext, VisualTestContext, div, point, px,
441    };
442    use std::cell::{Cell, RefCell};
443
444    struct ToggleHarness {
445        disabled: bool,
446        changes: Rc<RefCell<Vec<bool>>>,
447        parent_clicks: Rc<Cell<usize>>,
448    }
449
450    impl Render for ToggleHarness {
451        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
452            let changes = self.changes.clone();
453            let parent_clicks = self.parent_clicks.clone();
454            h_flex()
455                .id("toggle-parent")
456                .tab_group()
457                .size(px(100.))
458                .on_click(move |_, _, _| parent_clicks.set(parent_clicks.get() + 1))
459                .child(
460                    Toggle::new("toggle")
461                        .label("Bold")
462                        .disabled(self.disabled)
463                        .size_full()
464                        .on_click(move |next, _, _| changes.borrow_mut().push(*next)),
465                )
466        }
467    }
468
469    fn harness(
470        cx: &mut TestAppContext,
471        disabled: bool,
472    ) -> (
473        &mut VisualTestContext,
474        Rc<RefCell<Vec<bool>>>,
475        Rc<Cell<usize>>,
476    ) {
477        cx.update(crate::init);
478        let changes = Rc::new(RefCell::new(Vec::new()));
479        let parent_clicks = Rc::new(Cell::new(0));
480        let (_, cx) = cx.add_window_view({
481            let changes = changes.clone();
482            let parent_clicks = parent_clicks.clone();
483            move |_, _| ToggleHarness {
484                disabled,
485                changes,
486                parent_clicks,
487            }
488        });
489        cx.update(|window, cx| window.draw(cx).clear(cx));
490        (cx, changes, parent_clicks)
491    }
492
493    fn activate_key(cx: &mut VisualTestContext, key: &str) {
494        let keystroke =
495            cx.update(|_, cx| Keystroke::parse_with_os(key, cx.platform_info().os).unwrap());
496        cx.simulate_event(KeyDownEvent {
497            keystroke: keystroke.clone(),
498            is_held: false,
499            prefer_character_input: false,
500        });
501        cx.simulate_event(KeyUpEvent { keystroke });
502    }
503
504    #[gpui::test]
505    fn canonical_pointer_activation_fires_once_and_focuses(cx: &mut TestAppContext) {
506        let (cx, changes, _) = harness(cx, false);
507        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
508        assert_eq!(changes.borrow().as_slice(), &[true]);
509        cx.update(|window, cx| assert!(window.focused(cx).is_some()));
510    }
511
512    #[gpui::test]
513    fn canonical_toggle_supports_tab_enter_and_space(cx: &mut TestAppContext) {
514        let (cx, changes, _) = harness(cx, false);
515        cx.update(|window, cx| window.focus_next(cx));
516        cx.update(|window, cx| assert!(window.focused(cx).is_some()));
517        activate_key(cx, "enter");
518        activate_key(cx, "space");
519        assert_eq!(changes.borrow().as_slice(), &[true, true]);
520    }
521
522    #[gpui::test]
523    fn canonical_disabled_toggle_is_inert_and_blocks_parent(cx: &mut TestAppContext) {
524        let (cx, changes, parent_clicks) = harness(cx, true);
525        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
526        assert!(changes.borrow().is_empty());
527        assert_eq!(parent_clicks.get(), 0);
528    }
529
530    struct ToggleGroupHarness {
531        install_group_callback: bool,
532        child_clicks: Rc<Cell<usize>>,
533        group_changes: Rc<RefCell<Vec<Vec<bool>>>>,
534    }
535
536    impl Render for ToggleGroupHarness {
537        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
538            let child_clicks = self.child_clicks.clone();
539            let mut group = ToggleGroup::new("toggle-group")
540                .w(px(120.))
541                .child(
542                    Toggle::new("one")
543                        .label("One")
544                        .checked(true)
545                        .on_click(move |_, _, _| child_clicks.set(child_clicks.get() + 1)),
546                )
547                .child(Toggle::new("two").label("Two"));
548            if self.install_group_callback {
549                let changes = self.group_changes.clone();
550                group = group.on_click(move |next, _, _| changes.borrow_mut().push(next.clone()));
551            }
552            group
553        }
554    }
555
556    fn toggle_group_harness(
557        cx: &mut TestAppContext,
558        install_group_callback: bool,
559    ) -> (
560        &mut VisualTestContext,
561        Rc<Cell<usize>>,
562        Rc<RefCell<Vec<Vec<bool>>>>,
563    ) {
564        cx.update(crate::init);
565        let child_clicks = Rc::new(Cell::new(0));
566        let group_changes = Rc::new(RefCell::new(Vec::new()));
567        let (_, cx) = cx.add_window_view({
568            let child_clicks = child_clicks.clone();
569            let group_changes = group_changes.clone();
570            move |_, _| ToggleGroupHarness {
571                install_group_callback,
572                child_clicks,
573                group_changes,
574            }
575        });
576        cx.update(|window, cx| window.draw(cx).clear(cx));
577        (cx, child_clicks, group_changes)
578    }
579
580    #[gpui::test]
581    fn legacy_toggle_group_overrides_child_callback_even_without_group_callback(
582        cx: &mut TestAppContext,
583    ) {
584        let (cx, child_clicks, changes) = toggle_group_harness(cx, false);
585        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
586        assert_eq!(child_clicks.get(), 0);
587        assert!(changes.borrow().is_empty());
588    }
589
590    #[gpui::test]
591    fn legacy_toggle_group_pointer_flips_only_the_clicked_rendered_value(cx: &mut TestAppContext) {
592        let (cx, child_clicks, changes) = toggle_group_harness(cx, true);
593        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
594        assert_eq!(child_clicks.get(), 0);
595        assert_eq!(changes.borrow().as_slice(), &[vec![false, false]]);
596    }
597
598    #[gpui::test]
599    fn legacy_toggle_group_keyboard_click_does_not_reach_the_group_callback(
600        cx: &mut TestAppContext,
601    ) {
602        let (cx, child_clicks, changes) = toggle_group_harness(cx, true);
603        cx.update(|window, cx| window.focus_next(cx));
604        activate_key(cx, "enter");
605        assert_eq!(child_clicks.get(), 0);
606        assert!(changes.borrow().is_empty());
607    }
608
609    /// Three 60 px items with no gap, so the pointer reaches each of them at
610    /// a known x: the first is checked.
611    struct SelectionHarness {
612        single: bool,
613        changes: Rc<RefCell<Vec<Vec<bool>>>>,
614    }
615
616    impl Render for SelectionHarness {
617        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
618            let changes = self.changes.clone();
619            ToggleGroup::new("selection")
620                .segmented()
621                .when(self.single, ToggleGroup::single)
622                .child(Toggle::new("one").label("One").w(px(60.)).checked(true))
623                .child(Toggle::new("two").label("Two").w(px(60.)))
624                .child(Toggle::new("three").label("Three").w(px(60.)))
625                .on_click(move |next, _, _| changes.borrow_mut().push(next.clone()))
626        }
627    }
628
629    fn selection_harness(
630        cx: &mut TestAppContext,
631        single: bool,
632    ) -> (&mut VisualTestContext, Rc<RefCell<Vec<Vec<bool>>>>) {
633        cx.update(crate::init);
634        let changes = Rc::new(RefCell::new(Vec::new()));
635        let (_, cx) = cx.add_window_view({
636            let changes = changes.clone();
637            move |_, _| SelectionHarness { single, changes }
638        });
639        cx.update(|window, cx| window.draw(cx).clear(cx));
640        (cx, changes)
641    }
642
643    #[gpui::test]
644    fn single_toggle_group_moves_the_check_to_the_clicked_item(cx: &mut TestAppContext) {
645        let (cx, changes) = selection_harness(cx, true);
646        cx.simulate_click(point(px(90.), px(16.)), Modifiers::default());
647        assert_eq!(changes.borrow().as_slice(), &[vec![false, true, false]]);
648    }
649
650    #[gpui::test]
651    fn single_toggle_group_clears_the_checked_item_when_it_is_clicked(cx: &mut TestAppContext) {
652        let (cx, changes) = selection_harness(cx, true);
653        cx.simulate_click(point(px(30.), px(16.)), Modifiers::default());
654        assert_eq!(changes.borrow().as_slice(), &[vec![false, false, false]]);
655    }
656
657    #[gpui::test]
658    fn multi_toggle_group_keeps_the_other_checked_items(cx: &mut TestAppContext) {
659        let (cx, changes) = selection_harness(cx, false);
660        cx.simulate_click(point(px(90.), px(16.)), Modifiers::default());
661        assert_eq!(changes.borrow().as_slice(), &[vec![true, true, false]]);
662    }
663
664    /// Records the text color the toggle hands down to its content.
665    #[derive(IntoElement)]
666    struct ContentColor(Rc<Cell<Option<Hsla>>>);
667
668    impl RenderOnce for ContentColor {
669        fn render(self, window: &mut Window, _: &mut App) -> impl IntoElement {
670            self.0.set(Some(window.text_style().color));
671            div().w(px(40.)).h(px(16.))
672        }
673    }
674
675    /// A single group of two 60 px items that owns its selection; the first
676    /// item reports the text color it passes to its content.
677    struct ContentColorHarness {
678        checked: Option<usize>,
679        color: Rc<Cell<Option<Hsla>>>,
680    }
681
682    impl Render for ContentColorHarness {
683        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
684            ToggleGroup::new("selection")
685                .segmented()
686                .single()
687                .child(
688                    Toggle::new("one")
689                        .w(px(60.))
690                        .checked(self.checked == Some(0))
691                        .child(ContentColor(self.color.clone())),
692                )
693                .child(
694                    Toggle::new("two")
695                        .label("Two")
696                        .w(px(60.))
697                        .checked(self.checked == Some(1)),
698                )
699                .on_click(cx.listener(|this, next: &Vec<bool>, _, cx| {
700                    this.checked = next.iter().position(|checked| *checked);
701                    cx.notify();
702                }))
703        }
704    }
705
706    #[gpui::test]
707    fn an_item_unchecked_from_elsewhere_drops_its_hover_color(cx: &mut TestAppContext) {
708        let (foreground, accent_foreground) = cx.update(|cx| {
709            crate::init(cx);
710            let theme = Theme::global_mut(cx);
711            theme.foreground = gpui::black();
712            theme.accent_foreground = gpui::white();
713            (theme.foreground, theme.accent_foreground)
714        });
715        let color = Rc::new(Cell::new(None));
716        let (_, cx) = cx.add_window_view({
717            let color = color.clone();
718            move |_, _| ContentColorHarness {
719                checked: None,
720                color,
721            }
722        });
723        let draw = |cx: &mut VisualTestContext| cx.update(|window, cx| window.draw(cx).clear(cx));
724        draw(cx);
725        assert_eq!(color.get(), Some(foreground));
726
727        // Hover the first item and check it, then rest the pointer on the second.
728        cx.simulate_mouse_move(point(px(30.), px(16.)), None, Modifiers::default());
729        draw(cx);
730        assert_eq!(color.get(), Some(accent_foreground));
731        cx.simulate_click(point(px(30.), px(16.)), Modifiers::default());
732        draw(cx);
733        assert_eq!(color.get(), Some(accent_foreground));
734        cx.simulate_mouse_move(point(px(90.), px(16.)), None, Modifiers::default());
735        draw(cx);
736        assert_eq!(color.get(), Some(accent_foreground));
737
738        // Checking the second item unchecks the first while the pointer is
739        // elsewhere, so its content goes back to the plain foreground.
740        cx.simulate_click(point(px(90.), px(16.)), Modifiers::default());
741        draw(cx);
742        assert_eq!(color.get(), Some(foreground));
743    }
744
745    #[test]
746    fn instance_style_remains_the_final_visual_override() {
747        let toggle = Toggle::new("styled").checked(true).opacity(0.37);
748        assert_eq!(toggle.style.opacity, Some(0.37));
749    }
750
751    #[gpui::test]
752    fn test_toggle_builder(_cx: &mut gpui::TestAppContext) {
753        let toggle = Toggle::new("complex-toggle")
754            .label("Enable Feature")
755            .icon(IconName::Check)
756            .checked(true)
757            .outline()
758            .large()
759            .disabled(false)
760            .on_click(|_, _, _| {});
761
762        assert_eq!(toggle.children.len(), 2); // label + icon
763        assert!(toggle.checked);
764        assert_eq!(toggle.variant, ToggleVariant::Outline);
765        assert_eq!(toggle.size, Size::Large);
766        assert!(!toggle.disabled);
767        assert!(toggle.on_click.is_some());
768    }
769
770    #[gpui::test]
771    fn test_toggle_group_builder(_cx: &mut gpui::TestAppContext) {
772        let group = ToggleGroup::new("complex-group")
773            .child(Toggle::new("toggle1").label("Option 1"))
774            .child(Toggle::new("toggle2").label("Option 2").checked(true))
775            .child(Toggle::new("toggle3").label("Option 3"))
776            .outline()
777            .large()
778            .segmented()
779            .single()
780            .disabled(false)
781            .on_click(|_, _, _| {});
782
783        assert_eq!(group.items.len(), 3);
784        assert_eq!(group.variant, ToggleVariant::Outline);
785        assert_eq!(group.size, Size::Large);
786        assert!(group.segmented);
787        assert!(group.single);
788        assert!(!group.disabled);
789        assert!(group.on_click.is_some());
790    }
791}