gpui-component 0.9.1

GPUI Component: the styled component library of GPUI Kit, with 60+ desktop UI components for GPUI.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
use std::{cell::Cell, rc::Rc, time::Duration};

use gpui::{
    AnyElement, App, Axis, Corners, Edges, ElementId, InteractiveElement, IntoElement,
    ParentElement, RenderOnce, SharedString, StatefulInteractiveElement, StyleRefinement, Styled,
    Window, prelude::FluentBuilder as _, relative,
};
use gpui_base::{Toggle as BaseToggle, ToggleGroup as BaseToggleGroup};
use smallvec::{SmallVec, smallvec};

use crate::{ActiveTheme, Disableable, Icon, Sizable, Size, StyledExt, tooltip::ComponentTooltip};

#[derive(Default, Copy, Debug, Clone, PartialEq, Eq, Hash)]
pub enum ToggleVariant {
    #[default]
    Ghost,
    Outline,
}

pub trait ToggleVariants: Sized {
    /// Set the variant of the toggle.
    fn with_variant(self, variant: ToggleVariant) -> Self;
    /// Set the variant to ghost.
    fn ghost(self) -> Self {
        self.with_variant(ToggleVariant::Ghost)
    }
    /// Set the variant to outline.
    fn outline(self) -> Self {
        self.with_variant(ToggleVariant::Outline)
    }
}

#[derive(IntoElement)]
pub struct Toggle {
    id: ElementId,
    style: StyleRefinement,
    checked: bool,
    size: Size,
    variant: ToggleVariant,
    disabled: bool,
    border_corners: Corners<bool>,
    border_edges: Edges<bool>,
    children: SmallVec<[AnyElement; 1]>,
    on_click: Option<Box<dyn Fn(&bool, &mut Window, &mut App) + 'static>>,
    tooltip: ComponentTooltip,
}

impl Toggle {
    /// Create a new Toggle element.
    pub fn new(id: impl Into<ElementId>) -> Self {
        Self {
            id: id.into(),
            style: StyleRefinement::default(),
            checked: false,
            size: Size::default(),
            variant: ToggleVariant::default(),
            disabled: false,
            border_corners: Corners {
                top_left: true,
                top_right: true,
                bottom_left: true,
                bottom_right: true,
            },
            border_edges: Edges::all(true),
            children: smallvec![],
            on_click: None,
            tooltip: ComponentTooltip::default(),
        }
    }

    /// Set tooltip text for the toggle.
    pub fn tooltip(mut self, tooltip: impl Into<SharedString>) -> Self {
        self.tooltip.text = Some((tooltip.into(), None));
        self
    }

    /// Overrides how long the pointer must rest before the tooltip shows.
    ///
    /// Defaults to [`gpui_base::TooltipDefaults::show_delay`].
    pub fn tooltip_show_delay(mut self, delay: Duration) -> Self {
        self.tooltip.show_delay = Some(delay);
        self
    }

    /// Add a label to the toggle.
    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
        let label: SharedString = label.into();
        self.children.push(label.into_any_element());
        self
    }

    /// Add icon to the toggle.
    pub fn icon(mut self, icon: impl Into<Icon>) -> Self {
        let icon: Icon = icon.into();
        self.children.push(icon.into());
        self
    }

    /// Set the checked state of the toggle, default: false
    pub fn checked(mut self, checked: bool) -> Self {
        self.checked = checked;
        self
    }

    /// Set the callback to be called when the toggle is clicked.
    ///
    /// The `&bool` parameter represents the new checked state of the toggle.
    pub fn on_click(mut self, handler: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self {
        self.on_click = Some(Box::new(handler));
        self
    }

    pub(crate) fn border_corners(mut self, corners: impl Into<Corners<bool>>) -> Self {
        self.border_corners = corners.into();
        self
    }

    pub(crate) fn border_edges(mut self, edges: impl Into<Edges<bool>>) -> Self {
        self.border_edges = edges.into();
        self
    }
}

impl ToggleVariants for Toggle {
    fn with_variant(mut self, variant: ToggleVariant) -> Self {
        self.variant = variant;
        self
    }
}

impl ParentElement for Toggle {
    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
        self.children.extend(elements);
    }
}

impl Disableable for Toggle {
    fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }
}

