gpui-m3 0.2.4

Material 3 Expressive components for GPUI: shape morphing, spring motion and dynamic color
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
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
use std::f32::consts::TAU;
use std::rc::Rc;

use gpui::prelude::FluentBuilder as _;

use gpui::{
    AnyElement, App, ClickEvent, ElementId, FontWeight, Hsla, InteractiveElement, IntoElement,
    MouseButton, ParentElement, Pixels, RenderOnce, SharedString, StatefulInteractiveElement,
    Styled, Window, div, px,
};

use super::{ButtonVariant, ClickHandler, Icon, RoundedExt, all};
use crate::interaction::{interactive, keyboard_focus, state_layer, use_interaction};
use crate::motion::{Spring, animate_color, animate_f32, continuous_at, entrance, key};
use crate::shapes::Tone;
use crate::theme::{MONO_FONT_FAMILY, Scheme, Theme, alpha, font_family};

#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum ChipKind {
    /// Outlined (actions and suggestions).
    #[default]
    Assist,
    /// Filled with the primary container (the project chip in the reference design).
    Filled,
    /// Toggleable: when activated it goes from 8 px corners to a pill and fills in.
    Filter,
    /// Outlined, with a trailing "x" that calls [`Chip::on_remove`] (attachments, tags).
    Input,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum ChipSize {
    /// 24 px (tool cards, inline actions).
    Small,
    /// 32 px.
    #[default]
    Medium,
}

/// 32 px chip with 8 px corners (per M3). It rounds with the spring on press.
#[derive(IntoElement)]
pub struct Chip {
    id: ElementId,
    label: SharedString,
    sublabel: Option<SharedString>,
    icon: Option<SharedString>,
    leading: Option<AnyElement>,
    trailing: Option<AnyElement>,
    kind: ChipKind,
    tone: Option<Tone>,
    size: ChipSize,
    selected: bool,
    show_check: bool,
    open: Option<bool>,
    muted: bool,
    mono: bool,
    inert: bool,
    pulse_icon: bool,
    danger: bool,
    max_width: Option<Pixels>,
    on_click: Option<ClickHandler>,
    on_remove: Option<ClickHandler>,
}

