u0ui 0.3.16

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
//! Tabs: shadcn `Tabs` (by `value`) → Carbon `Tabs` / `TabList` / `Tab` /
//! `TabPanels` (`.cds--tabs`, `.cds--tab-content`).
//!
//! - **Behavior** is Kit's: [`gpui_kit::base::Tabs`] / [`gpui_kit::base::Tab`]
//!   implement the ARIA tabs pattern (one tab stop, ←/→ and Home/End move
//!   focus, Enter/Space activate, disabled tabs skipped). Activation is
//!   automatic by default, as Carbon's `Tabs` (`activation="automatic"`):
//!   ←/→/Home/End also select the tab they move to; [`TabsActivation::Manual`]
//!   keeps Kit's focus-only arrows. Controlled or not.
//! - **Appearance** ([`TabLook`]): `line` tabs are `size-md` tall with a 2px
//!   bottom indicator (`border-subtle`, hover `border-strong`, selected
//!   `border-interactive`), `text-secondary` labels that turn `text-primary`
//!   on hover and heading-compact-01 when selected, 1px apart. `contained`
//!   tabs are `size-lg` on `layer-accent` with a 1px `border-strong` divider,
//!   `layer-accent-hover` on hover, and the selected tab on `layer` with a 2px
//!   `border-interactive` top line; `full_width` splits the row equally.
//!   Disabled: `text-disabled` (contained: `button-disabled` fill,
//!   `text-on-color-disabled`). Keyboard focus: a 2px inset `focus` outline.
//!   The panel is padded 1rem (`.cds--tab-content`), on `layer` when contained.
//! - **Panel**: once any `content` is given, the selected tab always gets a
//!   panel (Carbon renders a `TabPanel` per tab, empty when it has no
//!   content), so a tab without content shows an empty padded panel. The
//!   panel is a tab stop (`TabPanel tabIndex=0`) with a 2px inset `focus`
//!   outline while focused (`.cds--tab-content:focus`).
//! - **Panel gap**: Carbon's `Tabs` renders no wrapper, so the tab list and
//!   the panel are siblings of the surrounding layout and take its gap (the
//!   reference previews sit in `.cu-stack { gap: spacing-06 }`).
//!   [`Tabs::panel_gap`] reproduces that gap; it is 0 by default.
//! - **Flush**: a tab set inside a card whose own padding already insets
//!   it (`.np-card .cds--tab-content { padding: 24px 0 0 }` and
//!   `.np-card [role=tab]:first-child { padding-left: 0 }` on the
//!   NoProjects board) lies flush with the card's content, [`Tabs::flush`]:
//!   the panel has no padding, its distance from the list given by
//!   `panel_gap`, and the first tab no padding before its label, so its
//!   label and its indicator begin at the card's content edge, as the
//!   panel's content does. The panel stays a tab stop with its focus
//!   outline; the first tab's focus ring lies 2px into the card's padding.
//!   Line tabs laid flush are ruled across the card under the list
//!   (`.np-card .cds--tabs { box-shadow: inset 0 -1px 0
//!   var(--border-subtle-01) }`): one 1px `border-subtle-01` line from the
//!   first tab to the card's content edge, under each tab's indicator.
//! - **Motion**: `transition: color 70ms, border 70ms, background-color 70ms`
//!   (productive standard) on every tab.
use super::{form::inset_outline, overlay::rem};
use crate::{
    icons::{Icon, IconSize},
    motion::{self, Curve, Motion, Speed},
    theme::color,
    tokens::{ColorRole, SIZE_LG, SIZE_MD, TypeStyle},
    typography::TypeStyled as _,
};
use gpui_kit::{
    AbsoluteLength, AnyElement, App, CursorStyle, ElementId, Hsla, InteractiveElement, IntoElement,
    ParentElement, RenderOnce, SharedString, StatefulInteractiveElement as _, Styled, Window, div,
    prelude::FluentBuilder as _, px,
};
use std::rc::Rc;

/// Width in px of a tab's inset focus ring, drawn as a border inside the
/// tab's padding (the padding gives up the same width).
const FOCUS_RING: f32 = 2.;

/// `.cds--tabs__nav-item { transition: background-color 70ms cubic-bezier(0.2, 0, 0.38, 0.9) }`.
pub const TAB_MOTION: Motion = Motion::new(Curve::ProductiveStandard, Speed::Fast01);

