u0ui 0.3.10

Carbon UI: IBM Carbon v11 visuals with a shadcn-style API for GPUI Kit
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
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
//! Alert: shadcn `Alert` → Carbon `InlineNotification`, or the inline
//! `ActionableNotification` when an `action` is given (`.cds--inline-notification*`,
//! `.cds--actionable-notification*`).
//!
//! - **Kinds**: `index.jsx` `KINDOF` maps `default` → info, `destructive` →
//!   error, and `success` / `warning` / `info` to themselves ([`AlertVariant::kind`]).
//! - **Colors** ([`NotificationLook`], shared with [`super::toast`]): low contrast
//!   (the default, `lowContrast = true`) paints `notification-background-*`,
//!   a 3px `support-*` start border, `support-*` icon, `text-primary`, and a
//!   1px top/end/bottom outline in the support color at 40% (`::before { border-width:
//!   1px 1px 1px 0; filter: opacity(0.4) }`); high contrast paints
//!   `background-inverse`, `support-*-inverse` border and icon, `text-inverse`.
//!   The warning icon's "!" is black (`path[opacity="0"] { fill: #000; opacity: 1 }`).
//! - **Geometry**: `min-block-size: 3rem`, `min-inline-size: 18rem`, full width
//!   up to `38rem` (`46rem` from a 66rem-wide viewport, `52rem` from 99rem).
//!   From a 42rem-wide viewport the row does not wrap, the details have
//!   `margin: 0 0.8125rem` and the 48px close button sits in the flow; below it
//!   the row wraps, the details keep `margin-inline-end: 3rem` and the close
//!   button is absolute at the top end. Icon 20px with `margin-block-start:
//!   0.875rem; margin-inline-end: 1rem`; text wrapper `padding: 0.9375rem 0`
//!   with the `heading-compact-01` title (4px end margin) and the
//!   `body-compact-01` subtitle on one wrapping line.
//! - **Action** (`.cds--actionable-notification__action-button.cds--btn--ghost`):
//!   a 2rem ghost button (`margin: 0.5rem 0`; narrow `margin-inline-start: 2.5rem`),
//!   `link-inverse` text on high contrast, hover `background-inverse-hover` /
//!   `notification-action-hover`, a 2px `focus-inverse` / `focus` outline.
//! - **Close**: a 3rem square button with the 20px `Close` icon (`icon-inverse`
//!   / `icon-primary`), no hover fill, a 2px `focus-inverse` / `focus` inset
//!   outline (`transition: outline 110ms`). Closing unmounts the notification
//!   (Carbon has no hide transition) after calling `on_close`.
//! - **Rich description**: [`Alert::description_inlines`] sets the subtitle
//!   as one wrapping paragraph of [`Inline`] runs, so a command or a path
//!   reads in mono inside the sentence (u0's `EmptyStates` board:
//!   `.esb-mono { font-family: var(--font-mono); font-size: 12px }`). GPUI
//!   runs cannot change size, so the mono runs use the inline-code face
//!   ([`inline_code_font`], 13px in the 14px subtitle), the nearest the
//!   text system draws; a link is underlined in `link-primary` and opens.
//! - **Behavior**: the buttons are Base buttons (focus, Enter/Space, pointer).
//! - **Words** (u0's, not Carbon's): the title and the plain text given by
//!   [`Alert::words`] are selectable (Base's `SelectableText`). With
//!   [`Alert::copy`] a 3rem Copy button (20px `Copy`, `Checkmark` for
//!   [`COPIED_MS`] after) sits before the close button and copies the title
//!   and the whole of the words. With [`Alert::fold`], words longer than
//!   [`FOLD_LINES`] lines or [`FOLD_CHARS`] characters show their start and
//!   a link (`link-primary`, `body-compact-01`) to show all, then fewer.
use super::form::{inset_outline, rem};
use super::overlay::Callback;
use super::typography::Inline;
use crate::{
    icons::{CarbonIcon, Icon, IconSize},
    motion::{self, Curve, Motion, Speed},
    theme::color,
    tokens::{ColorRole, FontFamilyKey, TypeStyle},
    typography::{TypeStyled as _, font, inline_code_font},
};
use gpui_kit::base::SelectableText;
use gpui_kit::{
    AnyElement, App, ClipboardItem, CursorStyle, ElementId, Hsla, InteractiveElement as _,
    InteractiveText, IntoElement, MouseButton, ParentElement, RenderOnce, SharedString,
    StatefulInteractiveElement as _, Styled, StyledText, TextRun, UnderlineStyle, Window, div,
    prelude::FluentBuilder as _, px,
};
use std::rc::Rc;