impl Chip {
    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            sublabel: None,
            icon: None,
            leading: None,
            trailing: None,
            kind: ChipKind::Assist,
            tone: None,
            size: ChipSize::Medium,
            selected: false,
            show_check: true,
            open: None,
            muted: false,
            mono: false,
            inert: false,
            pulse_icon: false,
            danger: false,
            max_width: None,
            on_click: None,
            on_remove: None,
        }
    }

    /// Input chip: outlined, with a trailing "x" (see [`Chip::on_remove`]).
    pub fn input(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
        Self::new(id, label).kind(ChipKind::Input)
    }

    pub fn icon(mut self, icon: impl Into<SharedString>) -> Self {
        self.icon = Some(icon.into());
        self
    }

    /// Leading element instead of the icon (a color dot, an [`super::Avatar`]…).
    pub fn leading(mut self, el: impl IntoElement) -> Self {
        self.leading = Some(el.into_any_element());
        self
    }

    /// Element after the label (e.g. a small chevron for a picker).
    pub fn trailing(mut self, el: impl IntoElement) -> Self {
        self.trailing = Some(el.into_any_element());
        self
    }

    /// Picker chip: adds a trailing chevron that turns over while `open`.
    pub fn open(mut self, open: bool) -> Self {
        self.open = Some(open);
        self
    }

    /// Secondary text after the label, in the outline color (e.g. ":12-30" line ranges).
    pub fn sublabel(mut self, sublabel: impl Into<SharedString>) -> Self {
        self.sublabel = Some(sublabel.into());
        self
    }

    pub fn kind(mut self, kind: ChipKind) -> Self {
        self.kind = kind;
        self
    }

    pub fn filled(self) -> Self {
        self.kind(ChipKind::Filled)
    }

    /// Toggleable chip with its state.
    pub fn filter(mut self, selected: bool) -> Self {
        self.kind = ChipKind::Filter;
        self.selected = selected;
        self
    }

    /// Fills the chip with a tonal container and drops the border (permission mode, files).
    pub fn tone(mut self, tone: Tone) -> Self {
        self.tone = Some(tone);
        self
    }

    pub fn size(mut self, size: ChipSize) -> Self {
        self.size = size;
        self
    }

    /// Whether a selected filter chip replaces its icon with a check (default `true`).
    pub fn show_check(mut self, show: bool) -> Self {
        self.show_check = show;
        self
    }

    /// Text and icon in the variant color (secondary information such as the branch).
    pub fn muted(mut self, muted: bool) -> Self {
        self.muted = muted;
        self
    }

    /// Label in the monospace font.
    pub fn mono(mut self, mono: bool) -> Self {
        self.mono = mono;
        self
    }

    /// Display-only chip: no hover, ripple or pointer cursor.
    pub fn inert(mut self, inert: bool) -> Self {
        self.inert = inert;
        self
    }

    /// The icon pulses (opacity 1 → 0.45 → 1 every 1.4 s), e.g. while agents are running.
    pub fn pulse_icon(mut self, pulse: bool) -> Self {
        self.pulse_icon = pulse;
        self
    }

    /// Destructive or failed: the error container with its content color, without a border
    /// (a selected filter chip keeps its selected look).
    pub fn danger(mut self, danger: bool) -> Self {
        self.danger = danger;
        self
    }

    /// Maximum width; the label is truncated with an ellipsis.
    pub fn max_w(mut self, max_width: Pixels) -> Self {
        self.max_width = Some(max_width);
        self
    }

    pub fn on_click(mut self, f: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static) -> Self {
        self.on_click = Some(Rc::new(f));
        self
    }

    /// Called by the "x" of an input chip.
    pub fn on_remove(mut self, f: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static) -> Self {
        self.on_remove = Some(Rc::new(f));
        self
    }
}

impl RenderOnce for Chip {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let s = *Theme::of(cx);
        let reactive = !self.inert;
        let state = use_interaction(&self.id, window, cx);
        let pressed = state.read(cx).pressed && reactive;
        let on = self.kind == ChipKind::Filter && self.selected;
        // (height, text size, icon size, gap, side padding)
        let (height, text_size, icon_size, gap, pad) = match self.size {
            ChipSize::Small => (24., 12., 13., 5., 8.),
            ChipSize::Medium => (32., 12.5, 16., 7., 12.),
        };

        let radius = match (pressed, on) {
            (true, _) | (false, true) => height / 2.,
            (false, false) => 8.,
        };
        let radius = px(animate_f32(
            key(&self.id, "radius"),
            Spring::SPATIAL_FAST,
            radius,
            window,
            cx,
        ));
        // Press shrink (scale 0.96 in the reference design): approximated by reducing the height.
        let shrink = animate_f32(
            key(&self.id, "shrink"),
            Spring::SPATIAL_FAST,
            if pressed { 1. } else { 0. },
            window,
            cx,
        );