/// `index.d.ts` `TabsProps.variant`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum TabsVariant {
    /// `line` (default).
    #[default]
    Line,
    /// `contained`.
    Contained,
}

impl TabsVariant {
    /// Both variants.
    pub const ALL: [TabsVariant; 2] = [Self::Line, Self::Contained];

    /// The `index.d.ts` name.
    pub const fn name(self) -> &'static str {
        match self {
            Self::Line => "line",
            Self::Contained => "contained",
        }
    }

    /// Tab height in px: `--layout-size-height-local` is md for line tabs and
    /// lg for contained ones.
    pub const fn height(self) -> f32 {
        match self {
            Self::Line => SIZE_MD.px_value(),
            Self::Contained => SIZE_LG.px_value(),
        }
    }
}

/// Carbon `Tabs` `activation`: whether moving focus with the arrow keys
/// selects the tab.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum TabsActivation {
    /// Arrows, Home and End select the tab they move to (Carbon's default).
    #[default]
    Automatic,
    /// Arrows only move focus; Enter or Space selects.
    Manual,
}

impl TabsActivation {
    /// Both modes.
    pub const ALL: [TabsActivation; 2] = [Self::Automatic, Self::Manual];

    /// Carbon's name.
    pub const fn name(self) -> &'static str {
        match self {
            Self::Automatic => "automatic",
            Self::Manual => "manual",
        }
    }
}

/// The tab an arrow/Home/End key moves to from `from` in automatic
/// activation, skipping disabled tabs and wrapping (Kit's focus rule).
pub fn automatic_target(key: &str, from: usize, disabled: &[bool]) -> Option<usize> {
    let n = disabled.len();
    let enabled = |i: &usize| !disabled[*i];
    match key {
        "home" => (0..n).find(enabled),
        "end" => (0..n).rev().find(enabled),
        "right" | "left" => {
            let step = if key == "right" { 1 } else { n - 1 };
            (1..n).map(|k| (from + k * step) % n).find(enabled)
        }
        _ => None,
    }
}

/// The state a tab is drawn in.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct TabState {
    /// The selected tab.
    pub selected: bool,
    /// Pointer over it.
    pub hovered: bool,
    /// Disabled.
    pub disabled: bool,
}

/// The colors of one tab.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TabLook {
    /// Tab fill.
    pub background: Hsla,
    /// Label color.
    pub text: Hsla,
    /// The 2px indicator: bottom (line) or top (contained, selected only).
    pub indicator: Hsla,
    /// Contained tabs' 1px left divider (`box-shadow: -1px 0 0 0 border-strong`).
    pub divider: Hsla,
}

impl TabLook {
    /// The look of a tab of `variant` in `state` on the active theme.
    pub fn of(variant: TabsVariant, state: TabState) -> Self {
        use ColorRole::*;
        let clear = Hsla::transparent_black();
        match variant {
            TabsVariant::Line => {
                let (text, indicator) = if state.disabled {
                    // `.cds--tabs__nav-item--disabled`.
                    (color(TextDisabled), color(BorderSubtle01))
                } else if state.selected {
                    // `.cds--tabs__nav-item--selected { border-block-end: 2px solid border-interactive }`.
                    (color(TextPrimary), color(BorderInteractive))
                } else if state.hovered {
                    // `:hover { border-block-end: 2px solid border-strong; color: text-primary }`.
                    (color(TextPrimary), color(BorderStrong01))
                } else {
                    // `.cds--tabs__nav-link { border-block-end: 2px solid border-subtle; color: text-secondary }`.
                    (color(TextSecondary), color(BorderSubtle01))
                };
                Self {
                    background: clear,
                    text,
                    indicator,
                    divider: clear,
                }
            }
            TabsVariant::Contained => {
                let (background, text, indicator) = if state.disabled {
                    (color(ButtonDisabled), color(TextOnColorDisabled), clear)
                } else if state.selected {
                    // `--selected { background-color: var(--layer); box-shadow: inset 0 2px 0 0 border-interactive }`.
                    (color(Layer01), color(TextPrimary), color(BorderInteractive))
                } else if state.hovered {
                    (color(LayerAccentHover01), color(TextPrimary), clear)
                } else {
                    (color(LayerAccent01), color(TextSecondary), clear)
                };
                Self {
                    background,
                    text,
                    indicator,
                    divider: color(BorderStrong01),
                }
            }
        }
    }
}