/// A Carbon notification kind.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum NotificationKind {
    /// `error`.
    Error,
    /// `success`.
    Success,
    /// `warning`.
    Warning,
    /// `info` (the default).
    #[default]
    Info,
}

impl NotificationKind {
    /// Every kind.
    pub const ALL: [NotificationKind; 4] = [Self::Error, Self::Success, Self::Warning, Self::Info];

    /// Carbon's name.
    pub const fn name(self) -> &'static str {
        match self {
            Self::Error => "error",
            Self::Success => "success",
            Self::Warning => "warning",
            Self::Info => "info",
        }
    }

    /// Carbon's `NotificationIcon`: `ErrorFilled`, `CheckmarkFilled`,
    /// `WarningFilled`, `InformationFilled` (20px).
    pub const fn icon(self) -> CarbonIcon {
        match self {
            Self::Error => CarbonIcon::ErrorFilled,
            Self::Success => CarbonIcon::CheckmarkFilled,
            Self::Warning => CarbonIcon::WarningFilled,
            Self::Info => CarbonIcon::InformationFilled,
        }
    }
}

/// `index.d.ts` `AlertProps.variant`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum AlertVariant {
    /// `default` → info.
    #[default]
    Default,
    /// `destructive` → error.
    Destructive,
    /// `success`.
    Success,
    /// `warning`.
    Warning,
    /// `info`.
    Info,
    /// `error`.
    Error,
}

impl AlertVariant {
    /// Every variant.
    pub const ALL: [AlertVariant; 6] = [
        Self::Default,
        Self::Destructive,
        Self::Success,
        Self::Warning,
        Self::Info,
        Self::Error,
    ];

    /// The `index.d.ts` name.
    pub const fn name(self) -> &'static str {
        match self {
            Self::Default => "default",
            Self::Destructive => "destructive",
            Self::Success => "success",
            Self::Warning => "warning",
            Self::Info => "info",
            Self::Error => "error",
        }
    }

    /// `KINDOF = { default: 'info', destructive: 'error', error: 'error', … }`.
    pub const fn kind(self) -> NotificationKind {
        match self {
            Self::Default | Self::Info => NotificationKind::Info,
            Self::Destructive | Self::Error => NotificationKind::Error,
            Self::Success => NotificationKind::Success,
            Self::Warning => NotificationKind::Warning,
        }
    }
}

/// The colors of a notification (inline, actionable or toast).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct NotificationLook {
    /// Fill.
    pub background: Hsla,
    /// The 3px start border and the status icon.
    pub accent: Hsla,
    /// The low-contrast 1px outline (`::before`, already at 40%), if any.
    pub outline: Option<Hsla>,
    /// Title and subtitle.
    pub text: Hsla,
    /// The close icon.
    pub close_icon: Hsla,
    /// Focus outlines.
    pub focus: Hsla,
}

impl NotificationLook {
    /// The look of `kind`, low or high contrast.
    pub fn of(kind: NotificationKind, low_contrast: bool) -> Self {
        use NotificationKind::*;
        if low_contrast {
            // `.cds--inline-notification--low-contrast.cds--inline-notification--error
            // { background: notification-background-error; border-inline-start: 3px
            // solid support-error }`, `::before { border-color: support-error }`.
            let (bg, accent) = match kind {
                Error => (
                    ColorRole::NotificationBackgroundError,
                    ColorRole::SupportError,
                ),
                Success => (
                    ColorRole::NotificationBackgroundSuccess,
                    ColorRole::SupportSuccess,
                ),
                Warning => (
                    ColorRole::NotificationBackgroundWarning,
                    ColorRole::SupportWarning,
                ),
                Info => (
                    ColorRole::NotificationBackgroundInfo,
                    ColorRole::SupportInfo,
                ),
            };
            Self {
                background: color(bg),
                accent: color(accent),
                // `filter: opacity(0.4)`.
                outline: Some(color(accent).opacity(0.4)),
                // `.cds--inline-notification--low-contrast { color: text-primary }`.
                text: color(ColorRole::TextPrimary),
                close_icon: color(ColorRole::IconPrimary),
                focus: color(ColorRole::Focus),
            }
        } else {
            // `.cds--inline-notification--error { background: background-inverse;
            // border-inline-start: 3px solid support-error-inverse }`.
            let accent = match kind {
                Error => ColorRole::SupportErrorInverse,
                Success => ColorRole::SupportSuccessInverse,
                Warning => ColorRole::SupportWarningInverse,
                Info => ColorRole::SupportInfoInverse,
            };
            Self {
                background: color(ColorRole::BackgroundInverse),
                accent: color(accent),
                outline: None,
                text: color(ColorRole::TextInverse),
                close_icon: color(ColorRole::IconInverse),
                focus: color(ColorRole::FocusInverse),
            }
        }
    }
}

