u0ui 0.3.2

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
//! NavigationMenu: a site's top navigation → Carbon UI shell `Header` +
//! `HeaderName` + `HeaderNavigation` + `HeaderMenuItem` / `HeaderMenu`
//! (`.cds--header`). Always laid out inline (the reference's default
//! `inline`), so it can sit in a page or at the top of a window.
//!
//! - **Behavior**: links and menu titles are Base `Button`s (focus,
//!   Enter/Space, pointer). A `HeaderMenu` opens under its title on press or
//!   ↓; inside it ↑/↓ move between items, Enter runs one, Escape (or a press
//!   outside) closes and returns focus to the title. Tab and Shift+Tab follow
//!   the reference's document order (title, items, then what follows the
//!   menu): Tab on an open title enters the first item, Tab on an item moves
//!   to the next, and Tab past the last item closes the menu and moves on to
//!   the next element after it; Shift+Tab on the first item closes the menu
//!   and returns to the title. They need [`init`]'s bindings, which beat
//!   Base's window-level Tab. Placement is Base's
//!   `Popup`; open state and focus moves come from [`super::overlay`].
//! - **Appearance**: a 3rem bar on `background` with a 1px `border-subtle`
//!   bottom line; the name in body-compact-01 600 with a 400 prefix, padded
//!   `0 2rem 0 1rem`; the navigation after a 1.5rem `border-subtle` rule;
//!   items `text-secondary` on `background`, hover `background-hover` +
//!   `text-primary`, press `background-active`, focus a 2px `focus` border,
//!   the current item still `text-secondary` (the `a.` rule outranks
//!   `--current`) with a 3px `border-interactive` bottom bar. An open menu title turns `layer`, its chevron (`icon-secondary`)
//!   turns 180°; the menu is 12.5rem wide on `layer` with `0 4px 8px
//!   rgba(0,0,0,.5)`, 3rem items, hover `layer-hover`, the current one
//!   `layer-selected` with a 3px start bar. Global actions sit at the end.
//! - **Motion**: `transition: background-color 110ms, border-color 110ms,
//!   color 110ms`; chevron `transform 110ms`; the menu shows and hides at
//!   once (`.cds--header__menu { display: none }` → `flex`, no transition).
use super::overlay::{Callback, rem};
use crate::{
    icons::{CarbonIcon, Icon, IconSize},
    motion::{self, Curve, Motion, Speed},
    theme::color,
    tokens::{ColorRole, TypeStyle},
    typography::TypeStyled as _,
};
use gpui_kit::{
    Anchor, AnyElement, App, BoxShadow, CursorStyle, ElementId, Entity, FocusHandle, FontWeight,
    Hsla, InteractiveElement, IntoElement, KeyDownEvent, ParentElement, RenderOnce, SharedString,
    StatefulInteractiveElement as _, Styled, TestSupportExt as _, Window, div, hsla,
    prelude::FluentBuilder as _, px,
};
use gpui_kit::{KeyBinding, actions};
use std::rc::Rc;

actions!(
    u0ui_navigation_menu,
    [
        /// Tab inside a header menu (its title or items).
        TabNext,
        /// Shift+Tab inside a header menu (its title or items).
        TabPrev
    ]
);

/// The key context of a header menu (its title and its open item list).
const KEY_CONTEXT: &str = "U0NavigationMenu";

/// Bind Tab and Shift+Tab inside header menus. The menu's items paint in a
/// deferred layer, so in GPUI's tab order they come after everything else;
/// these bindings put them back between their title and what follows it.
pub(crate) fn init(cx: &mut App) {
    cx.bind_keys([
        KeyBinding::new("tab", TabNext, Some(KEY_CONTEXT)),
        KeyBinding::new("shift-tab", TabPrev, Some(KEY_CONTEXT)),
    ]);
}

/// `a.cds--header__menu-item { transition: background-color 110ms, border-color 110ms, color 110ms }`
/// (CSS `ease`, the closest Carbon curve being productive standard).
pub const ITEM_MOTION: Motion = Motion::new(Curve::ProductiveStandard, Speed::Fast02);
/// `.cds--header { block-size: 3rem }`.
pub const HEADER_HEIGHT: f32 = 48.;
/// `.cds--header__menu { inline-size: 12.5rem }`.
pub const MENU_WIDTH: f32 = 200.;

