Skip to main content

gpui_component/tab/
tab.rs

1use std::{rc::Rc, time::Duration};
2
3use crate::animation::{Lerp, ease_in_out_cubic};
4use crate::{ActiveTheme, Icon, IconName, Selectable, Sizable, Size, StyledExt, h_flex};
5use gpui::ColorExt as _;
6use gpui::prelude::FluentBuilder as _;
7use gpui::{
8    Animation, AnimationExt as _, AnyElement, App, Background, ClickEvent, Edges, ElementId, Hsla,
9    InteractiveElement, IntoElement, ParentElement, Pixels, RenderOnce, SharedString,
10    StatefulInteractiveElement, Styled, Window, div, px, relative,
11};
12
13/// Tab variants.
14#[derive(Debug, Clone, Default, Copy, PartialEq, Eq, Hash)]
15pub enum TabVariant {
16    #[default]
17    Tab,
18    Outline,
19    Pill,
20    Segmented,
21    Underline,
22}
23
24impl TabVariant {
25    fn height(&self, size: Size) -> Pixels {
26        match size {
27            Size::XSmall => match self {
28                TabVariant::Underline => px(26.),
29                _ => px(20.),
30            },
31            Size::Small => match self {
32                TabVariant::Underline => px(30.),
33                _ => px(24.),
34            },
35            Size::Large => match self {
36                TabVariant::Underline => px(44.),
37                _ => px(36.),
38            },
39            _ => match self {
40                TabVariant::Underline => px(36.),
41                _ => px(32.),
42            },
43        }
44    }
45
46    pub(super) fn inner_height(&self, size: Size) -> Pixels {
47        match size {
48            Size::XSmall => match self {
49                TabVariant::Tab | TabVariant::Outline | TabVariant::Pill => px(18.),
50                TabVariant::Segmented => px(16.),
51                TabVariant::Underline => px(20.),
52            },
53            Size::Small => match self {
54                TabVariant::Tab | TabVariant::Outline | TabVariant::Pill => px(22.),
55                TabVariant::Segmented => px(18.),
56                TabVariant::Underline => px(22.),
57            },
58            Size::Large => match self {
59                TabVariant::Tab | TabVariant::Outline | TabVariant::Pill => px(36.),
60                TabVariant::Segmented => px(28.),
61                TabVariant::Underline => px(32.),
62            },
63            _ => match self {
64                TabVariant::Tab => px(30.),
65                TabVariant::Outline | TabVariant::Pill => px(26.),
66                TabVariant::Segmented => px(24.),
67                TabVariant::Underline => px(26.),
68            },
69        }
70    }
71
72    /// Default px(12) to match a dock tab bar's px_3
73    fn inner_paddings(&self, size: Size) -> Edges<Pixels> {
74        let mut padding_x = match size {
75            Size::XSmall => px(8.),
76            Size::Small => px(10.),
77            Size::Large => px(16.),
78            _ => px(12.),
79        };
80
81        if matches!(self, TabVariant::Underline) {
82            padding_x = px(0.);
83        }
84
85        Edges {
86            left: padding_x,
87            right: padding_x,
88            ..Default::default()
89        }
90    }
91
92    fn inner_margins(&self, size: Size) -> Edges<Pixels> {
93        match size {
94            Size::XSmall => match self {
95                TabVariant::Underline => Edges {
96                    top: px(1.),
97                    bottom: px(2.),
98                    ..Default::default()
99                },
100                _ => Edges::all(px(0.)),
101            },
102            Size::Small => match self {
103                TabVariant::Underline => Edges {
104                    top: px(2.),
105                    bottom: px(3.),
106                    ..Default::default()
107                },
108                _ => Edges::all(px(0.)),
109            },
110            Size::Large => match self {
111                TabVariant::Underline => Edges {
112                    top: px(5.),
113                    bottom: px(6.),
114                    ..Default::default()
115                },
116                _ => Edges::all(px(0.)),
117            },
118            _ => match self {
119                TabVariant::Underline => Edges {
120                    top: px(3.),
121                    bottom: px(4.),
122                    ..Default::default()
123                },
124                _ => Edges::all(px(0.)),
125            },
126        }
127    }
128
129    fn normal(&self, cx: &App) -> TabStyle {
130        match self {
131            TabVariant::Tab => TabStyle {
132                fg: cx.theme().tab_foreground,
133                bg: cx.theme().transparent.into(),
134                borders: Edges {
135                    left: px(1.),
136                    right: px(1.),
137                    ..Default::default()
138                },
139                border_color: cx.theme().transparent,
140                ..Default::default()
141            },
142            TabVariant::Outline => TabStyle {
143                fg: cx.theme().tab_foreground,
144                bg: cx.theme().transparent.into(),
145                borders: Edges::all(px(1.)),
146                border_color: cx.theme().border,
147                ..Default::default()
148            },
149            TabVariant::Pill => TabStyle {
150                fg: cx.theme().foreground,
151                bg: cx.theme().transparent.into(),
152                ..Default::default()
153            },
154            TabVariant::Segmented => TabStyle {
155                fg: cx.theme().tab_foreground,
156                bg: cx.theme().transparent.into(),
157                ..Default::default()
158            },
159            TabVariant::Underline => TabStyle {
160                fg: cx.theme().tab_foreground,
161                bg: cx.theme().transparent.into(),
162                inner_bg: cx.theme().transparent.into(),
163                borders: Edges {
164                    bottom: px(2.),
165                    ..Default::default()
166                },
167                border_color: cx.theme().transparent,
168                ..Default::default()
169            },
170        }
171    }
172
173    fn hovered(&self, selected: bool, cx: &App) -> TabStyle {
174        match self {
175            TabVariant::Tab => TabStyle {
176                fg: cx.theme().tab_active_foreground,
177                bg: cx.theme().transparent.into(),
178                borders: Edges {
179                    left: px(1.),
180                    right: px(1.),
181                    ..Default::default()
182                },
183                border_color: cx.theme().transparent,
184                ..Default::default()
185            },
186            TabVariant::Outline => TabStyle {
187                fg: cx.theme().secondary_foreground,
188                bg: cx.theme().tokens.secondary_hover.into(),
189                borders: Edges::all(px(1.)),
190                border_color: cx.theme().border,
191                ..Default::default()
192            },
193            TabVariant::Pill => TabStyle {
194                fg: cx.theme().secondary_foreground,
195                bg: cx.theme().tokens.secondary.into(),
196                ..Default::default()
197            },
198            TabVariant::Segmented => TabStyle {
199                fg: cx.theme().tab_active_foreground,
200                bg: cx.theme().transparent.into(),
201                inner_bg: if selected {
202                    cx.theme().tokens.background.into()
203                } else {
204                    cx.theme().transparent.into()
205                },
206                ..Default::default()
207            },
208            TabVariant::Underline => TabStyle {
209                fg: cx.theme().tab_active_foreground,
210                bg: cx.theme().transparent.into(),
211                inner_bg: cx.theme().transparent.into(),
212                borders: Edges {
213                    bottom: px(2.),
214                    ..Default::default()
215                },
216                border_color: cx.theme().transparent,
217                ..Default::default()
218            },
219        }
220    }
221
222    fn selected(&self, cx: &App) -> TabStyle {
223        match self {
224            TabVariant::Tab => TabStyle {
225                fg: cx.theme().tab_active_foreground,
226                bg: cx.theme().tokens.tab_active.into(),
227                borders: Edges {
228                    left: px(1.),
229                    right: px(1.),
230                    ..Default::default()
231                },
232                border_color: cx.theme().border,
233                ..Default::default()
234            },
235            TabVariant::Outline => TabStyle {
236                fg: cx.theme().primary,
237                bg: cx.theme().transparent.into(),
238                borders: Edges::all(px(1.)),
239                border_color: cx.theme().primary,
240                ..Default::default()
241            },
242            TabVariant::Pill => TabStyle {
243                fg: cx.theme().primary_foreground,
244                bg: cx.theme().tokens.primary.into(),
245                ..Default::default()
246            },
247            TabVariant::Segmented => TabStyle {
248                fg: cx.theme().tab_active_foreground,
249                bg: cx.theme().transparent.into(),
250                inner_bg: cx.theme().tokens.background.into(),
251                shadow: true,
252                ..Default::default()
253            },
254            TabVariant::Underline => TabStyle {
255                fg: cx.theme().tab_active_foreground,
256                bg: cx.theme().transparent.into(),
257                borders: Edges {
258                    bottom: px(2.),
259                    ..Default::default()
260                },
261                border_color: cx.theme().primary,
262                ..Default::default()
263            },
264        }
265    }
266
267    fn disabled(&self, selected: bool, cx: &App) -> TabStyle {
268        match self {
269            TabVariant::Tab => TabStyle {
270                fg: cx.theme().muted_foreground,
271                bg: cx.theme().transparent.into(),
272                border_color: if selected {
273                    cx.theme().border
274                } else {
275                    cx.theme().transparent
276                },
277                borders: Edges {
278                    left: px(1.),
279                    right: px(1.),
280                    ..Default::default()
281                },
282                ..Default::default()
283            },
284            TabVariant::Outline => TabStyle {
285                fg: cx.theme().muted_foreground,
286                bg: cx.theme().transparent.into(),
287                borders: Edges::all(px(1.)),
288                border_color: if selected {
289                    cx.theme().primary
290                } else {
291                    cx.theme().border
292                },
293                ..Default::default()
294            },
295            TabVariant::Pill => TabStyle {
296                fg: if selected {
297                    cx.theme().primary_foreground.opacity(0.5)
298                } else {
299                    cx.theme().muted_foreground
300                },
301                bg: if selected {
302                    cx.theme().primary.opacity(0.5).into()
303                } else {
304                    cx.theme().transparent.into()
305                },
306                ..Default::default()
307            },
308            TabVariant::Segmented => TabStyle {
309                fg: cx.theme().muted_foreground,
310                bg: cx.theme().tokens.tab_bar.into(),
311                inner_bg: if selected {
312                    cx.theme().tokens.background.into()
313                } else {
314                    cx.theme().transparent.into()
315                },
316                ..Default::default()
317            },
318            TabVariant::Underline => TabStyle {
319                fg: cx.theme().muted_foreground,
320                bg: cx.theme().transparent.into(),
321                border_color: if selected {
322                    cx.theme().border
323                } else {
324                    cx.theme().transparent
325                },
326                borders: Edges {
327                    bottom: px(2.),
328                    ..Default::default()
329                },
330                ..Default::default()
331            },
332        }
333    }
334
335    pub(super) fn tab_bar_radius(&self, size: Size, cx: &App) -> Pixels {
336        if *self != TabVariant::Segmented {
337            return px(0.);
338        }
339
340        match size {
341            Size::XSmall | Size::Small => cx.theme().radius,
342            Size::Large => cx.theme().radius_lg,
343            _ => cx.theme().radius_lg,
344        }
345    }
346
347    fn radius(&self, size: Size, cx: &App) -> Pixels {
348        match self {
349            TabVariant::Outline | TabVariant::Pill => cx.theme().radius_full(),
350            TabVariant::Segmented => match size {
351                Size::XSmall | Size::Small => cx.theme().radius,
352                Size::Large => cx.theme().radius_lg,
353                _ => cx.theme().radius_lg,
354            },
355            _ => px(0.),
356        }
357    }
358
359    pub(super) fn inner_radius(&self, size: Size, cx: &App) -> Pixels {
360        match self {
361            // The inset the active pill sits at, taken off the bar's own radius
362            // so the two curves stay concentric. Floored at zero: a square bar
363            // has nothing to inset from.
364            TabVariant::Segmented => match size {
365                Size::Large => (self.tab_bar_radius(size, cx) - px(3.)).max(px(0.)),
366                _ => (self.tab_bar_radius(size, cx) - px(2.)).max(px(0.)),
367            },
368            _ => px(0.),
369        }
370    }
371}
372
373#[allow(dead_code)]
374struct TabStyle {
375    borders: Edges<Pixels>,
376    border_color: Hsla,
377    bg: Background,
378    fg: Hsla,
379    shadow: bool,
380    inner_bg: Background,
381}
382
383impl Default for TabStyle {
384    fn default() -> Self {
385        TabStyle {
386            borders: Edges::all(px(0.)),
387            border_color: gpui::transparent_white(),
388            bg: gpui::transparent_white().into(),
389            fg: gpui::transparent_white(),
390            shadow: false,
391            inner_bg: gpui::transparent_white().into(),
392        }
393    }
394}
395
396/// A Tab element for the [`super::TabBar`].
397#[derive(IntoElement)]
398pub struct Tab {
399    ix: usize,
400    base: gpui_base::Tab,
401    pub(super) label: Option<SharedString>,
402    aria_label: Option<SharedString>,
403    pub(super) icon: Option<Icon>,
404    prefix: Option<AnyElement>,
405    pub(super) tab_bar_prefix: Option<bool>,
406    suffix: Option<AnyElement>,
407    children: Vec<AnyElement>,
408    variant: TabVariant,
409    size: Size,
410    pub(super) disabled: bool,
411    pub(super) selected: bool,
412    pub(super) indicator_active: bool,
413    pub(super) indicator_ready: bool,
414    /// Animation epoch of the [`super::TabBar`] indicator; increments on every
415    /// tab switch. Used to key the selected tab's text color fade so it
416    /// restarts in sync with the indicator slide.
417    pub(super) indicator_epoch: u64,
418    pub(super) max_width: Option<Pixels>,
419    on_click: Option<Rc<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>>,
420}
421
422impl From<&'static str> for Tab {
423    fn from(label: &'static str) -> Self {
424        Self::new().label(label)
425    }
426}
427
428impl From<String> for Tab {
429    fn from(label: String) -> Self {
430        Self::new().label(label)
431    }
432}
433
434impl From<SharedString> for Tab {
435    fn from(label: SharedString) -> Self {
436        Self::new().label(label)
437    }
438}
439
440impl From<Icon> for Tab {
441    fn from(icon: Icon) -> Self {
442        Self::default().icon(icon)
443    }
444}
445
446impl From<IconName> for Tab {
447    fn from(icon_name: IconName) -> Self {
448        Self::default().icon(Icon::new(icon_name))
449    }
450}
451
452impl Default for Tab {
453    fn default() -> Self {
454        Self {
455            ix: 0,
456            base: gpui_base::Tab::new(0usize),
457            label: None,
458            aria_label: None,
459            icon: None,
460            tab_bar_prefix: None,
461            children: Vec::new(),
462            disabled: false,
463            selected: false,
464            indicator_active: false,
465            indicator_ready: true,
466            indicator_epoch: 0,
467            prefix: None,
468            suffix: None,
469            variant: TabVariant::default(),
470            size: Size::default(),
471            max_width: None,
472            on_click: None,
473        }
474    }
475}
476
477impl Tab {
478    /// Create a new tab with a label.
479    pub fn new() -> Self {
480        Self::default()
481    }
482
483    /// Set label for the tab.
484    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
485        self.label = Some(label.into());
486        self
487    }
488
489    /// Set the accessible label for the tab.
490    pub fn aria_label(mut self, label: impl Into<SharedString>) -> Self {
491        self.aria_label = Some(label.into());
492        self
493    }
494
495    fn a11y_label(&self) -> Option<SharedString> {
496        self.aria_label.clone().or_else(|| self.label.clone())
497    }
498
499    /// Set icon for the tab.
500    pub fn icon(mut self, icon: impl Into<Icon>) -> Self {
501        self.icon = Some(icon.into());
502        self
503    }
504
505    /// Set Tab Variant.
506    pub fn with_variant(mut self, variant: TabVariant) -> Self {
507        self.variant = variant;
508        self
509    }
510
511    /// Use Pill variant.
512    pub fn pill(mut self) -> Self {
513        self.variant = TabVariant::Pill;
514        self
515    }
516
517    /// Use outline variant.
518    pub fn outline(mut self) -> Self {
519        self.variant = TabVariant::Outline;
520        self
521    }
522
523    /// Use Segmented variant.
524    pub fn segmented(mut self) -> Self {
525        self.variant = TabVariant::Segmented;
526        self
527    }
528
529    /// Use Underline variant.
530    pub fn underline(mut self) -> Self {
531        self.variant = TabVariant::Underline;
532        self
533    }
534
535    /// Set the left side of the tab
536    pub fn prefix(mut self, prefix: impl IntoElement) -> Self {
537        self.prefix = Some(prefix.into_any_element());
538        self
539    }
540
541    /// Set the right side of the tab
542    pub fn suffix(mut self, suffix: impl IntoElement) -> Self {
543        self.suffix = Some(suffix.into_any_element());
544        self
545    }
546
547    /// Set disabled state to the tab, default false.
548    pub fn disabled(mut self, disabled: bool) -> Self {
549        self.disabled = disabled;
550        self
551    }
552
553    /// Set the click handler for the tab.
554    pub fn on_click(
555        mut self,
556        on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
557    ) -> Self {
558        self.on_click = Some(Rc::new(on_click));
559        self
560    }
561
562    /// Set index to the tab.
563    pub(crate) fn ix(mut self, ix: usize) -> Self {
564        self.ix = ix;
565        self.base = self.base.id(ix);
566        self
567    }
568
569    /// Set if the tab bar has a prefix.
570    pub(crate) fn tab_bar_prefix(mut self, tab_bar_prefix: bool) -> Self {
571        self.tab_bar_prefix = Some(tab_bar_prefix);
572        self
573    }
574
575    /// Set the maximum width of the tab, see [`super::TabBar::max_width`].
576    pub(super) fn max_width(mut self, max_width: Option<Pixels>) -> Self {
577        self.max_width = max_width;
578        self
579    }
580}
581
582impl ParentElement for Tab {
583    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
584        self.children.extend(elements);
585    }
586}
587
588impl Selectable for Tab {
589    fn selected(mut self, selected: bool) -> Self {
590        self.selected = selected;
591        self
592    }
593
594    fn is_selected(&self) -> bool {
595        self.selected
596    }
597}
598
599impl InteractiveElement for Tab {
600    fn interactivity(&mut self) -> &mut gpui::Interactivity {
601        self.base.interactivity()
602    }
603}
604
605impl StatefulInteractiveElement for Tab {}
606
607impl Styled for Tab {
608    fn style(&mut self) -> &mut gpui::StyleRefinement {
609        self.base.style()
610    }
611}
612
613impl Sizable for Tab {
614    fn with_size(mut self, size: impl Into<Size>) -> Self {
615        self.size = size.into();
616        self
617    }
618}
619
620impl RenderOnce for Tab {
621    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
622        let mut normal_style = self.variant.normal(cx);
623        let mut selected_style = self.variant.selected(cx);
624        let mut disabled_style = self.variant.disabled(self.selected, cx);
625        let mut hover_style = self.variant.hovered(self.selected, cx);
626        if self.disabled {
627            hover_style = self.variant.disabled(self.selected, cx);
628        }
629        let tab_bar_prefix = self.tab_bar_prefix.unwrap_or_default();
630        if !tab_bar_prefix {
631            if self.ix == 0 && self.variant == TabVariant::Tab {
632                normal_style.borders.left = px(0.);
633                selected_style.borders.left = px(0.);
634                disabled_style.borders.left = px(0.);
635                hover_style.borders.left = px(0.);
636            }
637        }
638        let tab_style = if self.disabled {
639            &disabled_style
640        } else if self.selected {
641            &selected_style
642        } else {
643            &normal_style
644        };
645        let radius = self.variant.radius(self.size, cx);
646        let inner_radius = self.variant.inner_radius(self.size, cx);
647        let inner_paddings = self.variant.inner_paddings(self.size);
648        let inner_margins = self.variant.inner_margins(self.size);
649        let inner_height = self.variant.inner_height(self.size);
650        let height = self.variant.height(self.size);
651        let aria_label = self.a11y_label();
652
653        let segmented_indicator_active =
654            self.variant == TabVariant::Segmented && self.indicator_active;
655        let has_inline_inner_bg =
656            self.selected && segmented_indicator_active && !self.indicator_ready;
657        let inline_inner_bg = tab_style.inner_bg;
658        let (inner_bg, hover_inner_bg) = if segmented_indicator_active && self.indicator_ready {
659            (cx.theme().transparent.into(), cx.theme().transparent.into())
660        } else if has_inline_inner_bg {
661            (inline_inner_bg, inline_inner_bg)
662        } else {
663            (tab_style.inner_bg, hover_style.inner_bg)
664        };
665        let inner_shadow = tab_style.shadow && !segmented_indicator_active;
666
667        // When a sliding indicator is active and ready, it alone represents the
668        // selected state. Suppress the selected tab's own active background/border
669        // so the two don't overlap during the switch animation (Segmented already
670        // does this for its `inner_bg` above). Skip disabled tabs so a
671        // disabled-selected tab keeps its dimmed styling instead of the
672        // full-strength indicator color.
673        let suppress_active_visual =
674            self.selected && !self.disabled && self.indicator_active && self.indicator_ready;
675        // Pill paints its active state via the outer `bg`.
676        let selected_outer_bg = if suppress_active_visual && self.variant == TabVariant::Pill {
677            cx.theme().transparent.into()
678        } else {
679            selected_style.bg
680        };
681        // Underline paints its active state via the bottom `border_color`.
682        let selected_outer_border_color =
683            if suppress_active_visual && self.variant == TabVariant::Underline {
684                cx.theme().transparent
685            } else {
686                selected_style.border_color
687            };
688
689        // For Pill, the newly selected tab's text color (`primary_foreground`)
690        // would otherwise snap to white instantly while the indicator is still
691        // sliding into place. Fade it from the normal color in sync with the
692        // indicator slide (keyed on the indicator epoch so it restarts on each
693        // switch). `epoch == 0` is the initial layout (no slide), so we skip it.
694        let animate_fg = self.selected
695            && !self.disabled
696            && self.variant == TabVariant::Pill
697            && self.indicator_active
698            && self.indicator_ready
699            && self.indicator_epoch > 0;
700        let fg_from = self.variant.normal(cx).fg;
701        let fg_to = tab_style.fg;
702        // Icon-only tabs are fixed-size and exempt from `max_width`.
703        let max_width = self.max_width.filter(|_| self.icon.is_none());
704
705        let inner_content = h_flex()
706            .flex_1()
707            .h(inner_height)
708            .line_height(relative(1.))
709            .whitespace_nowrap()
710            .items_center()
711            .justify_center()
712            .overflow_hidden()
713            .margins(inner_margins)
714            // Normally the label decides the tab width, so it never shrinks. With
715            // `max_width` it is the one part that gives way.
716            .map(|this| match max_width {
717                Some(_) => this.flex_auto(),
718                None => this.flex_shrink_0(),
719            })
720            .map(|this| match self.icon {
721                Some(icon) => this
722                    .w(inner_height * 1.25)
723                    .child(icon.map(|this| match self.size {
724                        Size::XSmall => this.size_2p5(),
725                        Size::Small => this.size_3p5(),
726                        Size::Large => this.size_4(),
727                        _ => this.size_4(),
728                    })),
729                None => this
730                    .paddings(inner_paddings)
731                    .map(|this| match (self.label, max_width) {
732                        // Text always takes its natural width, so it needs a box
733                        // that is allowed to shrink to ellipsize inside of.
734                        (Some(label), Some(_)) => this.child(div().truncate().child(label)),
735                        (Some(label), None) => this.child(label),
736                        (None, _) => this,
737                    })
738                    .children(self.children),
739            })
740            .bg(inner_bg)
741            .rounded(inner_radius)
742            .when(inner_shadow, |this| this.shadow_xs())
743            .hover(|this| this.bg(hover_inner_bg).rounded(inner_radius));
744
745        let inner_element = if animate_fg {
746            inner_content
747                .with_animation(
748                    ElementId::NamedInteger("tab-fg".into(), self.indicator_epoch),
749                    Animation::new(Duration::from_millis(200)).with_easing(ease_in_out_cubic),
750                    move |this, delta| this.text_color(Lerp::lerp(&fg_from, &fg_to, delta)),
751                )
752                .into_any_element()
753        } else {
754            inner_content.into_any_element()
755        };
756
757        self.base
758            .id(self.ix)
759            .selected(self.selected)
760            .disabled(self.disabled)
761            .when_some(aria_label, |this, label| this.accessibility_label(label))
762            .styles(|styles| {
763                styles
764                    .selected(|style| {
765                        style
766                            .text_color(selected_style.fg)
767                            .bg(selected_outer_bg)
768                            .border_l(selected_style.borders.left)
769                            .border_r(selected_style.borders.right)
770                            .border_t(selected_style.borders.top)
771                            .border_b(selected_style.borders.bottom)
772                            .border_color(selected_outer_border_color)
773                    })
774                    .disabled(|style| {
775                        style
776                            .text_color(disabled_style.fg)
777                            .bg(disabled_style.bg)
778                            .border_l(disabled_style.borders.left)
779                            .border_r(disabled_style.borders.right)
780                            .border_t(disabled_style.borders.top)
781                            .border_b(disabled_style.borders.bottom)
782                            .border_color(disabled_style.border_color)
783                    })
784            })
785            .relative()
786            .flex()
787            // Wrapping would move the overflow onto a clipped second line instead
788            // of letting the label shrink, so a capped tab lays out on one line.
789            .map(|this| match max_width {
790                Some(max_width) => this.flex_nowrap().max_w(max_width),
791                None => this.flex_wrap(),
792            })
793            .gap_1()
794            .items_center()
795            .flex_shrink_0()
796            .h(height)
797            .overflow_hidden()
798            .map(|this| match self.size {
799                Size::XSmall => this.text_xs(),
800                Size::Large => this.text_base(),
801                _ => this.text_sm(),
802            })
803            .rounded(radius)
804            .when(!self.selected && !self.disabled, |this| {
805                this.text_color(normal_style.fg)
806                    .bg(normal_style.bg)
807                    .border_l(normal_style.borders.left)
808                    .border_r(normal_style.borders.right)
809                    .border_t(normal_style.borders.top)
810                    .border_b(normal_style.borders.bottom)
811                    .border_color(normal_style.border_color)
812            })
813            .hover(|this| {
814                // Always register the hover style: GPUI only refreshes the cached
815                // hover state while one is present. If the selected tab skipped it,
816                // the stale state would keep hover colors after unselecting.
817                if self.selected || self.disabled {
818                    return this;
819                }
820                this.text_color(hover_style.fg)
821                    .bg(hover_style.bg)
822                    .border_l(hover_style.borders.left)
823                    .border_r(hover_style.borders.right)
824                    .border_t(hover_style.borders.top)
825                    .border_b(hover_style.borders.bottom)
826                    .border_color(hover_style.border_color)
827                    .rounded(radius)
828            })
829            .when(has_inline_inner_bg, |this| {
830                this.child(
831                    div()
832                        .absolute()
833                        .left_0()
834                        .right_0()
835                        .top_0()
836                        .bottom_0()
837                        .flex()
838                        .items_center()
839                        .child(
840                            div()
841                                .w_full()
842                                .h(inner_height)
843                                .bg(inline_inner_bg)
844                                .rounded(inner_radius)
845                                .when(tab_style.shadow, |this| this.shadow_sm()),
846                        ),
847                )
848            })
849            // Under `max_width` the label is the only part that gives way, so
850            // hold the prefix and suffix (e.g. a close button) at their full size.
851            .when_some(self.prefix, |this, prefix| {
852                this.child(
853                    div()
854                        .when_some(max_width, |this, _| this.flex_shrink_0())
855                        .child(prefix),
856                )
857            })
858            .child(inner_element)
859            .when_some(self.suffix, |this, suffix| {
860                this.child(
861                    div()
862                        .when_some(max_width, |this, _| this.flex_shrink_0())
863                        .child(suffix),
864                )
865            })
866            .when_some(self.on_click.clone(), |this, on_click| {
867                this.on_click(move |event, window, cx| on_click(event, window, cx))
868            })
869    }
870}
871
872#[cfg(test)]
873mod tests {
874    use super::*;
875    use crate::tab::TabBar;
876    use gpui::{Context, Render, TestAppContext, VisualTestContext};
877
878    const VARIANTS: [TabVariant; 5] = [
879        TabVariant::Tab,
880        TabVariant::Outline,
881        TabVariant::Pill,
882        TabVariant::Segmented,
883        TabVariant::Underline,
884    ];
885
886    const LONG_LABEL: &str = "Account Settings & Preferences";
887
888    /// One [`TabBar`], optionally capped, holding the tab `build` returns.
889    struct TabBarTest {
890        variant: TabVariant,
891        max_width: Option<Pixels>,
892        build: fn(Tab) -> Tab,
893    }
894
895    impl Render for TabBarTest {
896        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
897            TabBar::new("tabs")
898                .with_variant(self.variant)
899                .selected_index(0)
900                .when_some(self.max_width, |this, width| this.max_width(width))
901                .child((self.build)(
902                    Tab::new().debug_selector(|| "tab".to_string()),
903                ))
904        }
905    }
906
907    fn show(
908        cx: &mut TestAppContext,
909        variant: TabVariant,
910        max_width: Option<Pixels>,
911        build: fn(Tab) -> Tab,
912    ) -> &mut VisualTestContext {
913        cx.update(crate::init);
914        let (_, cx) = cx.add_window_view(|_, _| TabBarTest {
915            variant,
916            max_width,
917            build,
918        });
919        cx.run_until_parked();
920        cx
921    }
922
923    /// Outer width of a labelled tab in every variant, capped or not.
924    fn variant_widths(
925        cx: &mut TestAppContext,
926        build: fn(Tab) -> Tab,
927        max_width: Option<Pixels>,
928    ) -> Vec<Pixels> {
929        VARIANTS
930            .into_iter()
931            .map(|variant| {
932                show(cx, variant, max_width, build)
933                    .debug_bounds("tab")
934                    .expect("tab not rendered")
935                    .size
936                    .width
937            })
938            .collect()
939    }
940
941    #[gpui::test]
942    fn a11y_label_defaults_to_visible_label(_cx: &mut TestAppContext) {
943        let tab = Tab::new().label("Account");
944
945        assert_eq!(tab.a11y_label(), Some("Account".into()));
946    }
947
948    #[gpui::test]
949    fn explicit_a11y_label_overrides_visible_label(_cx: &mut TestAppContext) {
950        let tab = Tab::new().label("Acct").aria_label("Account settings");
951
952        assert_eq!(tab.a11y_label(), Some("Account settings".into()));
953    }
954
955    #[gpui::test]
956    fn max_width_leaves_short_tabs_untouched(cx: &mut TestAppContext) {
957        // The box the cap wraps the label in must not report a different
958        // intrinsic width than the bare label it replaces.
959        let build: fn(Tab) -> Tab = |tab| tab.label("Go");
960
961        let uncapped = variant_widths(cx, build, None);
962        let capped = variant_widths(cx, build, Some(px(200.)));
963
964        assert_eq!(uncapped, capped, "a tab under the cap must not be resized");
965    }
966
967    #[gpui::test]
968    fn max_width_caps_long_tabs(cx: &mut TestAppContext) {
969        let build: fn(Tab) -> Tab = |tab| tab.label(LONG_LABEL);
970
971        let uncapped = variant_widths(cx, build, None);
972        let capped = variant_widths(cx, build, Some(px(120.)));
973
974        for (variant, (uncapped, capped)) in
975            VARIANTS.into_iter().zip(uncapped.into_iter().zip(capped))
976        {
977            assert!(
978                uncapped > px(120.),
979                "{variant:?} is not long enough to exercise the cap ({uncapped:?})"
980            );
981            assert!(
982                capped <= px(120.),
983                "{variant:?} width {capped:?} exceeds max_width"
984            );
985        }
986    }
987
988    #[gpui::test]
989    fn max_width_keeps_prefix_and_suffix_intact(cx: &mut TestAppContext) {
990        let cx = show(cx, TabVariant::Segmented, Some(px(140.)), |tab| {
991            tab.prefix(Icon::new(IconName::BookOpen))
992                .label(LONG_LABEL)
993                .suffix(div().size(px(16.)).debug_selector(|| "suffix".to_string()))
994        });
995
996        let tab = cx.debug_bounds("tab").expect("tab not rendered");
997        let suffix = cx.debug_bounds("suffix").expect("suffix not rendered");
998
999        assert!(tab.size.width <= px(140.));
1000        assert_eq!(
1001            suffix.size.width,
1002            px(16.),
1003            "the label should absorb the truncation, not the suffix"
1004        );
1005        assert!(
1006            suffix.right() <= tab.right(),
1007            "suffix must stay within the tab"
1008        );
1009        // A wrapping tab pushes the suffix onto a second line, which the fixed
1010        // tab height then clips: it keeps its size and stays inside the tab,
1011        // but lands back at the left edge instead of after the label.
1012        assert!(
1013            suffix.left() > tab.center().x,
1014            "suffix must follow the label, not wrap below it"
1015        );
1016    }
1017
1018    /// Icon-only tabs are sized to a square by construction, so the cap has to
1019    /// leave them alone however narrow it is.
1020    #[gpui::test]
1021    fn max_width_exempts_icon_only_tabs(cx: &mut TestAppContext) {
1022        let build: fn(Tab) -> Tab = |tab| tab.icon(Icon::new(IconName::BookOpen));
1023        let width = |cx: &mut TestAppContext, max_width| {
1024            show(cx, TabVariant::Tab, max_width, build)
1025                .debug_bounds("tab")
1026                .expect("tab not rendered")
1027                .size
1028                .width
1029        };
1030
1031        let uncapped = width(cx, None);
1032        assert!(
1033            uncapped > px(16.),
1034            "the cap has to be narrower than the icon tab to be meaningful"
1035        );
1036        assert_eq!(
1037            width(cx, Some(px(16.))),
1038            uncapped,
1039            "an icon-only tab must ignore max_width"
1040        );
1041    }
1042}