/// `border-inline-start: 3px solid …`.
pub const ACCENT_WIDTH: f32 = 3.;
/// `min-block-size: 3rem` and the close button's 3rem square.
pub const ROW_HEIGHT: f32 = 48.;
/// `.cds--inline-notification__details { margin: 0 0.8125rem }`.
pub const DETAILS_MARGIN: f32 = 13.;

/// `max-inline-size` for a viewport `width_rem` wide: `18rem`, `38rem` from
/// 42rem, `46rem` from 66rem, `52rem` from 99rem.
pub fn max_width(width_rem: f32) -> f32 {
    if width_rem >= 99. {
        52. * 16.
    } else if width_rem >= 66. {
        46. * 16.
    } else if width_rem >= 42. {
        38. * 16.
    } else {
        18. * 16.
    }
}

/// `@media (min-width: 42rem)`: the wide (non-wrapping) layout.
pub fn is_wide(width_rem: f32) -> bool {
    width_rem >= 42.
}

/// The viewport width in rems.
pub(crate) fn viewport_rem(window: &Window) -> f32 {
    f32::from(window.viewport_size().width) / f32::from(window.rem_size())
}

/// The 20px status icon; the warning glyph's "!" filled black
/// (`.cds--inline-notification--warning .cds--inline-notification__icon
/// path[opacity="0"] { fill: #000000; opacity: 1 }`).
pub(crate) fn status_icon(kind: NotificationKind, accent: Hsla) -> AnyElement {
    let icon = Icon::carbon(kind.icon()).size(IconSize::S20).color(accent);
    if kind != NotificationKind::Warning {
        return icon.into_any_element();
    }
    div()
        .relative()
        .size(rem(20.))
        .flex_none()
        .child(
            div()
                .absolute()
                .left(rem(8.5))
                .top(rem(5.))
                .w(rem(3.))
                .h(rem(10.5))
                .bg(gpui_kit::black()),
        )
        .child(icon.absolute().top_0().left_0())
        .into_any_element()
}

/// `transition: outline 110ms cubic-bezier(0.2, 0, 0.38, 0.9)` (close button).
pub const CLOSE_MOTION: Motion = Motion::new(Curve::ProductiveStandard, Speed::Fast02);

/// The 3rem close button.
pub(crate) fn close_button(
    id: ElementId,
    look: NotificationLook,
    label: SharedString,
    on_click: Callback,
    window: &mut Window,
    cx: &mut App,
) -> gpui_kit::base::Button {
    let focus = window
        .use_keyed_state((id.clone(), "focus"), cx, |_, cx| cx.focus_handle())
        .read(cx)
        .clone();
    square_button(
        id,
        CarbonIcon::Close,
        look,
        label,
        Rc::new(move |window, cx| {
            // Closing removes the button: keep the Tab starting point.
            crate::u0::primitives::parts::vacate_focus(&focus, window, cx);
            on_click(window, cx)
        }),
        window,
        cx,
    )
}

/// How long the Copy button shows `Checkmark` after a copy.
pub const COPIED_MS: u64 = 2000;

/// The most lines of words a folded notification shows.
pub const FOLD_LINES: usize = 6;

/// The most characters of words a folded notification shows.
pub const FOLD_CHARS: usize = 480;

/// Where `words` are cut while folded: after [`FOLD_LINES`] lines or
/// [`FOLD_CHARS`] characters, whichever comes first; `None` when they fit.
pub fn fold_at(words: &str) -> Option<usize> {
    let by_lines = words
        .match_indices('\n')
        .nth(FOLD_LINES - 1)
        .map(|(i, _)| i);
    let by_chars = words.char_indices().nth(FOLD_CHARS).map(|(i, _)| i);
    let at = match (by_lines, by_chars) {
        (Some(a), Some(b)) => a.min(b),
        (a, b) => a.or(b)?,
    };
    // Nothing but blank space past the cut: it fits.
    (!words[at..].trim().is_empty()).then_some(at)
}

/// What Copy puts on the clipboard: the title, then the words, a line apart.
pub fn copied_text(title: Option<&str>, words: Option<&str>) -> String {
    match (title, words) {
        (Some(t), Some(w)) => format!("{t}\n{w}"),
        (t, w) => t.or(w).unwrap_or_default().to_owned(),
    }
}