/// The tab panel (`.cds--tab-content`).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PanelLook {
    /// `.cds--tab-content { padding: layout-density-padding-inline-local }` (1rem).
    pub padding: f32,
    /// `.cds--tabs--contained ~ .cds--tab-content { background: var(--layer) }`;
    /// transparent for line tabs.
    pub background: Hsla,
    /// `.cds--tab-content:focus { outline: 2px solid var(--focus); outline-offset: -2px }`.
    pub focus: Hsla,
    /// The focus outline width.
    pub focus_width: f32,
}

impl PanelLook {
    /// The panel of `variant` tabs on the active theme.
    pub fn of(variant: TabsVariant) -> Self {
        Self {
            padding: 16.,
            background: match variant {
                TabsVariant::Line => Hsla::transparent_black(),
                TabsVariant::Contained => color(ColorRole::Layer01),
            },
            focus: color(ColorRole::Focus),
            focus_width: 2.,
        }
    }
}

/// Whether a panel is drawn: Carbon renders `TabPanels` only when some
/// content exists, and then one `TabPanel` per tab (empty without content).
pub fn shows_panel(content_count: usize) -> bool {
    content_count > 0
}

/// One tab (`TabsTrigger value`).
pub struct TabsTrigger {
    value: SharedString,
    label: SharedString,
    disabled: bool,
    icon: Option<Icon>,
}

impl TabsTrigger {
    /// A tab for `value` showing `label`.
    pub fn new(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
        Self {
            value: value.into(),
            label: label.into(),
            disabled: false,
            icon: None,
        }
    }

    /// Disable the tab.
    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    /// A trailing icon (`renderIcon`).
    pub fn icon(mut self, icon: impl Into<Icon>) -> Self {
        self.icon = Some(icon.into());
        self
    }
}

type ValueChange = Rc<dyn Fn(SharedString, &mut Window, &mut App)>;

/// Carbon tabs. See the module docs.
#[derive(IntoElement)]
pub struct Tabs {
    id: ElementId,
    variant: TabsVariant,
    full_width: bool,
    value: Option<SharedString>,
    default_value: Option<SharedString>,
    on_value_change: Option<ValueChange>,
    triggers: Vec<TabsTrigger>,
    contents: Vec<(SharedString, AnyElement)>,
    label: SharedString,
    activation: TabsActivation,
    panel_gap: AbsoluteLength,
    flush: bool,
}

impl Tabs {
    /// Tabs with a stable `id`.
    pub fn new(id: impl Into<ElementId>) -> Self {
        Self {
            id: id.into(),
            variant: TabsVariant::Line,
            full_width: false,
            value: None,
            default_value: None,
            on_value_change: None,
            triggers: Vec::new(),
            contents: Vec::new(),
            label: SharedString::default(),
            activation: TabsActivation::Automatic,
            panel_gap: rem(0.).into(),
            flush: false,
        }
    }

    /// `line` or `contained`.
    pub fn variant(mut self, variant: TabsVariant) -> Self {
        self.variant = variant;
        self
    }

    /// Contained tabs share the row equally.
    pub fn full_width(mut self, full_width: bool) -> Self {
        self.full_width = full_width;
        self
    }

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

    /// Initially selected value when uncontrolled (default: the first tab).
    pub fn default_value(mut self, value: impl Into<SharedString>) -> Self {
        self.default_value = Some(value.into());
        self
    }

    /// Called when a tab is activated.
    pub fn on_value_change(
        mut self,
        f: impl Fn(SharedString, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_value_change = Some(Rc::new(f));
        self
    }

    /// Append a tab.
    pub fn trigger(mut self, trigger: TabsTrigger) -> Self {
        self.triggers.push(trigger);
        self
    }

    /// The panel shown for `value` (`TabsContent value`).
    pub fn content(mut self, value: impl Into<SharedString>, content: impl IntoElement) -> Self {
        self.contents
            .push((value.into(), content.into_any_element()));
        self
    }

    /// Automatic (default) or manual activation.
    pub fn activation(mut self, activation: TabsActivation) -> Self {
        self.activation = activation;
        self
    }

    /// The gap between the tab list and the panel: the gap of the layout the
    /// tabs sit in, since Carbon's `Tabs` renders the list and the panel as
    /// siblings of that layout (see the module docs). Default 0.
    pub fn panel_gap(mut self, gap: impl Into<AbsoluteLength>) -> Self {
        self.panel_gap = gap.into();
        self
    }

    /// Lay the tabs flush with a card already padded: the panel without
    /// `.cds--tab-content`'s padding, the first tab without padding before
    /// its label, and line tabs ruled across the card (see the module
    /// docs). Default false.
    pub fn flush(mut self, flush: bool) -> Self {
        self.flush = flush;
        self
    }

    /// The tab list's accessible name.
    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
        self.label = label.into();
        self
    }
}