        let (bg, fg, border, icon_color, weight) = match (self.kind, self.tone) {
            (ChipKind::Filter, _) if on => (
                s.primary_container,
                s.on_primary_container,
                alpha(s.outline_variant, 0.),
                s.on_primary_container,
                600.,
            ),
            _ if self.danger => (
                s.error_container,
                s.on_error_container,
                alpha(s.error_container, 0.),
                s.on_error_container,
                600.,
            ),
            (_, Some(tone)) => {
                let (bg, fg) = tone.colors(&s);
                (bg, fg, alpha(bg, 0.), fg, 500.)
            }
            (ChipKind::Assist | ChipKind::Input, None) => (
                alpha(s.surface, 0.),
                s.on_surface,
                s.outline_variant,
                s.primary,
                500.,
            ),
            (ChipKind::Filled, None) => (
                s.primary_container,
                s.on_primary_container,
                alpha(s.primary_container, 0.),
                s.on_primary_container,
                600.,
            ),
            (ChipKind::Filter, None) => (
                alpha(s.surface, 0.),
                s.on_surface_variant,
                s.outline_variant,
                s.on_surface_variant,
                500.,
            ),
        };
        let (fg, icon_color) = if self.muted && !on && !self.danger {
            (s.on_surface_variant, s.on_surface_variant)
        } else {
            (fg, icon_color)
        };
        let bg = animate_color(key(&self.id, "bg"), Spring::EFFECTS, bg, window, cx);
        let fg = animate_color(key(&self.id, "fg"), Spring::EFFECTS, fg, window, cx);
        let border = animate_color(key(&self.id, "border"), Spring::EFFECTS, border, window, cx);
        let icon_color = animate_color(
            key(&self.id, "icon"),
            Spring::EFFECTS,
            icon_color,
            window,
            cx,
        );
        let icon_color = if self.pulse_icon {
            let t = continuous_at(30., window, cx);
            alpha(icon_color, 0.725 + 0.275 * (t / 1.4 * TAU).cos())
        } else {
            icon_color
        };
        let layer = state_layer(&self.id, &state, all(radius), fg, window, cx);

        let has_leading = self.icon.is_some() || self.leading.is_some() || on;
        let mut face = div()
            .relative()
            .flex()
            .items_center()
            .gap(px(gap))
            .h(px(height - shrink * 2.))
            .pl(px(if has_leading { pad - 4. } else { pad }))
            .pr(px(if self.kind == ChipKind::Input {
                4.
            } else {
                pad
            }))
            .corners(all(radius))
            .bg(bg)
            .border_1()
            .border_color(border)
            .text_color(fg)
            .font_family(font_family())
            .text_size(px(text_size))
            .font_weight(FontWeight(weight))
            .when_some(self.max_width, |d, w| d.max_w(w))
            .child(layer);
        if on && self.show_check {
            face = face.child(Icon::new("check").size(px(icon_size)).color(fg));
        } else if let Some(leading) = self.leading {
            face = face.child(leading);
        } else if let Some(icon) = self.icon {
            let color = if on { fg } else { icon_color };
            face = face.child(Icon::new(icon).size(px(icon_size)).color(color));
        }
        let truncate = self.max_width.is_some();
        let label = div()
            .flex()
            .items_baseline()
            .whitespace_nowrap()
            .when(truncate, |d| d.min_w_0().overflow_hidden())
            .when(!truncate, |d| d.flex_none())
            .when(self.mono, |d| {
                d.font_family(MONO_FONT_FAMILY)
                    .font_weight(FontWeight(400.))
            })
            .child(
                div()
                    .when(truncate, |d| d.min_w_0().overflow_hidden().text_ellipsis())
                    .child(self.label),
            )
            .children(
                self.sublabel
                    .map(|sub| div().flex_none().text_color(s.outline).child(sub)),
            );
        face = face.child(label);
        if let Some(trailing) = self.trailing {
            face = face.child(div().flex_none().child(trailing));
        }
        if let Some(open) = self.open {
            let rotation = animate_f32(
                key(&self.id, "chevron"),
                Spring::SPATIAL,
                if open { std::f32::consts::PI } else { 0. },
                window,
                cx,
            );
            face = face.child(
                Icon::new("chevron-down")
                    .size(px(12.))
                    .color(fg)
                    .rotate(rotation),
            );
        }
        if self.kind == ChipKind::Input {
            let remove_id = super::child_id(&self.id, "remove");
            let remove_state = use_interaction(&remove_id, window, cx);
            let remove_layer = state_layer(&remove_id, &remove_state, all(px(9.)), fg, window, cx);
            let remove = div()
                .id(remove_id)
                .relative()
                .flex()
                .flex_none()
                .items_center()
                .justify_center()
                .size(px(18.))
                .mr(px(2.))
                .rounded(px(9.))
                .child(remove_layer)
                .child(Icon::new("x").size(px(12.)).color(s.on_surface_variant))
                // Keeps the press from also rippling the whole chip.
                .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation());
            let mut remove = interactive(remove, &remove_state, true, true);
            if let Some(f) = self.on_remove {
                remove = remove.on_click(move |e, w, cx| {
                    cx.stop_propagation();
                    f(e, w, cx)
                });
            }
            face = face.child(remove);
        }

        let el = div()
            .id(self.id.clone())
            .flex()
            .flex_none()
            .items_center()
            .h(px(height))
            .when_some(self.max_width, |d, w| d.max_w(w))
            .child(face);
        let mut el = interactive(el, &state, reactive, reactive);
        if let (Some(f), true) = (self.on_click, reactive) {
            el = el.on_click(move |e, w, cx| f(e, w, cx));
        }
        el
    }
}