impl Sizable for Toggle {
    fn with_size(mut self, size: impl Into<Size>) -> Self {
        self.size = size.into();
        self
    }
}

impl Styled for Toggle {
    fn style(&mut self) -> &mut StyleRefinement {
        &mut self.style
    }
}

impl RenderOnce for Toggle {
    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
        let checked = self.checked;
        let disabled = self.disabled;
        let hoverable = !disabled && !checked;
        let rounding = cx.theme().radius;
        let pressed_background = cx.theme().tokens.accent;
        let pressed_foreground = cx.theme().accent_foreground;
        let instance_style = self.style.clone();

        BaseToggle::new(self.id)
            .pressed(checked)
            .disabled(disabled)
            .when_some(
                self.tooltip.text.as_ref().map(|(text, _)| text.clone()),
                |this, label| this.accessibility_label(label),
            )
            .when_some(self.on_click, |this, on_click| {
                this.on_change(move |next, _, window, cx| on_click(&next, window, cx))
            })
            .flex()
            .flex_row()
            .line_height(relative(1.25))
            .items_center()
            .justify_center()
            .map(|this| match self.size {
                Size::XSmall => this.min_w_5().h_5().px_0p5().text_xs(),
                Size::Small => this.min_w_6().h_6().px_1().text_sm(),
                Size::Large => this.min_w_9().h_9().px_3().text_base(),
                _ => this.min_w_8().h_8().px_2().text_sm(),
            })
            .when(self.border_corners.top_left, |this| {
                this.rounded_tl(rounding)
            })
            .when(self.border_corners.top_right, |this| {
                this.rounded_tr(rounding)
            })
            .when(self.border_corners.bottom_left, |this| {
                this.rounded_bl(rounding)
            })
            .when(self.border_corners.bottom_right, |this| {
                this.rounded_br(rounding)
            })
            .when(self.variant == ToggleVariant::Outline, |this| {
                this.when(self.border_edges.left, |this| this.border_l_1())
                    .when(self.border_edges.right, |this| this.border_r_1())
                    .when(self.border_edges.top, |this| this.border_t_1())
                    .when(self.border_edges.bottom, |this| this.border_b_1())
                    .border_color(cx.theme().border)
                    .bg(cx.theme().tokens.background)
            })
            // Always register the hover style: GPUI only refreshes the cached
            // hover state while one is present. If a checked toggle skipped it,
            // the stale state would paint its label in the hover color once
            // something else unchecks it while the pointer rests elsewhere.
            .hover(|this| {
                if !hoverable {
                    return this;
                }
                this.bg(cx.theme().tokens.accent)
                    .text_color(cx.theme().accent_foreground)
            })
            .styles(|styles| {
                styles.pressed(|style| {
                    style
                        .bg(pressed_background)
                        .text_color(pressed_foreground)
                        .refine_style(&instance_style)
                })
            })
            .refine_style(&self.style)
            .children(self.children)
            .map(|this| self.tooltip.apply(this))
    }
}

/// A group of toggles.
#[derive(IntoElement)]
pub struct ToggleGroup {
    id: ElementId,
    style: StyleRefinement,
    size: Size,
    variant: ToggleVariant,
    disabled: bool,
    segmented: bool,
    single: bool,
    items: Vec<Toggle>,
    on_click: Option<Rc<dyn Fn(&Vec<bool>, &mut Window, &mut App) + 'static>>,
}

impl ToggleGroup {
    /// Create a new ToggleGroup element.
    pub fn new(id: impl Into<ElementId>) -> Self {
        Self {
            id: id.into(),
            style: StyleRefinement::default(),
            size: Size::default(),
            variant: ToggleVariant::default(),
            disabled: false,
            segmented: false,
            single: false,
            items: Vec::new(),
            on_click: None,
        }
    }

    /// Add a child [`Toggle`] to the group.
    pub fn child(mut self, toggle: impl Into<Toggle>) -> Self {
        self.items.push(toggle.into());
        self
    }

    /// Add multiple [`Toggle`]s to the group.
    pub fn children(mut self, children: impl IntoIterator<Item = impl Into<Toggle>>) -> Self {
        self.items.extend(children.into_iter().map(Into::into));
        self
    }