/// A 3rem square button with a 20px icon: close and copy.
fn square_button(
    id: ElementId,
    icon: CarbonIcon,
    look: NotificationLook,
    label: SharedString,
    on_click: Callback,
    window: &mut Window,
    cx: &mut App,
) -> gpui_kit::base::Button {
    let focus = window
        .use_keyed_state((id.clone(), "focus"), cx, |_, cx| cx.focus_handle())
        .read(cx)
        .clone();
    let outline = motion::animate_color(
        (id.clone(), "outline"),
        if focus.is_focused(window) {
            look.focus
        } else {
            look.focus.opacity(0.)
        },
        CLOSE_MOTION,
        window,
        cx,
    );
    gpui_kit::base::Button::new(id)
        .track_focus(&focus)
        .accessibility_label(label)
        .relative()
        .flex_none()
        .size(rem(ROW_HEIGHT))
        .flex()
        .items_center()
        .justify_center()
        .cursor(CursorStyle::PointingHand)
        .child(
            Icon::carbon(icon)
                .size(IconSize::S20)
                .color(look.close_icon),
        )
        .child(inset_outline(2., outline))
        .on_click(move |_, window, cx| on_click(window, cx))
}

/// `AlertTitle`.
pub struct AlertTitle(pub SharedString);

impl AlertTitle {
    /// A title.
    pub fn new(text: impl Into<SharedString>) -> Self {
        Self(text.into())
    }
}

/// `AlertDescription`.
pub struct AlertDescription(pub AnyElement);

impl AlertDescription {
    /// A description.
    pub fn new(content: impl IntoElement) -> Self {
        Self(content.into_any_element())
    }
}

/// `AlertProps.action`: `{ label, onClick }`.
pub struct AlertAction {
    label: SharedString,
    on_click: Option<Callback>,
}

impl AlertAction {
    /// An action button labeled `label`.
    pub fn new(label: impl Into<SharedString>) -> Self {
        Self {
            label: label.into(),
            on_click: None,
        }
    }

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

/// One piece of an alert's description.
enum Description {
    /// Any element.
    Element(AnyElement),
    /// A paragraph of runs, coloured as the alert's text.
    Inlines(Vec<Inline>),
}

/// Text, its runs, and the link ranges with their targets.
pub type DescriptionRuns = (
    String,
    Vec<TextRun>,
    Vec<(std::ops::Range<usize>, SharedString)>,
);

/// The text of `inlines` and its runs in `ink`: [`Inline::Code`] in the
/// inline-code face with no fill (`.esb-mono` has none), a link underlined
/// in `link-primary`; with the link ranges and their targets.
pub fn description_runs(inlines: &[Inline], ink: Hsla) -> DescriptionRuns {
    let mut text = String::new();
    let mut runs = Vec::new();
    let mut links = Vec::new();
    for inline in inlines {
        let (s, run_font, run_color, underline) = match inline {
            Inline::Text(s) => (s, font(FontFamilyKey::Sans, 400), ink, None),
            Inline::Code(s) => (s, inline_code_font(), ink, None),
            Inline::Link(s, _) => {
                let link = color(ColorRole::LinkPrimary);
                (
                    s,
                    font(FontFamilyKey::Sans, 400),
                    link,
                    Some(UnderlineStyle {
                        thickness: px(1.),
                        color: Some(link),
                        wavy: false,
                    }),
                )
            }
        };
        let start = text.len();
        text.push_str(s);
        if let Inline::Link(_, href) = inline {
            links.push((start..text.len(), href.clone()));
        }
        runs.push(TextRun {
            len: s.len(),
            font: run_font,
            color: run_color,
            background_color: None,
            underline,
            strikethrough: None,
        });
    }
    (text, runs, links)
}

/// An inline notification. See the module docs.
#[derive(IntoElement)]
pub struct Alert {
    id: ElementId,
    variant: AlertVariant,
    title: Option<SharedString>,
    description: Vec<Description>,
    action: Option<AlertAction>,
    full_width: bool,
    on_close: Option<Callback>,
    close_label: SharedString,
    low_contrast: bool,
    words: Option<SharedString>,
    copy: Option<(SharedString, SharedString)>,
    fold: Option<(SharedString, SharedString)>,
}

impl Alert {
    /// A low-contrast info alert.
    pub fn new(id: impl Into<ElementId>) -> Self {
        Self {
            id: id.into(),
            variant: AlertVariant::Default,
            title: None,
            description: Vec::new(),
            action: None,
            full_width: false,
            on_close: None,
            close_label: "Close notification".into(),
            low_contrast: true,
            words: None,
            copy: None,
            fold: None,
        }
    }