impl RenderOnce for Tabs {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let id = self.id.clone();
        let first = self.triggers.first().map(|t| t.value.clone());
        let initial = self.default_value.clone().or(first).unwrap_or_default();
        let internal = window.use_keyed_state((id.clone(), "value"), cx, |_, _| initial);
        let selected = self
            .value
            .clone()
            .unwrap_or_else(|| internal.read(cx).clone());
        let variant = self.variant;
        let height = variant.height();

        let mut list = gpui_kit::base::Tabs::new((id.clone(), "list"))
            .flex()
            .flex_row()
            .when(
                self.full_width && variant == TabsVariant::Contained,
                |this| this.w_full(),
            );
        let count = self.triggers.len();
        let flush = self.flush;
        let selected_index = self.triggers.iter().position(|t| t.value == selected);
        // Automatic activation: select where the arrow keys take focus. Kit
        // moves focus in its own key handler; this runs in the capture phase
        // with the same rule, from the selected tab (which has focus).
        let automatic = (self.activation == TabsActivation::Automatic).then(|| {
            let values: Vec<SharedString> = self.triggers.iter().map(|t| t.value.clone()).collect();
            let disabled: Vec<bool> = self.triggers.iter().map(|t| t.disabled).collect();
            let internal = internal.clone();
            let on_change = self.on_value_change.clone();
            move |event: &gpui_kit::KeyDownEvent, window: &mut Window, cx: &mut App| {
                if event.keystroke.modifiers.modified() {
                    return;
                }
                let Some(from) = selected_index else {
                    return;
                };
                let rtl = gpui_kit::base::LayoutDirection::global(cx).is_rtl();
                let key = match (event.keystroke.key.as_str(), rtl) {
                    ("left", true) => "right",
                    ("right", true) => "left",
                    (key, _) => key,
                };
                let Some(to) = automatic_target(key, from, &disabled) else {
                    return;
                };
                if to == from {
                    return;
                }
                let value = values[to].clone();
                internal.update(cx, |v, cx| {
                    *v = value.clone();
                    cx.notify();
                });
                if let Some(f) = &on_change {
                    f(value, window, cx);
                }
            }
        });
        for (index, trigger) in self.triggers.into_iter().enumerate() {
            let tab_id = ElementId::NamedChild(
                std::sync::Arc::new(id.clone()),
                SharedString::from(format!("tab-{}", trigger.value)),
            );
            let hover = window.use_keyed_state((tab_id.clone(), "hover"), cx, |_, _| false);
            let state = TabState {
                selected: trigger.value == selected,
                hovered: *hover.read(cx),
                disabled: trigger.disabled,
            };
            let look = TabLook::of(variant, state);
            let animate =
                |channel: &'static str, target: Hsla, window: &mut Window, cx: &mut App| {
                    motion::animate_color((tab_id.clone(), channel), target, TAB_MOTION, window, cx)
                };
            let background = animate("bg", look.background, window, cx);
            let text = animate("text", look.text, window, cx);
            let indicator = animate("indicator", look.indicator, window, cx);
            let value = trigger.value.clone();
            let on_change = self.on_value_change.clone();
            let internal = internal.clone();
            // The divider (`box-shadow: -1px 0 0 0 border-strong` on every tab
            // after the first) gives way on the selected tab to its top line
            // (`--selected { box-shadow: inset 0 2px … }`) and is dropped on
            // the tab after it (`--selected + .cds--tabs__nav-item { box-shadow: none }`).
            let no_divider = state.selected || selected_index.is_some_and(|s| s + 1 == index);
            // Flush, the first tab's label begins at the list's edge: no
            // padding before it, and its focus ring's border drawn left of
            // the edge.
            let flush_first = flush && index == 0;
            let tab = gpui_kit::base::Tab::new(tab_id.clone())
                .selected(state.selected)
                .disabled(trigger.disabled)
                .set_position(index + 1, count)
                .accessibility_label(trigger.label.clone())
                .relative()
                .h(rem(height))
                .flex()
                .flex_row()
                .items_center()
                .gap(rem(8.))
                // `.cds--tabs__nav-link { padding-inline: 1rem }`, less the
                // transparent 2px border that draws the inset focus ring
                // (`outline: 2px solid var(--focus); outline-offset: -2px`):
                // the ring sits inside the tab, so the tab is as wide as
                // Carbon's (label + 2rem), not 4px wider.
                .px(rem(16. - FOCUS_RING))
                .when(flush_first, |this| this.pl_0().ml(px(-FOCUS_RING)))
                .border_2()
                .border_color(Hsla::transparent_black())
                .focus_visible(|s| s.border_color(color(ColorRole::Focus)))
                .bg(background)
                .text_color(text)
                .whitespace_nowrap()
                .map(|this| {
                    if state.selected {
                        this.type_style(TypeStyle::HeadingCompact01)
                    } else {
                        this.type_style(TypeStyle::BodyCompact01)
                    }
                })
                .cursor(if trigger.disabled {
                    CursorStyle::OperationNotAllowed
                } else {
                    CursorStyle::PointingHand
                })
                .when(variant == TabsVariant::Line && index > 0, |this| {
                    this.ml(px(1.))
                })
                .when(
                    self.full_width && variant == TabsVariant::Contained,
                    |this| this.flex_1().min_w_0(),
                )
                .on_hover(move |hovered, _, cx| {
                    hover.update(cx, |h, cx| {
                        *h = *hovered;
                        cx.notify();
                    })
                })
                .on_click(move |_, window, cx| {
                    internal.update(cx, |v, cx| {
                        *v = value.clone();
                        cx.notify();
                    });
                    if let Some(f) = &on_change {
                        f(value.clone(), window, cx);
                    }
                })
                .child(div().flex_1().min_w_0().child(trigger.label.clone()))
                .when_some(trigger.icon, |this, icon| {
                    this.child(icon.size(IconSize::S16).color(text))
                })
                .child(match variant {
                    // The bottom indicator covers the reserved border.
                    TabsVariant::Line => div()
                        .absolute()
                        .left(px(if flush_first { 0. } else { -2. }))
                        .right(px(-2.))
                        .bottom(px(-2.))
                        .h(px(2.))
                        .bg(indicator),
                    TabsVariant::Contained => div()
                        .absolute()
                        .left(px(-2.))
                        .right(px(-2.))
                        .top(px(-2.))
                        .h(px(2.))
                        .bg(indicator),
                })
                .when(
                    variant == TabsVariant::Contained && index > 0 && !no_divider,
                    |this| {
                        this.child(
                            div()
                                .absolute()
                                .left(px(-3.))
                                .top(px(-2.))
                                .bottom(px(-2.))
                                .w(px(1.))
                                .bg(look.divider),
                        )
                    },
                );
            list = list.child(tab);
        }

        let show_panel = shows_panel(self.contents.len());
        let content = self
            .contents
            .into_iter()
            .find(|(value, _)| *value == selected)
            .map(|(_, content)| content);
        let panel = show_panel.then(|| {
            let look = PanelLook::of(variant);
            let focus = window
                .use_keyed_state((id.clone(), "panel-focus"), cx, |_, cx| cx.focus_handle())
                .read(cx)
                .clone();
            let focused = focus.is_focused(window);
            div()
                .id((id.clone(), "panel"))
                // `TabPanel tabIndex=0`.
                .track_focus(&focus.tab_stop(true))
                .relative()
                .p(rem(if flush { 0. } else { look.padding }))
                .type_style(TypeStyle::Body01)
                .text_color(color(ColorRole::TextPrimary))
                .bg(look.background)
                .children(content)
                .when(focused, |this| {
                    this.child(inset_outline(look.focus_width, look.focus))
                })
        });
        div()
            .flex()
            .flex_col()
            .gap(self.panel_gap)
            .w_full()
            .child(
                div()
                    .relative()
                    .when_some(automatic, |this, on_key| this.capture_key_down(on_key))
                    // Under the tabs, the rule across the card
                    // (`.np-card .cds--tabs { box-shadow: inset 0 -1px 0
                    // var(--border-subtle-01) }`), drawn first so each
                    // tab's indicator lies over it.
                    .when(ruled(flush, variant), |this| {
                        this.child(
                            div()
                                .absolute()
                                .left_0()
                                .right_0()
                                .bottom_0()
                                .h(px(1.))
                                .bg(color(ColorRole::BorderSubtle01)),
                        )
                    })
                    .child(list),
            )
            .children(panel)
    }
}