/// Split button (the model picker in the reference design): a main action and a trailing button
/// that, when open, becomes a circle in a stronger color and rotates its arrow.
///
/// Tonal by default; [`SplitButton::filled`], [`SplitButton::outlined`] and
/// [`SplitButton::variant`] change the colors. [`SplitButton::menu`] draws its menu under it
/// while [`open`](SplitButton::open); the open state stays yours.
#[derive(IntoElement)]
pub struct SplitButton {
    id: ElementId,
    label: SharedString,
    sublabel: Option<SharedString>,
    icon: Option<SharedString>,
    variant: ButtonVariant,
    open: bool,
    autofocus: bool,
    menu: Option<Vec<AnyElement>>,
    menu_width: f32,
    on_click: Option<ClickHandler>,
    on_toggle: Option<ClickHandler>,
    on_dismiss: Option<ClickHandler>,
}

impl SplitButton {
    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            sublabel: None,
            icon: None,
            variant: ButtonVariant::Tonal,
            open: false,
            autofocus: false,
            menu: None,
            menu_width: 240.,
            on_click: None,
            on_toggle: None,
            on_dismiss: None,
        }
    }

    /// Secondary text next to the label (e.g. the effort level).
    pub fn sublabel(mut self, sublabel: impl Into<SharedString>) -> Self {
        self.sublabel = Some(sublabel.into());
        self
    }

    /// Icon before the label.
    pub fn icon(mut self, icon: impl Into<SharedString>) -> Self {
        self.icon = Some(icon.into());
        self
    }

    /// Filled, tonal (the default) or outlined. Text and ghost are drawn as text buttons.
    pub fn variant(mut self, variant: ButtonVariant) -> Self {
        self.variant = variant;
        self
    }

    /// The primary color, for the main action of a view.
    pub fn filled(self) -> Self {
        self.variant(ButtonVariant::Filled)
    }

    pub fn outlined(self) -> Self {
        self.variant(ButtonVariant::Outlined)
    }

    pub fn open(mut self, open: bool) -> Self {
        self.open = open;
        self
    }

    /// Makes both halves Tab stops with a focus ring, and the main action takes the keyboard
    /// focus the first time it appears (never again after that). Without it the halves are
    /// not Tab stops, as before 0.2.1.
    pub fn autofocus(mut self, autofocus: bool) -> Self {
        self.autofocus = autofocus;
        self
    }

    /// The items of its menu (usually [`super::MenuItem`]s), drawn under the button over the
    /// rest of the window while it is [`open`](SplitButton::open). A press outside the menu and
    /// the button calls [`SplitButton::on_dismiss`].
    pub fn menu(mut self, items: impl IntoIterator<Item = impl IntoElement>) -> Self {
        self.menu = Some(items.into_iter().map(IntoElement::into_any_element).collect());
        self
    }

    /// Width of the [`menu`](SplitButton::menu) (240 px by default).
    pub fn menu_width(mut self, width: f32) -> Self {
        self.menu_width = width;
        self
    }

    pub fn on_click(mut self, f: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static) -> Self {
        self.on_click = Some(Rc::new(f));
        self
    }

    pub fn on_toggle(mut self, f: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static) -> Self {
        self.on_toggle = Some(Rc::new(f));
        self
    }

    /// Called on a press outside the open menu and outside the button (to close it).
    pub fn on_dismiss(mut self, f: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static) -> Self {
        self.on_dismiss = Some(Rc::new(f));
        self
    }
}