    /// `variant`.
    pub fn variant(mut self, variant: AlertVariant) -> Self {
        self.variant = variant;
        self
    }

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

    /// The description (`children`).
    pub fn description(mut self, content: impl IntoElement) -> Self {
        self.description
            .push(Description::Element(content.into_any_element()));
        self
    }

    /// The description as one wrapping paragraph of runs: plain text, mono
    /// [`Inline::Code`] (a command, a path) and links. See the module docs.
    pub fn description_inlines(mut self, inlines: impl IntoIterator<Item = Inline>) -> Self {
        self.description
            .push(Description::Inlines(inlines.into_iter().collect()));
        self
    }

    /// The description as plain text: selectable, copied whole by
    /// [`Self::copy`], folded by [`Self::fold`].
    pub fn words(mut self, words: impl Into<SharedString>) -> Self {
        self.words = Some(words.into());
        self
    }

    /// Show the Copy button, labeled `label`, and `copied` once it copied:
    /// it copies the title and the whole of the words.
    pub fn copy(mut self, label: impl Into<SharedString>, copied: impl Into<SharedString>) -> Self {
        self.copy = Some((label.into(), copied.into()));
        self
    }

    /// Fold long words (see [`fold_at`]) behind a link labeled `show_all`,
    /// and `show_less` once they are all shown.
    pub fn fold(
        mut self,
        show_all: impl Into<SharedString>,
        show_less: impl Into<SharedString>,
    ) -> Self {
        self.fold = Some((show_all.into(), show_less.into()));
        self
    }

    /// `<AlertTitle>` child.
    pub fn alert_title(mut self, title: AlertTitle) -> Self {
        self.title = Some(title.0);
        self
    }

    /// `<AlertDescription>` child.
    pub fn alert_description(mut self, description: AlertDescription) -> Self {
        self.description.push(Description::Element(description.0));
        self
    }

    /// Drop the `max-inline-size` cap (`style: { maxWidth: 'none' }`), as
    /// a banner across the content does. Off by default.
    pub fn full_width(mut self, full_width: bool) -> Self {
        self.full_width = full_width;
        self
    }

    /// `action`: makes it an `ActionableNotification`.
    pub fn action(mut self, action: AlertAction) -> Self {
        self.action = Some(action);
        self
    }

    /// `onClose`: shows the close button.
    pub fn on_close(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
        self.on_close = Some(Rc::new(f));
        self
    }

    /// The close button's accessible label (Carbon `ariaLabel`).
    pub fn close_label(mut self, label: impl Into<SharedString>) -> Self {
        self.close_label = label.into();
        self
    }