/// One navigation entry (`index.d.ts` `NavItem`: `label`, `active`, `items`).
#[derive(Clone)]
pub struct NavItem {
    label: SharedString,
    active: bool,
    on_click: Option<Callback>,
    items: Vec<NavItem>,
}

impl NavItem {
    /// A link (`HeaderMenuItem`).
    pub fn link(label: impl Into<SharedString>) -> Self {
        Self {
            label: label.into(),
            active: false,
            on_click: None,
            items: Vec::new(),
        }
    }

    /// A dropdown (`HeaderMenu`) with links.
    pub fn menu(label: impl Into<SharedString>, items: impl IntoIterator<Item = NavItem>) -> Self {
        Self {
            items: items.into_iter().collect(),
            ..Self::link(label)
        }
    }

    /// The current page (`isActive`).
    pub fn active(mut self, active: bool) -> Self {
        self.active = active;
        self
    }

    /// Navigate when activated (the reference's `href`).
    pub fn on_click(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
        self.on_click = Some(Rc::new(f));
        self
    }
}

/// `(background, text)` of a header item.
pub fn item_colors(in_menu: bool, current: bool, hovered: bool, pressed: bool) -> (Hsla, Hsla) {
    use ColorRole::*;
    if in_menu {
        let bg = match (current, hovered, pressed) {
            (_, _, true) => LayerActive01,
            (true, true, _) => LayerSelectedHover01,
            (true, false, _) => LayerSelected01,
            (false, true, _) => LayerHover01,
            _ => Layer01,
        };
        let text = if hovered || pressed || current {
            TextPrimary
        } else {
            TextSecondary
        };
        return (color(bg), color(text));
    }
    let bg = if pressed {
        BackgroundActive
    } else if hovered {
        BackgroundHover
    } else {
        Background
    };
    // The current item keeps `text-secondary`: `.cds--header__menu-item--current
    // { color: text-primary }` (0,1,0) loses to `a.cds--header__menu-item {
    // color: text-secondary }` (0,1,1); only its 3px bar marks it.
    let text = if hovered || pressed {
        TextPrimary
    } else {
        TextSecondary
    };
    (color(bg), color(text))
}

type KeyHandler = Rc<dyn Fn(&KeyDownEvent, &mut Window, &mut App)>;
/// Open or close a header menu, optionally focusing an item.
type SetMenu = Rc<dyn Fn(bool, Option<usize>, &mut Window, &mut App)>;

/// How far the menu shadow reaches past the menu's sides and bottom, so the
/// clip that keeps it off the title spares all of it: GPUI paints a shadow's
/// blur out to 3 × `blur_radius` (its gaussian's extent), plus the 4px
/// offset. A smaller reach cuts the fading edge into a hard step.
const MENU_SHADOW_REACH: f32 = 4. + 3. * 8.;

/// The header menu's shadow: `box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.5)`.
pub fn menu_shadow() -> Vec<BoxShadow> {
    vec![BoxShadow::new(px(0.), px(4.), hsla(0., 0., 0., 0.5)).blur_radius(px(8.))]
}

/// The name's flex-shrink weight against the links' 1: it takes nearly all
/// of a shortfall until only its padding is left.
const NAME_SHRINK: f32 = 1000.;

/// The UI shell header. See the module docs.
#[derive(IntoElement)]
pub struct NavigationMenu {
    id: ElementId,
    brand_prefix: SharedString,
    brand: SharedString,
    on_brand_click: Option<Callback>,
    items: Vec<NavItem>,
    actions: Vec<AnyElement>,
}

impl NavigationMenu {
    /// A header with a stable `id`; pass the name with [`Self::brand`].
    pub fn new(id: impl Into<ElementId>) -> Self {
        Self {
            id: id.into(),
            brand_prefix: SharedString::default(),
            brand: SharedString::default(),
            on_brand_click: None,
            items: Vec::new(),
            actions: Vec::new(),
        }
    }

    /// The name prefix (`brandPrefix`, regular weight).
    pub fn brand_prefix(mut self, prefix: impl Into<SharedString>) -> Self {
        self.brand_prefix = prefix.into();
        self
    }

    /// The product name (`brand`, semibold).
    pub fn brand(mut self, brand: impl Into<SharedString>) -> Self {
        self.brand = brand.into();
        self
    }