/// Colors of a split button: main container and content, the trailing button's container and
/// content (closed and open), and the outline.
struct SplitColors {
    main: (Hsla, Hsla),
    trail: (Hsla, Hsla),
    trail_open: (Hsla, Hsla),
    border: Option<Hsla>,
}

fn split_colors(s: &Scheme, variant: ButtonVariant) -> SplitColors {
    match variant {
        ButtonVariant::Filled => SplitColors {
            main: (s.primary, s.on_primary),
            trail: (s.primary, s.on_primary),
            trail_open: (s.primary_container, s.on_primary_container),
            border: None,
        },
        ButtonVariant::Outlined => SplitColors {
            main: (alpha(s.surface, 0.), s.on_surface_variant),
            trail: (alpha(s.surface, 0.), s.on_surface_variant),
            trail_open: (s.secondary_container, s.on_secondary_container),
            border: Some(s.outline_variant),
        },
        ButtonVariant::Text | ButtonVariant::Ghost => SplitColors {
            main: (alpha(s.surface, 0.), s.primary),
            trail: (alpha(s.surface, 0.), s.primary),
            trail_open: (s.secondary_container, s.on_secondary_container),
            border: None,
        },
        ButtonVariant::Tonal => SplitColors {
            main: (s.secondary_container, s.on_secondary_container),
            trail: (s.secondary_container, s.on_secondary_container),
            trail_open: (s.primary, s.on_primary),
            border: None,
        },
    }
}

impl RenderOnce for SplitButton {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let s = *Theme::of(cx);
        let colors = split_colors(&s, self.variant);
        let main_id = super::child_id(&self.id, "main");
        let trail_id = super::child_id(&self.id, "trail");
        let main_state = use_interaction(&main_id, window, cx);
        let trail_state = use_interaction(&trail_id, window, cx);
        let main_pressed = main_state.read(cx).pressed;
        let trail_pressed = trail_state.read(cx).pressed;

        let inner_main = if main_pressed { 8. } else { 4. };
        let main_r = crate::motion::animate(
            key(&main_id, "radius"),
            Spring::SPATIAL_FAST,
            [16., inner_main, inner_main, 16.],
            window,
            cx,
        );
        let inner_trail = if self.open {
            16.
        } else if trail_pressed {
            8.
        } else {
            4.
        };
        let trail_r = crate::motion::animate(
            key(&trail_id, "radius"),
            Spring::SPATIAL_FAST,
            [inner_trail, 16., 16., inner_trail],
            window,
            cx,
        );
        let rotation = animate_f32(
            key(&trail_id, "rot"),
            Spring::SPATIAL,
            if self.open { std::f32::consts::PI } else { 0. },
            window,
            cx,
        );
        let (trail_bg, trail_fg) = if self.open {
            colors.trail_open
        } else {
            colors.trail
        };
        let trail_bg = animate_color(key(&trail_id, "bg"), Spring::EFFECTS, trail_bg, window, cx);
        let trail_fg = animate_color(key(&trail_id, "fg"), Spring::EFFECTS, trail_fg, window, cx);
        let (main_bg, main_fg) = colors.main;

        let main_layer = state_layer(
            &main_id,
            &main_state,
            super::corners(main_r),
            main_fg,
            window,
            cx,
        );
        let trail_layer = state_layer(
            &trail_id,
            &trail_state,
            super::corners(trail_r),
            trail_fg,
            window,
            cx,
        );