    /// Set the callback to be called when the toggle group changes.
    ///
    /// The `&Vec<bool>` parameter represents the new check state of each [`Toggle`] in the group.
    /// In a [`single`](Self::single) group at most one of them is `true`.
    pub fn on_click(
        mut self,
        on_click: impl Fn(&Vec<bool>, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_click = Some(Rc::new(on_click));
        self
    }

    /// Render the group as a connected segmented control.
    ///
    /// This only changes the look: it removes the default gap and joins
    /// adjacent item borders into a single segmented outline. Pair it with
    /// [`single`](Self::single) for an exclusive choice.
    pub fn segmented(mut self) -> Self {
        self.segmented = true;
        self
    }

    /// Let at most one item be checked at a time.
    ///
    /// A click on an unchecked item checks it and clears the others. A click
    /// on the checked item clears it, so the group can also hold no selection.
    /// The caller keeps at most one item `checked`; the group does not
    /// reconcile a state in which several are.
    pub fn single(mut self) -> Self {
        self.single = true;
        self
    }
}

impl Sizable for ToggleGroup {
    fn with_size(mut self, size: impl Into<Size>) -> Self {
        self.size = size.into();
        self
    }
}

impl ToggleVariants for ToggleGroup {
    fn with_variant(mut self, variant: ToggleVariant) -> Self {
        self.variant = variant;
        self
    }
}

impl Disableable for ToggleGroup {
    fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }
}

impl Styled for ToggleGroup {
    fn style(&mut self) -> &mut StyleRefinement {
        &mut self.style
    }
}

impl RenderOnce for ToggleGroup {
    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
        let disabled = self.disabled;
        let single = self.single;
        let items_len = self.items.len();
        let checks = self
            .items
            .iter()
            .map(|item| item.checked)
            .collect::<Vec<bool>>();
        let clicked_index = Rc::new(Cell::new(None));

        BaseToggleGroup::new(self.id)
            .axis(Axis::Horizontal)
            .child(
                crate::h_flex()
                    .items_center()
                    .when(!self.segmented, |this| this.gap_2())
                    .refine_style(&self.style)
                    .children(self.items.into_iter().enumerate().map({
                        {
                            let clicked_index = clicked_index.clone();
                            move |(ix, item)| {
                                let item = if !self.segmented || items_len == 1 {
                                    item
                                } else if ix == 0 {
                                    item.border_corners(Corners {
                                        top_left: true,
                                        top_right: false,
                                        bottom_left: true,
                                        bottom_right: false,
                                    })
                                    .border_edges(Edges {
                                        left: true,
                                        top: true,
                                        right: true,
                                        bottom: true,
                                    })
                                } else if ix == items_len - 1 {
                                    item.border_corners(Corners {
                                        top_left: false,
                                        top_right: true,
                                        bottom_left: false,
                                        bottom_right: true,
                                    })
                                    .border_edges(Edges {
                                        left: false,
                                        top: true,
                                        right: true,
                                        bottom: true,
                                    })
                                } else {
                                    item.border_corners(Corners {
                                        top_left: false,
                                        top_right: false,
                                        bottom_left: false,
                                        bottom_right: false,
                                    })
                                    .border_edges(Edges {
                                        left: false,
                                        top: true,
                                        right: true,
                                        bottom: true,
                                    })
                                };

                                let effective_disabled = disabled || item.disabled;
                                let clicked_index = clicked_index.clone();
                                item.disabled(effective_disabled)
                                    .with_size(self.size)
                                    .with_variant(self.variant)
                                    .on_click(move |_, _, cx| {
                                        clicked_index.set(Some(ix));
                                        cx.propagate();
                                    })
                            }
                        }
                    })),
            )
            .when_some(
                (!disabled).then_some(self.on_click).flatten(),
                |this, on_click| {
                    this.on_click(move |_, window, cx| {
                        let Some(ix) = clicked_index.take() else {
                            return;
                        };
                        // A single group clears every other item; clicking its
                        // checked item still flips that one off.
                        let mut next = if single {
                            vec![false; checks.len()]
                        } else {
                            checks.clone()
                        };
                        next[ix] = !checks[ix];
                        on_click(&next, window, cx);
                    })
                },
            )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{IconName, Theme, h_flex};
    use gpui::{
        Context, Hsla, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, Render,
        StatefulInteractiveElement, TestAppContext, VisualTestContext, div, point, px,
    };
    use std::cell::{Cell, RefCell};