    /// `lowContrast` (default true).
    pub fn low_contrast(mut self, low: bool) -> Self {
        self.low_contrast = low;
        self
    }
}

/// The ghost action button (`.cds--actionable-notification__action-button.cds--btn--ghost`).
fn action_button(
    id: ElementId,
    action: AlertAction,
    low_contrast: bool,
    look: NotificationLook,
    window: &mut Window,
    cx: &mut App,
) -> impl IntoElement {
    let pointer = window.use_keyed_state((id.clone(), "pointer"), cx, |_, _| (false, false));
    let focus = window
        .use_keyed_state((id.clone(), "focus"), cx, |_, cx| cx.focus_handle())
        .read(cx)
        .clone();
    let (hovered, pressed) = *pointer.read(cx);
    // `:hover, :active { background-color: background-inverse-hover }`;
    // low contrast `notification-action-hover`.
    let hover_bg = color(if low_contrast {
        ColorRole::NotificationActionHover
    } else {
        ColorRole::BackgroundInverseHover
    });
    let bg = motion::animate_color(
        (id.clone(), "bg"),
        if hovered || pressed {
            hover_bg
        } else {
            hover_bg.opacity(0.)
        },
        Motion::HOVER,
        window,
        cx,
    );
    // `.cds--btn--ghost { color: var(--link-primary) }`; high contrast `link-inverse`.
    let text = color(if low_contrast {
        ColorRole::LinkPrimary
    } else {
        ColorRole::LinkInverse
    });
    let on_click = action.on_click.clone();
    gpui_kit::base::Button::new(id)
        .track_focus(&focus)
        .accessibility_label(action.label.clone())
        .relative()
        .flex_none()
        .h(rem(32.))
        // `.cds--actionable-notification .cds--actionable-notification__action-button.cds--btn
        // { block-size: 2rem; padding: 0 var(--spacing-04) }` (the bundle's r3-set rule).
        .px(rem(12.))
        // Computed `.cds--actionable-notification__action-button`:
        // `padding-block: 0` in a stretched flex box, so the label's line
        // sits at the top, under the 1px transparent `.cds--btn` border
        // (its centre 10px from the top, not the box's 16).
        .pt(px(1.))
        .flex()
        .items_start()
        .whitespace_nowrap()
        .type_style(TypeStyle::BodyCompact01)
        .text_color(text)
        .bg(bg)
        .cursor(CursorStyle::PointingHand)
        .on_hover({
            let pointer = pointer.clone();
            move |h, _, cx| {
                pointer.update(cx, |p, cx| {
                    p.0 = *h;
                    if !h {
                        p.1 = false;
                    }
                    cx.notify();
                })
            }
        })
        .on_mouse_down(MouseButton::Left, {
            let pointer = pointer.clone();
            move |_, _, cx| {
                pointer.update(cx, |p, cx| {
                    p.1 = true;
                    cx.notify();
                })
            }
        })
        .on_mouse_up(MouseButton::Left, move |_, _, cx| {
            pointer.update(cx, |p, cx| {
                p.1 = false;
                cx.notify();
            })
        })
        .when_some(on_click, |d, f| {
            let focus = focus.clone();
            d.on_click(move |_, window, cx| {
                crate::u0::primitives::parts::vacate_focus(&focus, window, cx);
                f(window, cx)
            })
        })
        .child(action.label)
        // `:focus { outline: 2px solid var(--focus-inverse) }`; low contrast `focus`.
        .when(focus.is_focused(window), |d| {
            d.child(inset_outline(2., look.focus))
        })
}

impl RenderOnce for Alert {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let id = self.id.clone();
        let open = window.use_keyed_state((id.clone(), "open"), cx, |_, _| true);
        if !*open.read(cx) {
            return div().into_any_element();
        }
        let kind = self.variant.kind();
        let look = NotificationLook::of(kind, self.low_contrast);
        let vw = viewport_rem(window);
        let wide = is_wide(vw);
        let closable = self.on_close.is_some();
        let corner = usize::from(closable) + usize::from(self.copy.is_some());
        let unfolded = window.use_keyed_state((id.clone(), "unfolded"), cx, |_, _| false);
        let words = self.words.clone().map(|words| {
            let cut = self.fold.as_ref().and_then(|_| fold_at(&words));
            let all = *unfolded.read(cx);
            let shown: SharedString = match cut {
                Some(at) if !all => words[..at].trim_end().to_owned().into(),
                _ => words.clone(),
            };
            let link = cut.and(self.fold.clone()).map(|(more, less)| {
                let unfolded = unfolded.clone();
                let focus = window
                    .use_keyed_state((id.clone(), "fold-focus"), cx, |_, cx| cx.focus_handle())
                    .read(cx)
                    .clone();
                // A Carbon `Link` (`.cds--link`): `link-primary`, hover
                // `link-primary-hover`, a 1px `focus` outline.
                gpui_kit::base::Button::new((id.clone(), "fold"))
                    .track_focus(&focus)
                    .relative()
                    .self_start()
                    .mt(rem(4.))
                    .cursor(CursorStyle::PointingHand)
                    .text_color(color(ColorRole::LinkPrimary))
                    .hover(|s| s.text_color(color(ColorRole::LinkPrimaryHover)))
                    .child(if all { less } else { more })
                    .when(focus.is_focused(window), |d| {
                        d.child(inset_outline(1., look.focus))
                    })
                    .on_click(move |_, _, cx| {
                        unfolded.update(cx, |u, cx| {
                            *u = !*u;
                            cx.notify();
                        })
                    })
            });
            div()
                .flex()
                .flex_col()
                .flex_shrink_1()
                .min_w_0()
                .type_style(TypeStyle::BodyCompact01)
                .child(SelectableText::new((id.clone(), "words"), shown))
                .children(link)
        });