        let mut main = div()
            .id(main_id.clone())
            .relative()
            .flex()
            .items_center()
            .gap(px(6.))
            .h(px(32.))
            .pl(px(if self.icon.is_some() { 10. } else { 14. }))
            .pr(px(10.))
            .corners(super::corners(main_r))
            .bg(main_bg)
            .text_color(main_fg)
            .font_weight(FontWeight(600.))
            .child(main_layer)
            .children(
                self.icon
                    .map(|icon| Icon::new(icon).size(px(16.)).color(main_fg)),
            )
            .child(self.label);
        if let Some(sub) = self.sublabel {
            main = main.child(div().font_weight(FontWeight(500.)).opacity(0.75).child(sub));
        }
        if let Some(border) = colors.border {
            main = main.border_1().border_color(border);
        }
        let mut main = interactive(main, &main_state, true, true);
        if self.autofocus {
            main = keyboard_focus(main, &main_id, super::corners(main_r), true, window, cx);
        }
        if let Some(f) = self.on_click {
            main = main.on_click(move |e, w, cx| f(e, w, cx));
        }

        let mut trail = div()
            .id(trail_id.clone())
            .relative()
            .flex()
            .items_center()
            .justify_center()
            .size(px(32.))
            .corners(super::corners(trail_r))
            .bg(trail_bg)
            .child(trail_layer)
            .child(
                Icon::new("chevron-down")
                    .size(px(16.))
                    .color(trail_fg)
                    .rotate(rotation),
            );
        if let (Some(border), false) = (colors.border, self.open) {
            trail = trail.border_1().border_color(border);
        }
        let mut trail = interactive(trail, &trail_state, true, true);
        if self.autofocus {
            trail = keyboard_focus(trail, &trail_id, super::corners(trail_r), false, window, cx);
        }
        if let Some(f) = self.on_toggle {
            trail = trail.on_click(move |e, w, cx| f(e, w, cx));
        }

        // Where the button is, so a press on it does not count as outside the menu (the toggle
        // closes it on its own).
        let bounds = window
            .use_keyed_state(key(&self.id, "bounds"), cx, |_, _| {
                Rc::new(std::cell::Cell::new(gpui::Bounds::<Pixels>::default()))
            })
            .read(cx)
            .clone();
        let menu = self.menu.filter(|_| self.open).map(|items| {
            let mut menu = super::Menu::new(super::child_id(&self.id, "menu"))
                .width(self.menu_width)
                .origin(gpui::Corner::TopLeft);
            for item in items {
                menu = menu.item(item);
            }
            let mut wrap = div().id(super::child_id(&self.id, "menu-wrap")).pt(px(4.)).child(menu);
            if let Some(f) = self.on_dismiss {
                let bounds = bounds.clone();
                wrap = wrap.on_mouse_down_out(move |event, w, cx| {
                    if bounds.get().contains(&event.position) {
                        return;
                    }
                    let click = ClickEvent::Mouse(gpui::MouseClickEvent {
                        down: event.clone(),
                        up: gpui::MouseUpEvent {
                            button: event.button,
                            position: event.position,
                            modifiers: event.modifiers,
                            click_count: event.click_count,
                        },
                    });
                    f(&click, w, cx)
                });
            }
            div().absolute().top(gpui::relative(1.)).left_0().child(
                gpui::deferred(
                    gpui::anchored()
                        .anchor(gpui::Corner::TopLeft)
                        .snap_to_window_with_margin(px(8.))
                        .child(wrap),
                )
                .with_priority(1),
            )
        });

        div()
            .relative()
            .flex()
            .flex_none()
            .items_center()
            .gap(px(2.))
            .font_family(font_family())
            .text_size(px(12.5))
            .child(main)
            .child(trail)
            .children(menu.map(|menu| {
                let measure = gpui::canvas(
                    move |b, _, _| bounds.set(b),
                    |_, _, _, _| {},
                )
                .absolute()
                .size_full();
                div().absolute().top_0().left_0().size_full().child(measure).child(menu)
            }))
    }
}