    struct ToggleHarness {
        disabled: bool,
        changes: Rc<RefCell<Vec<bool>>>,
        parent_clicks: Rc<Cell<usize>>,
    }

    impl Render for ToggleHarness {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            let changes = self.changes.clone();
            let parent_clicks = self.parent_clicks.clone();
            h_flex()
                .id("toggle-parent")
                .tab_group()
                .size(px(100.))
                .on_click(move |_, _, _| parent_clicks.set(parent_clicks.get() + 1))
                .child(
                    Toggle::new("toggle")
                        .label("Bold")
                        .disabled(self.disabled)
                        .size_full()
                        .on_click(move |next, _, _| changes.borrow_mut().push(*next)),
                )
        }
    }

    fn harness(
        cx: &mut TestAppContext,
        disabled: bool,
    ) -> (
        &mut VisualTestContext,
        Rc<RefCell<Vec<bool>>>,
        Rc<Cell<usize>>,
    ) {
        cx.update(crate::init);
        let changes = Rc::new(RefCell::new(Vec::new()));
        let parent_clicks = Rc::new(Cell::new(0));
        let (_, cx) = cx.add_window_view({
            let changes = changes.clone();
            let parent_clicks = parent_clicks.clone();
            move |_, _| ToggleHarness {
                disabled,
                changes,
                parent_clicks,
            }
        });
        cx.update(|window, cx| window.draw(cx).clear(cx));
        (cx, changes, parent_clicks)
    }

    fn activate_key(cx: &mut VisualTestContext, key: &str) {
        let keystroke =
            cx.update(|_, cx| Keystroke::parse_with_os(key, cx.platform_info().os).unwrap());
        cx.simulate_event(KeyDownEvent {
            keystroke: keystroke.clone(),
            is_held: false,
            prefer_character_input: false,
        });
        cx.simulate_event(KeyUpEvent { keystroke });
    }

    #[gpui::test]
    fn canonical_pointer_activation_fires_once_and_focuses(cx: &mut TestAppContext) {
        let (cx, changes, _) = harness(cx, false);
        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
        assert_eq!(changes.borrow().as_slice(), &[true]);
        cx.update(|window, cx| assert!(window.focused(cx).is_some()));
    }

    #[gpui::test]
    fn canonical_toggle_supports_tab_enter_and_space(cx: &mut TestAppContext) {
        let (cx, changes, _) = harness(cx, false);
        cx.update(|window, cx| window.focus_next(cx));
        cx.update(|window, cx| assert!(window.focused(cx).is_some()));
        activate_key(cx, "enter");
        activate_key(cx, "space");
        assert_eq!(changes.borrow().as_slice(), &[true, true]);
    }

    #[gpui::test]
    fn canonical_disabled_toggle_is_inert_and_blocks_parent(cx: &mut TestAppContext) {
        let (cx, changes, parent_clicks) = harness(cx, true);
        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
        assert!(changes.borrow().is_empty());
        assert_eq!(parent_clicks.get(), 0);
    }

    struct ToggleGroupHarness {
        install_group_callback: bool,
        child_clicks: Rc<Cell<usize>>,
        group_changes: Rc<RefCell<Vec<Vec<bool>>>>,
    }

    impl Render for ToggleGroupHarness {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            let child_clicks = self.child_clicks.clone();
            let mut group = ToggleGroup::new("toggle-group")
                .w(px(120.))
                .child(
                    Toggle::new("one")
                        .label("One")
                        .checked(true)
                        .on_click(move |_, _, _| child_clicks.set(child_clicks.get() + 1)),
                )
                .child(Toggle::new("two").label("Two"));
            if self.install_group_callback {
                let changes = self.group_changes.clone();
                group = group.on_click(move |next, _, _| changes.borrow_mut().push(next.clone()));
            }
            group
        }
    }

    fn toggle_group_harness(
        cx: &mut TestAppContext,
        install_group_callback: bool,
    ) -> (
        &mut VisualTestContext,
        Rc<Cell<usize>>,
        Rc<RefCell<Vec<Vec<bool>>>>,
    ) {
        cx.update(crate::init);
        let child_clicks = Rc::new(Cell::new(0));
        let group_changes = Rc::new(RefCell::new(Vec::new()));
        let (_, cx) = cx.add_window_view({
            let child_clicks = child_clicks.clone();
            let group_changes = group_changes.clone();
            move |_, _| ToggleGroupHarness {
                install_group_callback,
                child_clicks,
                group_changes,
            }
        });
        cx.update(|window, cx| window.draw(cx).clear(cx));
        (cx, child_clicks, group_changes)
    }

    #[gpui::test]
    fn legacy_toggle_group_overrides_child_callback_even_without_group_callback(
        cx: &mut TestAppContext,
    ) {
        let (cx, child_clicks, changes) = toggle_group_harness(cx, false);
        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
        assert_eq!(child_clicks.get(), 0);
        assert!(changes.borrow().is_empty());
    }

    #[gpui::test]
    fn legacy_toggle_group_pointer_flips_only_the_clicked_rendered_value(cx: &mut TestAppContext) {
        let (cx, child_clicks, changes) = toggle_group_harness(cx, true);
        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
        assert_eq!(child_clicks.get(), 0);
        assert_eq!(changes.borrow().as_slice(), &[vec![false, false]]);
    }

    #[gpui::test]
    fn legacy_toggle_group_keyboard_click_does_not_reach_the_group_callback(
        cx: &mut TestAppContext,
    ) {
        let (cx, child_clicks, changes) = toggle_group_harness(cx, true);
        cx.update(|window, cx| window.focus_next(cx));
        activate_key(cx, "enter");
        assert_eq!(child_clicks.get(), 0);
        assert!(changes.borrow().is_empty());
    }

    /// Three 60 px items with no gap, so the pointer reaches each of them at
    /// a known x: the first is checked.
    struct SelectionHarness {
        single: bool,
        changes: Rc<RefCell<Vec<Vec<bool>>>>,
    }

    impl Render for SelectionHarness {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            let changes = self.changes.clone();
            ToggleGroup::new("selection")
                .segmented()
                .when(self.single, ToggleGroup::single)
                .child(Toggle::new("one").label("One").w(px(60.)).checked(true))
                .child(Toggle::new("two").label("Two").w(px(60.)))
                .child(Toggle::new("three").label("Three").w(px(60.)))
                .on_click(move |next, _, _| changes.borrow_mut().push(next.clone()))
        }
    }

    fn selection_harness(
        cx: &mut TestAppContext,
        single: bool,
    ) -> (&mut VisualTestContext, Rc<RefCell<Vec<Vec<bool>>>>) {
        cx.update(crate::init);
        let changes = Rc::new(RefCell::new(Vec::new()));
        let (_, cx) = cx.add_window_view({
            let changes = changes.clone();
            move |_, _| SelectionHarness { single, changes }
        });
        cx.update(|window, cx| window.draw(cx).clear(cx));
        (cx, changes)
    }

    #[gpui::test]
    fn single_toggle_group_moves_the_check_to_the_clicked_item(cx: &mut TestAppContext) {
        let (cx, changes) = selection_harness(cx, true);
        cx.simulate_click(point(px(90.), px(16.)), Modifiers::default());
        assert_eq!(changes.borrow().as_slice(), &[vec![false, true, false]]);
    }

    #[gpui::test]
    fn single_toggle_group_clears_the_checked_item_when_it_is_clicked(cx: &mut TestAppContext) {
        let (cx, changes) = selection_harness(cx, true);
        cx.simulate_click(point(px(30.), px(16.)), Modifiers::default());
        assert_eq!(changes.borrow().as_slice(), &[vec![false, false, false]]);
    }

    #[gpui::test]
    fn multi_toggle_group_keeps_the_other_checked_items(cx: &mut TestAppContext) {
        let (cx, changes) = selection_harness(cx, false);
        cx.simulate_click(point(px(90.), px(16.)), Modifiers::default());
        assert_eq!(changes.borrow().as_slice(), &[vec![true, true, false]]);
    }

    /// Records the text color the toggle hands down to its content.
    #[derive(IntoElement)]
    struct ContentColor(Rc<Cell<Option<Hsla>>>);

    impl RenderOnce for ContentColor {
        fn render(self, window: &mut Window, _: &mut App) -> impl IntoElement {
            self.0.set(Some(window.text_style().color));
            div().w(px(40.)).h(px(16.))
        }
    }

    /// A single group of two 60 px items that owns its selection; the first
    /// item reports the text color it passes to its content.
    struct ContentColorHarness {
        checked: Option<usize>,
        color: Rc<Cell<Option<Hsla>>>,
    }

    impl Render for ContentColorHarness {
        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            ToggleGroup::new("selection")
                .segmented()
                .single()
                .child(
                    Toggle::new("one")
                        .w(px(60.))
                        .checked(self.checked == Some(0))
                        .child(ContentColor(self.color.clone())),
                )
                .child(
                    Toggle::new("two")
                        .label("Two")
                        .w(px(60.))
                        .checked(self.checked == Some(1)),
                )
                .on_click(cx.listener(|this, next: &Vec<bool>, _, cx| {
                    this.checked = next.iter().position(|checked| *checked);
                    cx.notify();
                }))
        }
    }

    #[gpui::test]
    fn an_item_unchecked_from_elsewhere_drops_its_hover_color(cx: &mut TestAppContext) {
        let (foreground, accent_foreground) = cx.update(|cx| {
            crate::init(cx);
            let theme = Theme::global_mut(cx);
            theme.foreground = gpui::black();
            theme.accent_foreground = gpui::white();
            (theme.foreground, theme.accent_foreground)
        });
        let color = Rc::new(Cell::new(None));
        let (_, cx) = cx.add_window_view({
            let color = color.clone();
            move |_, _| ContentColorHarness {
                checked: None,
                color,
            }
        });
        let draw = |cx: &mut VisualTestContext| cx.update(|window, cx| window.draw(cx).clear(cx));
        draw(cx);
        assert_eq!(color.get(), Some(foreground));

        // Hover the first item and check it, then rest the pointer on the second.
        cx.simulate_mouse_move(point(px(30.), px(16.)), None, Modifiers::default());
        draw(cx);
        assert_eq!(color.get(), Some(accent_foreground));
        cx.simulate_click(point(px(30.), px(16.)), Modifiers::default());
        draw(cx);
        assert_eq!(color.get(), Some(accent_foreground));
        cx.simulate_mouse_move(point(px(90.), px(16.)), None, Modifiers::default());
        draw(cx);
        assert_eq!(color.get(), Some(accent_foreground));

        // Checking the second item unchecks the first while the pointer is
        // elsewhere, so its content goes back to the plain foreground.
        cx.simulate_click(point(px(90.), px(16.)), Modifiers::default());
        draw(cx);
        assert_eq!(color.get(), Some(foreground));
    }

    #[test]
    fn instance_style_remains_the_final_visual_override() {
        let toggle = Toggle::new("styled").checked(true).opacity(0.37);
        assert_eq!(toggle.style.opacity, Some(0.37));
    }

    #[gpui::test]
    fn test_toggle_builder(_cx: &mut gpui::TestAppContext) {
        let toggle = Toggle::new("complex-toggle")
            .label("Enable Feature")
            .icon(IconName::Check)
            .checked(true)
            .outline()
            .large()
            .disabled(false)
            .on_click(|_, _, _| {});

        assert_eq!(toggle.children.len(), 2); // label + icon
        assert!(toggle.checked);
        assert_eq!(toggle.variant, ToggleVariant::Outline);
        assert_eq!(toggle.size, Size::Large);
        assert!(!toggle.disabled);
        assert!(toggle.on_click.is_some());
    }

    #[gpui::test]
    fn test_toggle_group_builder(_cx: &mut gpui::TestAppContext) {
        let group = ToggleGroup::new("complex-group")
            .child(Toggle::new("toggle1").label("Option 1"))
            .child(Toggle::new("toggle2").label("Option 2").checked(true))
            .child(Toggle::new("toggle3").label("Option 3"))
            .outline()
            .large()
            .segmented()
            .single()
            .disabled(false)
            .on_click(|_, _, _| {});

        assert_eq!(group.items.len(), 3);
        assert_eq!(group.variant, ToggleVariant::Outline);
        assert_eq!(group.size, Size::Large);
        assert!(group.segmented);
        assert!(group.single);
        assert!(!group.disabled);
        assert!(group.on_click.is_some());
    }
}