    /// Run when the name is activated (`href`).
    pub fn on_brand_click(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
        self.on_brand_click = Some(Rc::new(f));
        self
    }

    /// Append a navigation item.
    pub fn item(mut self, item: NavItem) -> Self {
        self.items.push(item);
        self
    }

    /// Append a global action (`HeaderGlobalBar`), e.g. a 48px icon button.
    pub fn action(mut self, action: impl IntoElement) -> Self {
        self.actions.push(action.into_any_element());
        self
    }
}

/// Pointer state of one header item.
#[derive(Default)]
struct Pointer {
    hovered: bool,
    pressed: bool,
}

#[allow(clippy::too_many_arguments)]
fn header_item(
    id: ElementId,
    label: SharedString,
    current: bool,
    in_menu: bool,
    expanded: Option<bool>,
    focus: FocusHandle,
    on_click: Callback,
    on_key: Option<KeyHandler>,
    window: &mut Window,
    cx: &mut App,
) -> AnyElement {
    let pointer: Entity<Pointer> =
        window.use_keyed_state((id.clone(), "pointer"), cx, |_, _| Pointer::default());
    let (hovered, pressed) = {
        let p = pointer.read(cx);
        (p.hovered, p.pressed)
    };
    let (mut bg, text) = item_colors(in_menu, current, hovered, pressed);
    if expanded == Some(true) {
        // `.cds--header__menu-title[aria-expanded=true] { background-color: var(--layer) }`.
        bg = color(ColorRole::Layer01);
    }
    let bg = motion::animate_color((id.clone(), "bg"), bg, ITEM_MOTION, window, cx);
    let text = motion::animate_color((id.clone(), "text"), text, ITEM_MOTION, window, cx);
    let focused = focus.is_focused(window);
    let rotation =
        expanded.map(|open| motion::chevron_rotation((id.clone(), "arrow"), open, window, cx));
    gpui_kit::base::Button::new(id.clone())
        .track_focus(&focus)
        .accessibility_label(label.clone())
        .relative()
        // `.cds--header__menu-item { block-size: 100% }` of the header's
        // content box (3rem minus its 1px bottom border), so the current bar
        // sits fully above that border; submenu items are 3rem.
        .map(|this| {
            if in_menu {
                this.h(rem(HEADER_HEIGHT)).w_full()
            } else {
                this.h_full()
            }
        })
        .flex()
        .flex_row()
        .items_center()
        .justify_start()
        .px(rem(16.))
        .bg(bg)
        .text_color(text)
        .type_style(TypeStyle::BodyCompact01)
        .whitespace_nowrap()
        // `border: 2px solid transparent`, `:focus { border-color: var(--focus) }`.
        .border_2()
        .border_color(if focused {
            color(ColorRole::Focus)
        } else {
            Hsla::transparent_black()
        })
        .cursor(CursorStyle::PointingHand)
        .on_hover({
            let pointer = pointer.clone();
            move |h, _, cx| {
                pointer.update(cx, |p, cx| {
                    p.hovered = *h;
                    if !*h {
                        p.pressed = false;
                    }
                    cx.notify();
                })
            }
        })
        .on_mouse_down(gpui_kit::MouseButton::Left, {
            let pointer = pointer.clone();
            move |_, _, cx| {
                pointer.update(cx, |p, cx| {
                    p.pressed = true;
                    cx.notify();
                })
            }
        })
        .on_mouse_up(gpui_kit::MouseButton::Left, move |_, _, cx| {
            pointer.update(cx, |p, cx| {
                p.pressed = false;
                cx.notify();
            })
        })
        .on_click(move |_, window, cx| on_click(window, cx))
        .when_some(on_key, |this, on_key| {
            this.on_key_down(move |event, window, cx| on_key(event, window, cx))
        })
        .child(label)
        .when_some(rotation, |this, rotation| {
            this.child(
                div().ml(rem(8.)).child(
                    Icon::carbon(CarbonIcon::ChevronDown)
                        .size(IconSize::S16)
                        .color(color(ColorRole::IconSecondary))
                        .rotate(gpui_kit::radians(rotation)),
                ),
            )
        })
        .when(current, |this| {
            this.child(if in_menu {
                // Submenu current: a 3px start bar.
                div()
                    .absolute()
                    .top(px(-2.))
                    .bottom(px(-2.))
                    .left(px(-2.))
                    .w(px(3.))
                    .bg(color(ColorRole::BorderInteractive))
            } else {
                // `--current::after { block-size: 3px; inset-block-end: -2px }`.
                div()
                    .absolute()
                    .left(px(-2.))
                    .right(px(-2.))
                    .bottom(px(-2.))
                    .h(px(3.))
                    .bg(color(ColorRole::BorderInteractive))
            })
        })
        .into_any_element()
}