/// Badge: a dot (no text), a pill with a short number, or a tonal text label ("all",
/// "3 changes", "in background").
#[derive(IntoElement)]
pub struct Badge {
    label: Option<SharedString>,
    tone: Option<Tone>,
    strong: bool,
    mono: bool,
    height: Pixels,
    dot_size: Pixels,
    pop: Option<ElementId>,
}

impl Badge {
    /// Numeric badge (tertiary container).
    pub fn new(label: impl Into<SharedString>) -> Self {
        Self {
            label: Some(label.into()),
            tone: None,
            strong: false,
            mono: false,
            height: px(18.),
            dot_size: px(6.),
            pop: None,
        }
    }

    /// Solid badge: the tone's strong color with the surface color for text (the reference
    /// design's numeric badge uses tertiary). A dot uses the strong color too.
    pub fn strong(mut self, tone: Tone) -> Self {
        self.tone = Some(tone);
        self.strong = true;
        self
    }

    /// Size of a [`Badge::dot`] (6 px by default).
    pub fn size(mut self, size: Pixels) -> Self {
        self.dot_size = size;
        self
    }

    /// The dot pops in (grows from nothing with the spring) when it first appears.
    pub fn pop(mut self, id: impl Into<ElementId>) -> Self {
        self.pop = Some(id.into());
        self
    }

    pub fn dot() -> Self {
        Self {
            label: None,
            ..Self::new("")
        }
    }

    /// Text label on a tonal container (11 px, weight 500).
    pub fn tonal(tone: Tone, label: impl Into<SharedString>) -> Self {
        Self {
            tone: Some(tone),
            ..Self::new(label)
        }
    }

    /// Label in the monospace font.
    pub fn mono(mut self, mono: bool) -> Self {
        self.mono = mono;
        self
    }

    /// Height (18 px by default; 20 for a question header).
    pub fn height(mut self, height: Pixels) -> Self {
        self.height = height;
        self
    }
}

impl RenderOnce for Badge {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let s = *Theme::of(cx);
        let strong = |tone: Tone| match tone {
            Tone::Primary => s.primary,
            Tone::Secondary => s.on_secondary_container,
            Tone::Tertiary => s.tertiary,
        };
        let Some(label) = self.label else {
            let size = f32::from(self.dot_size);
            let grow = match &self.pop {
                Some(id) => entrance(key(id, "pop"), Spring::SPATIAL_FAST, 0., window, cx),
                None => 1.,
            };
            let color = self.tone.map_or(s.error, strong);
            let shown = (size * grow).max(0.);
            return div()
                .flex()
                .flex_none()
                .items_center()
                .justify_center()
                .size(self.dot_size)
                .child(div().size(px(shown)).rounded(px(shown / 2.)).bg(color));
        };
        let (bg, fg, weight, pad, min_w) = match self.tone {
            Some(tone) if self.strong => (strong(tone), s.surface, 700., 5., 18.),
            Some(tone) => {
                let (bg, fg) = tone.colors(&s);
                (bg, fg, 500., 6., 0.)
            }
            None => (s.tertiary_container, s.on_tertiary_container, 700., 5., 18.),
        };
        let height = f32::from(self.height);
        div()
            .flex()
            .flex_none()
            .items_center()
            .justify_center()
            .min_w(px(min_w))
            .h(self.height)
            .px(px(pad))
            .rounded(px(height / 2.))
            .bg(bg)
            .text_color(fg)
            .font_family(if self.mono {
                MONO_FONT_FAMILY
            } else {
                font_family()
            })
            .text_size(px(11.))
            .font_weight(FontWeight(if self.mono { 400. } else { weight }))
            .whitespace_nowrap()
            .child(label)
    }
}