        // `.cds--inline-notification__text-wrapper { display: flex; flex-wrap: wrap;
        // padding: 0.9375rem 0 }`.
        let text = div()
            .flex()
            .flex_row()
            .flex_wrap()
            .flex_1()
            .min_w_0()
            .py(rem(15.))
            .text_color(look.text)
            .when_some(self.title.clone(), |d, t| {
                d.child(
                    div()
                        .flex_shrink_1()
                        .min_w_0()
                        .type_style(TypeStyle::HeadingCompact01)
                        .mr(rem(4.))
                        .child(SelectableText::new((id.clone(), "title"), t)),
                )
            })
            .children(self.description.into_iter().enumerate().map(|(i, c)| {
                let c = match c {
                    Description::Element(e) => e,
                    Description::Inlines(inlines) => {
                        let (text, runs, links) = description_runs(&inlines, look.text);
                        let styled = StyledText::new(text).with_runs(runs);
                        if links.is_empty() {
                            styled.into_any_element()
                        } else {
                            let (ranges, targets): (Vec<_>, Vec<_>) = links.into_iter().unzip();
                            InteractiveText::new(
                                (id.clone(), SharedString::from(format!("description-{i}"))),
                                styled,
                            )
                            .on_click(ranges, move |ix, _, cx| cx.open_url(&targets[ix]))
                            .into_any_element()
                        }
                    }
                };
                div()
                    .flex_shrink_1()
                    .min_w_0()
                    .type_style(TypeStyle::BodyCompact01)
                    .child(c)
            }))
            .children(words);
        let details = div()
            .flex()
            .flex_row()
            .flex_1()
            .min_w_0()
            .ml(rem(DETAILS_MARGIN))
            .mr(rem(if wide || corner == 0 {
                DETAILS_MARGIN
            } else {
                ROW_HEIGHT * corner as f32
            }))
            .when(!wide, |d| d.w_full())
            .child(
                div()
                    .flex_none()
                    .mt(rem(14.))
                    .mr(rem(16.))
                    .child(status_icon(kind, look.accent)),
            )
            .child(text);

        let actionable = self.action.is_some();
        let action = self.action.map(|a| {
            div()
                .flex()
                .flex_none()
                .map(|d| {
                    if wide {
                        d.my(rem(8.))
                    } else {
                        d.ml(rem(40.)).mb(rem(8.))
                    }
                })
                // `--hide-close-button … { margin-inline-end: 0.5rem }`.
                .when(!closable, |d| d.mr(rem(8.)))
                .child(action_button(
                    (id.clone(), "action").into(),
                    a,
                    self.low_contrast,
                    look,
                    window,
                    cx,
                ))
        });

        let close = self.on_close.clone().map(|f| {
            let open = open.clone();
            let button = close_button(
                (id.clone(), "close").into(),
                look,
                self.close_label.clone(),
                Rc::new(move |window, cx| {
                    f(window, cx);
                    open.update(cx, |o, cx| {
                        *o = false;
                        cx.notify();
                    });
                }),
                window,
                cx,
            );
            if wide {
                button
            } else {
                button.absolute().top_0().right_0()
            }
        });

        let copy = self.copy.clone().map(|(label, copied)| {
            let flash =
                crate::u0::primitives::parts::flash_state((id.clone(), "copied"), window, cx);
            let done = crate::u0::primitives::parts::flash_on(&flash, COPIED_MS, cx);
            let text = copied_text(self.title.as_deref(), self.words.as_deref());
            let button = square_button(
                (id.clone(), "copy").into(),
                if done {
                    CarbonIcon::Checkmark
                } else {
                    CarbonIcon::Copy
                },
                look,
                if done { copied } else { label },
                Rc::new(move |_, cx| {
                    cx.write_to_clipboard(ClipboardItem::new_string(text.clone()));
                    crate::u0::primitives::parts::flash(&flash, COPIED_MS, cx);
                }),
                window,
                cx,
            );
            if wide {
                button
            } else {
                // Before the close button, where there is one.
                button
                    .absolute()
                    .top_0()
                    .right(rem(if closable { ROW_HEIGHT } else { 0. }))
            }
        });

        div()
            .id(id)
            .relative()
            .flex()
            .flex_row()
            .when(!wide, |d| d.flex_wrap())
            .w_full()
            .when(self.full_width, |d| d.min_w_0())
            .when(!self.full_width, |d| {
                d.min_w(rem(288.)).max_w(rem(max_width(vw)))
            })
            .min_h(rem(ROW_HEIGHT))
            .bg(look.background)
            .border_l(rem(ACCENT_WIDTH))
            .border_color(look.accent)
            .when_some(look.outline, |d, outline| {
                // `::before { border-width: 1px 1px 1px 0; filter: opacity(0.4) }`.
                d.child(
                    div()
                        .absolute()
                        .top_0()
                        .left_0()
                        .right_0()
                        .bottom_0()
                        .border_t(px(1.))
                        .border_r(px(1.))
                        .border_b(px(1.))
                        .border_color(outline),
                )
            })
            .child(details)
            .map(|d| {
                if actionable && wide {
                    // The bundle's r3-set rules for a (non-toast) actionable
                    // notification: `align-items: flex-start`, and the
                    // `__button-wrapper` (action + close) `align-self:
                    // flex-start; margin: 10px 16px 16px 16px`.
                    d.items_start().child(
                        div()
                            .flex()
                            .flex_row()
                            .flex_none()
                            .mt(rem(10.))
                            .mx(rem(16.))
                            .mb(rem(16.))
                            .children(action)
                            .children(copy)
                            .children(close),
                    )
                } else {
                    d.children(action).children(copy).children(close)
                }
            })
            .into_any_element()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tokens::CarbonTheme;