/// Open state and focus handles of one header menu.
struct MenuState {
    open: bool,
    title: FocusHandle,
    items: Vec<FocusHandle>,
}

impl RenderOnce for NavigationMenu {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let id = self.id.clone();
        let mut nav = div().flex().flex_row().h_full();
        for (index, item) in self.items.into_iter().enumerate() {
            let item_id = ElementId::NamedChild(
                std::sync::Arc::new(id.clone()),
                SharedString::from(format!("item-{index}")),
            );
            if item.items.is_empty() {
                let focus = window
                    .use_keyed_state((item_id.clone(), "focus"), cx, |_, cx| cx.focus_handle())
                    .read(cx)
                    .clone();
                let on_click = item.on_click.clone();
                nav = nav.child(header_item(
                    item_id,
                    item.label,
                    item.active,
                    false,
                    None,
                    focus,
                    Rc::new(move |window, cx| {
                        if let Some(f) = &on_click {
                            f(window, cx)
                        }
                    }),
                    None,
                    window,
                    cx,
                ));
                continue;
            }
            let count = item.items.len();
            let state = window.use_keyed_state((item_id.clone(), "menu"), cx, |_, cx| MenuState {
                open: false,
                title: cx.focus_handle(),
                items: Vec::new(),
            });
            if state.read(cx).items.len() < count {
                state.update(cx, |s, cx| {
                    while s.items.len() < count {
                        s.items.push(cx.focus_handle());
                    }
                });
            }
            let (open, title_focus, item_focus) = {
                let s = state.read(cx);
                (s.open, s.title.clone(), s.items.clone())
            };
            let set_open: SetMenu = {
                let state = state.clone();
                Rc::new(move |open, focus_item, window, cx| {
                    let (title, items) = state.update(cx, |s, cx| {
                        s.open = open;
                        cx.notify();
                        (s.title.clone(), s.items.clone())
                    });
                    match (open, focus_item) {
                        (true, Some(i)) => {
                            let handle = items[i].clone();
                            window.defer(cx, move |window, cx| handle.focus(window, cx));
                        }
                        (false, _) if items.iter().any(|h| h.is_focused(window)) => {
                            title.focus(window, cx)
                        }
                        _ => {}
                    }
                    window.refresh();
                })
            };
            let title = header_item(
                (item_id.clone(), "title").into(),
                item.label.clone(),
                item.active || item.items.iter().any(|i| i.active),
                false,
                Some(open),
                title_focus.clone(),
                {
                    let set_open = set_open.clone();
                    Rc::new(move |window, cx| set_open(!open, None, window, cx))
                },
                Some({
                    let set_open = set_open.clone();
                    Rc::new(
                        move |event: &KeyDownEvent, window: &mut Window, cx: &mut App| {
                            match event.keystroke.key.as_str() {
                                "down" => set_open(true, Some(0), window, cx),
                                // Opened with the pointer, focus stays on the
                                // title: Escape still closes the menu
                                // (`HeaderMenu` handles Escape on the whole item).
                                "escape" if open => set_open(false, None, window, cx),
                                _ => return,
                            }
                            cx.stop_propagation();
                        },
                    )
                }),
                window,
                cx,
            );
            let on_tab = {
                let set_open = set_open.clone();
                let title = title_focus.clone();
                let items = item_focus.clone();
                move |forward: bool, window: &mut Window, cx: &mut App| {
                    let at = if title.is_focused(window) {
                        None
                    } else if let Some(i) = items.iter().position(|h| h.is_focused(window)) {
                        Some(i)
                    } else {
                        cx.propagate();
                        return;
                    };
                    match (at, forward) {
                        // A closed menu's title is an ordinary tab stop.
                        (None, _) if !open => {
                            cx.propagate();
                            return;
                        }
                        (None, true) => set_open(true, Some(0), window, cx),
                        (None, false) => {
                            set_open(false, None, window, cx);
                            window.focus_prev(cx);
                        }
                        (Some(i), true) if i + 1 < count => set_open(true, Some(i + 1), window, cx),
                        (Some(_), true) => {
                            // Past the last item: close, and move on from
                            // the title to what follows the menu (the items
                            // are still in the last frame's tab order).
                            set_open(false, None, window, cx);
                            for _ in 0..=count {
                                window.focus_next(cx);
                                if !items.iter().any(|h| h.is_focused(window)) {
                                    break;
                                }
                            }
                        }
                        (Some(0), false) => set_open(false, None, window, cx),
                        (Some(i), false) => set_open(true, Some(i - 1), window, cx),
                    }
                    cx.stop_propagation();
                }
            };
            let on_tab = Rc::new(on_tab);
            let popup = gpui_kit::base::Popup::new((item_id.clone(), "popup"), title)
                .anchor(Anchor::TopLeft)
                .h_full()
                .key_context(KEY_CONTEXT)
                .on_action({
                    let on_tab = on_tab.clone();
                    move |_: &TabNext, window, cx| on_tab(true, window, cx)
                })
                .on_action(move |_: &TabPrev, window, cx| on_tab(false, window, cx));
            if !open {
                nav = nav.child(popup);
                continue;
            }
            let mut menu = div()
                .id((item_id.clone(), "list"))
                .w(rem(MENU_WIDTH))
                .flex()
                .flex_col()
                .bg(color(ColorRole::Layer01))
                .shadow(menu_shadow())
                .on_mouse_down_out({
                    let set_open = set_open.clone();
                    move |_, window, cx| {
                        if open {
                            set_open(false, None, window, cx)
                        }
                    }
                });
            for (i, link) in item.items.into_iter().enumerate() {
                let on_click = link.on_click.clone();
                let set_close = set_open.clone();
                let set_key = set_open.clone();
                menu = menu.child(header_item(
                    ElementId::NamedChild(
                        std::sync::Arc::new(item_id.clone()),
                        SharedString::from(format!("link-{i}")),
                    ),
                    link.label,
                    link.active,
                    true,
                    None,
                    item_focus[i].clone(),
                    Rc::new(move |window, cx| {
                        if let Some(f) = &on_click {
                            f(window, cx)
                        }
                        set_close(false, None, window, cx);
                    }),
                    Some(Rc::new(
                        move |event: &KeyDownEvent, window: &mut Window, cx: &mut App| {
                            match event.keystroke.key.as_str() {
                                "down" => set_key(true, Some((i + 1) % count), window, cx),
                                "up" => set_key(true, Some((i + count - 1) % count), window, cx),
                                "escape" => set_key(false, None, window, cx),
                                _ => return,
                            }
                            cx.stop_propagation();
                        },
                    )),
                    window,
                    cx,
                ));
            }
            // The open title sits above its menu (`[aria-expanded=true]`
            // z-index 8002 over the menu's 8001), so the menu's shadow never
            // falls on the title: clip the part above the menu's top edge.
            let pad = rem(MENU_SHADOW_REACH);
            let menu = div()
                .overflow_hidden()
                .ml(rem(-MENU_SHADOW_REACH))
                .pl(pad)
                .pr(pad)
                .pb(pad)
                .child(menu.test_support());
            nav = nav.child(popup.content(menu));
        }