/// Whether the list is ruled across under its tabs: line tabs laid flush
/// in a card (`.np-card .cds--tabs`).
fn ruled(flush: bool, variant: TabsVariant) -> bool {
    flush && variant == TabsVariant::Line
}

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

    #[test]
    fn only_line_tabs_laid_flush_are_ruled_across_the_card() {
        assert!(ruled(true, TabsVariant::Line));
        assert!(!ruled(false, TabsVariant::Line));
        assert!(!ruled(true, TabsVariant::Contained));
    }

    #[test]
    fn automatic_activation_moves_like_kit_focus() {
        let disabled = [false, true, false, false];
        assert_eq!(TabsActivation::default(), TabsActivation::Automatic);
        assert_eq!(automatic_target("right", 0, &disabled), Some(2));
        assert_eq!(automatic_target("right", 3, &disabled), Some(0));
        assert_eq!(automatic_target("left", 0, &disabled), Some(3));
        assert_eq!(automatic_target("left", 2, &disabled), Some(0));
        assert_eq!(automatic_target("home", 3, &disabled), Some(0));
        assert_eq!(automatic_target("end", 0, &disabled), Some(3));
        assert_eq!(automatic_target("enter", 0, &disabled), None);
    }
    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 line_tab_states_follow_bundle_css() {
        crate::theme::tests_set(CarbonTheme::White);
        let rest = TabLook::of(TabsVariant::Line, TabState::default());
        assert_eq!(
            (hex(rest.text), hex(rest.indicator)),
            ("#525252".into(), "#c6c6c6".into())
        );
        let hover = TabLook::of(
            TabsVariant::Line,
            TabState {
                hovered: true,
                ..Default::default()
            },
        );
        assert_eq!(
            (hex(hover.text), hex(hover.indicator)),
            ("#161616".into(), "#8d8d8d".into())
        );
        let selected = TabLook::of(
            TabsVariant::Line,
            TabState {
                selected: true,
                ..Default::default()
            },
        );
        assert_eq!(hex(selected.indicator), "#0f62fe");
        assert_eq!(TabsVariant::Line.height(), 40.);
        assert_eq!(TabsVariant::Contained.height(), 48.);
    }

    #[test]
    fn panel_follows_tab_content_css() {
        crate::theme::tests_set(CarbonTheme::White);
        let line = PanelLook::of(TabsVariant::Line);
        assert_eq!((line.padding, line.background.a), (16., 0.));
        assert_eq!((hex(line.focus), line.focus_width), ("#0f62fe".into(), 2.));
        let contained = PanelLook::of(TabsVariant::Contained);
        assert_eq!(hex(contained.background), "#f4f4f4");
        // An empty panel still shows once any tab has content.
        assert!(!shows_panel(0));
        assert!(shows_panel(1));
        assert_eq!(Tabs::new("t").panel_gap, rem(0.).into());
        assert!(!Tabs::new("t").flush);
        assert!(Tabs::new("t").flush(true).flush);
        assert_eq!(
            Tabs::new("t")
                .panel_gap(crate::tokens::SPACING_06)
                .panel_gap,
            rem(24.).into()
        );
    }

    #[test]
    fn contained_tab_states_follow_bundle_css() {
        crate::theme::tests_set(CarbonTheme::White);
        let rest = TabLook::of(TabsVariant::Contained, TabState::default());
        assert_eq!(hex(rest.background), "#e0e0e0");
        assert_eq!(hex(rest.divider), "#8d8d8d");
        let selected = TabLook::of(
            TabsVariant::Contained,
            TabState {
                selected: true,
                ..Default::default()
            },
        );
        assert_eq!(
            (hex(selected.background), hex(selected.indicator)),
            ("#f4f4f4".into(), "#0f62fe".into())
        );
        let disabled = TabLook::of(
            TabsVariant::Contained,
            TabState {
                disabled: true,
                ..Default::default()
            },
        );
        assert_eq!(
            (hex(disabled.background), hex(disabled.text)),
            ("#c6c6c6".into(), "#8d8d8d".into())
        );
    }
}