    #[test]
    fn variants_map_like_kindof() {
        assert_eq!(AlertVariant::Default.kind(), NotificationKind::Info);
        assert_eq!(AlertVariant::Destructive.kind(), NotificationKind::Error);
        assert_eq!(AlertVariant::Warning.kind(), NotificationKind::Warning);
        assert_eq!(
            NotificationKind::Success.icon(),
            CarbonIcon::CheckmarkFilled
        );
    }

    #[test]
    fn looks_match_bundle() {
        crate::theme::tests_set(CarbonTheme::White);
        let low = NotificationLook::of(NotificationKind::Error, true);
        assert_eq!(
            low.background,
            color(ColorRole::NotificationBackgroundError)
        );
        assert_eq!(low.accent, color(ColorRole::SupportError));
        assert_eq!(
            low.outline,
            Some(color(ColorRole::SupportError).opacity(0.4))
        );
        assert_eq!(low.text, color(ColorRole::TextPrimary));
        assert_eq!(low.close_icon, color(ColorRole::IconPrimary));
        let high = NotificationLook::of(NotificationKind::Success, false);
        assert_eq!(high.background, color(ColorRole::BackgroundInverse));
        assert_eq!(high.accent, color(ColorRole::SupportSuccessInverse));
        assert_eq!(high.outline, None);
        assert_eq!(high.text, color(ColorRole::TextInverse));
        assert_eq!(high.focus, color(ColorRole::FocusInverse));
        // Low-contrast warning keeps `support-warning` for border and icon.
        assert_eq!(
            NotificationLook::of(NotificationKind::Warning, true).accent,
            color(ColorRole::SupportWarning)
        );
    }

    #[test]
    fn long_words_fold_after_six_lines_or_480_characters() {
        let trace: String = (1..=20).map(|i| format!("    at line {i}\n")).collect();
        let at = fold_at(&trace).unwrap();
        assert_eq!(trace[..at].lines().count(), FOLD_LINES);
        assert!(trace[..at].ends_with("line 6"));
        assert_eq!(fold_at("one line"), None);
        // Six lines and a trailing newline fit.
        assert_eq!(fold_at("a\nb\nc\nd\ne\nf\n"), None);
        let long = "語".repeat(500);
        let at = fold_at(&long).unwrap();
        assert_eq!(long[..at].chars().count(), FOLD_CHARS);
    }

    #[test]
    fn copy_takes_the_title_and_all_the_words() {
        assert_eq!(
            copied_text(Some("Stopped"), Some("at a\nat b")),
            "Stopped\nat a\nat b"
        );
        assert_eq!(copied_text(None, Some("why")), "why");
        assert_eq!(copied_text(Some("Stopped"), None), "Stopped");
        assert_eq!(copied_text(None, None), "");
    }

    #[test]
    fn a_rich_description_sets_its_command_in_mono() {
        crate::theme::tests_set(CarbonTheme::White);
        let ink = color(ColorRole::TextPrimary);
        let (text, runs, links) = description_runs(
            &[
                Inline::Text("Install it with ".into()),
                Inline::Code("brew install gh".into()),
                Inline::Text(".".into()),
            ],
            ink,
        );
        assert_eq!(text, "Install it with brew install gh.");
        assert_eq!(runs.iter().map(|r| r.len).collect::<Vec<_>>(), [16, 15, 1]);
        assert_eq!(runs[1].font.family, inline_code_font().family);
        assert_eq!(runs[0].font.family, font(FontFamilyKey::Sans, 400).family);
        assert!(
            runs.iter()
                .all(|r| r.background_color.is_none() && r.color == ink)
        );
        assert!(links.is_empty());
    }

    #[test]
    fn widths_follow_media_queries() {
        assert_eq!(max_width(30.), 288.);
        assert_eq!(max_width(42.), 608.);
        assert_eq!(max_width(70.), 736.);
        assert_eq!(max_width(100.), 832.);
        assert!(!is_wide(41.9) && is_wide(42.));
        assert_eq!(ROW_HEIGHT, 48.);
        assert_eq!(ACCENT_WIDTH, 3.);
    }
}