        let brand_focus = window
            .use_keyed_state((id.clone(), "brand-focus"), cx, |_, cx| cx.focus_handle())
            .read(cx)
            .clone();
        let brand_focused = brand_focus.is_focused(window);
        let on_brand = self.on_brand_click.clone();
        div()
            .id(id.clone())
            .w_full()
            .h(rem(HEADER_HEIGHT))
            .flex()
            .flex_row()
            .items_center()
            .bg(color(ColorRole::Background))
            .border_b_1()
            .border_color(color(ColorRole::BorderSubtle01))
            .child(
                // `a.cds--header__name`: padding 0 2rem 0 1rem, 2px focus border.
                gpui_kit::base::Button::new((id.clone(), "name"))
                    .track_focus(&brand_focus)
                    .accessibility_label(self.brand.clone())
                    .h_full()
                    // In a bar too narrow for everything the name gives way
                    // first, down to its padding, its text ellipsized, so the
                    // links (Manage's chevron and focus ring) and the global
                    // actions still fit; then the links shrink.
                    .min_w_0()
                    .flex_shrink(NAME_SHRINK)
                    .flex()
                    .flex_row()
                    .items_center()
                    .pl(rem(16.))
                    .pr(rem(32.))
                    .border_2()
                    .border_color(if brand_focused {
                        color(ColorRole::Focus)
                    } else {
                        Hsla::transparent_black()
                    })
                    .type_style(TypeStyle::BodyCompact01)
                    .text_color(color(ColorRole::TextPrimary))
                    .whitespace_nowrap()
                    .cursor(CursorStyle::PointingHand)
                    .on_click(move |_, window, cx| {
                        if let Some(f) = &on_brand {
                            f(window, cx)
                        }
                    })
                    .when(!self.brand_prefix.is_empty(), |this| {
                        this.child(
                            div()
                                .flex_none()
                                .mr(rem(4.))
                                .child(self.brand_prefix.clone()),
                        )
                    })
                    .child(
                        div()
                            .min_w_0()
                            .overflow_hidden()
                            .text_ellipsis()
                            .font_weight(FontWeight::SEMIBOLD)
                            .child(self.brand.clone()),
                    ),
            )
            .child(
                // `.cds--header__nav { padding-inline-start: 1rem }` with a 1.5rem rule.
                // It gives way first when the bar is narrow, so the global
                // actions always fit (they paint over whatever overflows).
                div()
                    .relative()
                    .h_full()
                    .min_w_0()
                    .flex_shrink(1.)
                    .pl(rem(16.))
                    .child(
                        div()
                            .absolute()
                            .left_0()
                            .top(rem(12.))
                            .h(rem(24.))
                            .w(px(1.))
                            .bg(color(ColorRole::BorderSubtle01)),
                    )
                    .child(nav),
            )
            .child(
                // `.cds--header__global { display: flex; flex: 1 1; justify-content:
                // flex-end; block-size: 100% }`: no `align-items`, so a 32px
                // compact action sits at the top of the 48px bar.
                div()
                    .flex_1()
                    .flex_shrink_0()
                    .h_full()
                    .flex()
                    .flex_row()
                    .justify_end()
                    .items_start()
                    .bg(color(ColorRole::Background))
                    .children(self.actions),
            )
    }
}

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

    fn hex(c: Hsla) -> String {
        let c = c.to_rgb();
        let b = |v: f32| (v * 255.).round() as u8;
        format!("#{:02x}{:02x}{:02x}", b(c.r), b(c.g), b(c.b))
    }

    #[test]
    fn item_colors_follow_header_css() {
        crate::theme::tests_set(CarbonTheme::White);
        let (bg, text) = item_colors(false, false, false, false);
        assert_eq!((hex(bg), hex(text)), ("#ffffff".into(), "#525252".into()));
        // The current item stays `text-secondary` (`a.cds--header__menu-item`
        // outranks `.cds--header__menu-item--current`).
        let (_, text) = item_colors(false, true, false, false);
        assert_eq!(hex(text), "#525252");
        let (_, text) = item_colors(false, true, true, false);
        assert_eq!(hex(text), "#161616");
        let (bg, _) = item_colors(true, true, false, false);
        assert_eq!(hex(bg), "#e0e0e0");
        let (bg, _) = item_colors(true, false, true, false);
        assert_eq!(hex(bg), "#e8e8e8");
        assert_eq!((HEADER_HEIGHT, MENU_WIDTH), (48., 200.));
        let shadow = &menu_shadow()[0];
        assert_eq!((shadow.offset.y, shadow.blur_radius), (px(4.), px(8.)));
    }

    #[test]
    fn menu_clip_spares_the_whole_shadow() {
        // The clip pads the menu by MENU_SHADOW_REACH on the sides and bottom;
        // the shadow must fade out inside it (3σ of GPUI's gaussian + offset).
        let shadow = &menu_shadow()[0];
        let reach = px(MENU_SHADOW_REACH);
        assert!(reach >= shadow.offset.x.abs() + shadow.blur_radius * 3. + shadow.spread_radius);
        assert!(reach >= shadow.offset.y + shadow.blur_radius * 3. + shadow.spread_radius);
    }
}