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::prelude::FluentBuilder as _;
6use gpui::{
7    Animation, AnimationExt as _, AnyElement, App, Background, ClickEvent, Edges, ElementId,
8    FillOptions, Hsla, InteractiveElement, IntoElement, ParentElement, PathBuilder, PathStyle,
9    Pixels, Point, RenderOnce, SharedString, StatefulInteractiveElement, Styled, Window, canvas,
10    div, point, px, relative,
11};
12use gpui_base::LogicalStyledExt as _;
13
14/// Room between two [`TabVariant::Folder`] tabs, holding their separator.
15pub(super) const FOLDER_TAB_GAP: Pixels = px(4.);
16
17/// Geometry of [`TabVariant::Folder`].
18#[derive(Clone, Copy)]
19pub(super) struct FolderTabMetrics {
20    /// Bar space above the tabs. The content sits this much above the tab's
21    /// center so that it centers on the whole bar.
22    pub(super) top_padding: Pixels,
23    /// Radius of the top corners and of the curves joining the selected tab
24    /// to the content below.
25    pub(super) radius: Pixels,
26    pub(super) padding_x: Pixels,
27    pub(super) separator_height: Pixels,
28}
29
30impl FolderTabMetrics {
31    pub(super) fn new(size: Size, cx: &App) -> Self {
32        let (top_padding, padding_x, separator_height, radius) = match size {
33            Size::XSmall => (px(2.), px(8.), px(12.), cx.theme().radius),
34            Size::Small => (px(4.), px(8.), px(12.), cx.theme().radius),
35            Size::Large => (px(8.), px(16.), px(16.), cx.theme().radius_lg),
36            _ => (px(4.), px(12.), px(16.), cx.theme().radius_lg),
37        };
38        Self {
39            top_padding,
40            // Past a third of the height a curve reaches under its neighbor's
41            // hover fill.
42            radius: radius.min(TabVariant::Folder.height(size) / 3.),
43            padding_x,
44            separator_height,
45        }
46    }
47}
48
49/// Tab variants.
50#[derive(Debug, Clone, Default, Copy, PartialEq, Eq, Hash)]
51pub enum TabVariant {
52    #[default]
53    Tab,
54    Outline,
55    Pill,
56    Segmented,
57    Underline,
58    /// Tabs shaped like a folder's index tabs, as in a web browser: the
59    /// selected tab rises from the bar with rounded top corners and curves out
60    /// into the content below it.
61    Folder,
62}
63
64impl TabVariant {
65    fn height(&self, size: Size) -> Pixels {
66        match size {
67            Size::XSmall => match self {
68                TabVariant::Underline => px(26.),
69                _ => px(20.),
70            },
71            Size::Small => match self {
72                TabVariant::Underline => px(30.),
73                _ => px(24.),
74            },
75            Size::Large => match self {
76                TabVariant::Underline => px(44.),
77                _ => px(36.),
78            },
79            _ => match self {
80                TabVariant::Underline => px(36.),
81                _ => px(32.),
82            },
83        }
84    }
85
86    pub(super) fn inner_height(&self, size: Size) -> Pixels {
87        match size {
88            Size::XSmall => match self {
89                TabVariant::Tab | TabVariant::Outline | TabVariant::Pill => px(18.),
90                TabVariant::Segmented | TabVariant::Folder => px(16.),
91                TabVariant::Underline => px(20.),
92            },
93            Size::Small => match self {
94                TabVariant::Tab | TabVariant::Outline | TabVariant::Pill => px(22.),
95                TabVariant::Segmented | TabVariant::Folder => px(18.),
96                TabVariant::Underline => px(22.),
97            },
98            Size::Large => match self {
99                TabVariant::Tab | TabVariant::Outline | TabVariant::Pill => px(36.),
100                TabVariant::Segmented | TabVariant::Folder => px(28.),
101                TabVariant::Underline => px(32.),
102            },
103            _ => match self {
104                TabVariant::Tab => px(30.),
105                TabVariant::Outline | TabVariant::Pill => px(26.),
106                TabVariant::Segmented | TabVariant::Folder => px(24.),
107                TabVariant::Underline => px(26.),
108            },
109        }
110    }
111
112    /// Default px(12) to match a dock tab bar's px_3
113    fn inner_paddings(&self, size: Size) -> Edges<Pixels> {
114        let mut padding_x = match size {
115            Size::XSmall => px(8.),
116            Size::Small => px(10.),
117            Size::Large => px(16.),
118            _ => px(12.),
119        };
120
121        // A folder tab pads its content itself, see `FolderTabMetrics`.
122        if matches!(self, TabVariant::Underline | TabVariant::Folder) {
123            padding_x = px(0.);
124        }
125
126        Edges {
127            left: padding_x,
128            right: padding_x,
129            ..Default::default()
130        }
131    }
132
133    fn inner_margins(&self, size: Size) -> Edges<Pixels> {
134        match size {
135            Size::XSmall => match self {
136                TabVariant::Underline => Edges {
137                    top: px(1.),
138                    bottom: px(2.),
139                    ..Default::default()
140                },
141                _ => Edges::all(px(0.)),
142            },
143            Size::Small => match self {
144                TabVariant::Underline => Edges {
145                    top: px(2.),
146                    bottom: px(3.),
147                    ..Default::default()
148                },
149                _ => Edges::all(px(0.)),
150            },
151            Size::Large => match self {
152                TabVariant::Underline => Edges {
153                    top: px(5.),
154                    bottom: px(6.),
155                    ..Default::default()
156                },
157                _ => Edges::all(px(0.)),
158            },
159            _ => match self {
160                TabVariant::Underline => Edges {
161                    top: px(3.),
162                    bottom: px(4.),
163                    ..Default::default()
164                },
165                _ => Edges::all(px(0.)),
166            },
167        }
168    }
169
170    fn normal(&self, cx: &App) -> TabStyle {
171        match self {
172            TabVariant::Tab => TabStyle {
173                fg: cx.theme().tab_foreground,
174                bg: cx.theme().transparent.into(),
175                borders: Edges {
176                    left: px(1.),
177                    right: px(1.),
178                    ..Default::default()
179                },
180                border_color: cx.theme().transparent,
181                ..Default::default()
182            },
183            TabVariant::Outline => TabStyle {
184                fg: cx.theme().tab_foreground,
185                bg: cx.theme().transparent.into(),
186                borders: Edges::all(px(1.)),
187                border_color: cx.theme().border,
188                ..Default::default()
189            },
190            TabVariant::Pill => TabStyle {
191                fg: cx.theme().foreground,
192                bg: cx.theme().transparent.into(),
193                ..Default::default()
194            },
195            TabVariant::Segmented => TabStyle {
196                fg: cx.theme().tab_foreground,
197                bg: cx.theme().transparent.into(),
198                ..Default::default()
199            },
200            TabVariant::Underline => TabStyle {
201                fg: cx.theme().tab_foreground,
202                bg: cx.theme().transparent.into(),
203                inner_bg: cx.theme().transparent.into(),
204                borders: Edges {
205                    bottom: px(2.),
206                    ..Default::default()
207                },
208                border_color: cx.theme().transparent,
209                ..Default::default()
210            },
211            TabVariant::Folder => TabStyle {
212                fg: cx.theme().tab_foreground,
213                bg: cx.theme().transparent.into(),
214                ..Default::default()
215            },
216        }
217    }
218
219    fn hovered(&self, selected: bool, cx: &App) -> TabStyle {
220        match self {
221            TabVariant::Tab => TabStyle {
222                fg: cx.theme().tab_active_foreground,
223                bg: cx.theme().transparent.into(),
224                borders: Edges {
225                    left: px(1.),
226                    right: px(1.),
227                    ..Default::default()
228                },
229                border_color: cx.theme().transparent,
230                ..Default::default()
231            },
232            TabVariant::Outline => TabStyle {
233                fg: cx.theme().secondary_foreground,
234                bg: cx.theme().tokens.secondary_hover.into(),
235                borders: Edges::all(px(1.)),
236                border_color: cx.theme().border,
237                ..Default::default()
238            },
239            TabVariant::Pill => TabStyle {
240                fg: cx.theme().secondary_foreground,
241                bg: cx.theme().tokens.secondary.into(),
242                ..Default::default()
243            },
244            TabVariant::Segmented => TabStyle {
245                fg: cx.theme().tab_active_foreground,
246                bg: cx.theme().transparent.into(),
247                inner_bg: if selected {
248                    cx.theme().tokens.background.into()
249                } else {
250                    cx.theme().transparent.into()
251                },
252                ..Default::default()
253            },
254            TabVariant::Underline => TabStyle {
255                fg: cx.theme().tab_active_foreground,
256                bg: cx.theme().transparent.into(),
257                inner_bg: cx.theme().transparent.into(),
258                borders: Edges {
259                    bottom: px(2.),
260                    ..Default::default()
261                },
262                border_color: cx.theme().transparent,
263                ..Default::default()
264            },
265            // The hover fill is an inset rounded layer, see `Tab::render`.
266            TabVariant::Folder => TabStyle {
267                fg: cx.theme().tab_active_foreground,
268                bg: cx.theme().transparent.into(),
269                ..Default::default()
270            },
271        }
272    }
273
274    fn selected(&self, cx: &App) -> TabStyle {
275        match self {
276            TabVariant::Tab => TabStyle {
277                fg: cx.theme().tab_active_foreground,
278                bg: cx.theme().tokens.tab_active.into(),
279                borders: Edges {
280                    left: px(1.),
281                    right: px(1.),
282                    ..Default::default()
283                },
284                border_color: cx.theme().border,
285                ..Default::default()
286            },
287            TabVariant::Outline => TabStyle {
288                fg: cx.theme().primary,
289                bg: cx.theme().transparent.into(),
290                borders: Edges::all(px(1.)),
291                border_color: cx.theme().primary,
292                ..Default::default()
293            },
294            TabVariant::Pill => TabStyle {
295                fg: cx.theme().primary_foreground,
296                bg: cx.theme().tokens.primary.into(),
297                ..Default::default()
298            },
299            TabVariant::Segmented => TabStyle {
300                fg: cx.theme().tab_active_foreground,
301                bg: cx.theme().transparent.into(),
302                inner_bg: cx.theme().tokens.background.into(),
303                shadow: true,
304                ..Default::default()
305            },
306            TabVariant::Underline => TabStyle {
307                fg: cx.theme().tab_active_foreground,
308                bg: cx.theme().transparent.into(),
309                borders: Edges {
310                    bottom: px(2.),
311                    ..Default::default()
312                },
313                border_color: cx.theme().primary,
314                ..Default::default()
315            },
316            // The shape is painted by `folder_tab_shape`.
317            TabVariant::Folder => TabStyle {
318                fg: cx.theme().tab_active_foreground,
319                bg: cx.theme().transparent.into(),
320                ..Default::default()
321            },
322        }
323    }
324
325    fn disabled(&self, selected: bool, cx: &App) -> TabStyle {
326        match self {
327            TabVariant::Tab => TabStyle {
328                fg: cx.theme().muted_foreground,
329                bg: cx.theme().transparent.into(),
330                border_color: if selected {
331                    cx.theme().border
332                } else {
333                    cx.theme().transparent
334                },
335                borders: Edges {
336                    left: px(1.),
337                    right: px(1.),
338                    ..Default::default()
339                },
340                ..Default::default()
341            },
342            TabVariant::Outline => TabStyle {
343                fg: cx.theme().muted_foreground,
344                bg: cx.theme().transparent.into(),
345                borders: Edges::all(px(1.)),
346                border_color: if selected {
347                    cx.theme().primary
348                } else {
349                    cx.theme().border
350                },
351                ..Default::default()
352            },
353            TabVariant::Pill => TabStyle {
354                fg: if selected {
355                    cx.theme().primary_foreground.opacity(0.5)
356                } else {
357                    cx.theme().muted_foreground
358                },
359                bg: if selected {
360                    cx.theme().primary.opacity(0.5).into()
361                } else {
362                    cx.theme().transparent.into()
363                },
364                ..Default::default()
365            },
366            TabVariant::Segmented => TabStyle {
367                fg: cx.theme().muted_foreground,
368                bg: cx.theme().tokens.tab_bar.into(),
369                inner_bg: if selected {
370                    cx.theme().tokens.background.into()
371                } else {
372                    cx.theme().transparent.into()
373                },
374                ..Default::default()
375            },
376            TabVariant::Underline => TabStyle {
377                fg: cx.theme().muted_foreground,
378                bg: cx.theme().transparent.into(),
379                border_color: if selected {
380                    cx.theme().border
381                } else {
382                    cx.theme().transparent
383                },
384                borders: Edges {
385                    bottom: px(2.),
386                    ..Default::default()
387                },
388                ..Default::default()
389            },
390            TabVariant::Folder => TabStyle {
391                fg: cx.theme().muted_foreground,
392                bg: cx.theme().transparent.into(),
393                ..Default::default()
394            },
395        }
396    }
397
398    pub(super) fn tab_bar_radius(&self, size: Size, cx: &App) -> Pixels {
399        if *self != TabVariant::Segmented {
400            return px(0.);
401        }
402
403        match size {
404            Size::XSmall | Size::Small => cx.theme().radius,
405            Size::Large => cx.theme().radius_lg,
406            _ => cx.theme().radius_lg,
407        }
408    }
409
410    fn radius(&self, size: Size, cx: &App) -> Pixels {
411        match self {
412            TabVariant::Outline | TabVariant::Pill => cx.theme().radius_full(),
413            TabVariant::Segmented => match size {
414                Size::XSmall | Size::Small => cx.theme().radius,
415                Size::Large => cx.theme().radius_lg,
416                _ => cx.theme().radius_lg,
417            },
418            _ => px(0.),
419        }
420    }
421
422    pub(super) fn inner_radius(&self, size: Size, cx: &App) -> Pixels {
423        match self {
424            // The inset the active pill sits at, taken off the bar's own radius
425            // so the two curves stay concentric. Floored at zero: a square bar
426            // has nothing to inset from.
427            TabVariant::Segmented => match size {
428                Size::Large => (self.tab_bar_radius(size, cx) - px(3.)).max(px(0.)),
429                _ => (self.tab_bar_radius(size, cx) - px(2.)).max(px(0.)),
430            },
431            _ => px(0.),
432        }
433    }
434
435    /// How far a tab's painting reaches past its bounds on either side.
436    pub(super) fn overhang(&self, size: Size, cx: &App) -> Pixels {
437        match self {
438            TabVariant::Folder => FolderTabMetrics::new(size, cx).radius,
439            _ => px(0.),
440        }
441    }
442}
443
444/// The selected [`TabVariant::Folder`] tab: rounded on top and curving out at
445/// the bottom into the content below, traced after Chrome's tab path.
446fn folder_tab_shape(metrics: FolderTabMetrics, bg: Background) -> impl IntoElement {
447    let curve = metrics.radius;
448    canvas(
449        |_, _, _| {},
450        move |bounds, _, window, _| {
451            let (top, bottom) = (bounds.top(), bounds.bottom());
452            let (left, right) = (bounds.left(), bounds.right());
453            let (tab_left, tab_right) = (left + curve, right - curve);
454            // Like Chrome, keep at least a third of the top flat on narrow tabs.
455            let radius = ((bounds.size.width - curve * 2.) / 3.).clamp(px(0.), curve);
456
457            let mut path =
458                PathBuilder::fill().with_style(PathStyle::Fill(FillOptions::tolerance(0.02)));
459            path.move_to(point(left, bottom));
460            quarter_circle_to(
461                &mut path,
462                point(left, bottom),
463                point(tab_left, bottom),
464                point(tab_left, bottom - curve),
465            );
466            path.line_to(point(tab_left, top + radius));
467            quarter_circle_to(
468                &mut path,
469                point(tab_left, top + radius),
470                point(tab_left, top),
471                point(tab_left + radius, top),
472            );
473            path.line_to(point(tab_right - radius, top));
474            quarter_circle_to(
475                &mut path,
476                point(tab_right - radius, top),
477                point(tab_right, top),
478                point(tab_right, top + radius),
479            );
480            path.line_to(point(tab_right, bottom - curve));
481            quarter_circle_to(
482                &mut path,
483                point(tab_right, bottom - curve),
484                point(tab_right, bottom),
485                point(right, bottom),
486            );
487            path.close();
488            if let Ok(path) = path.build() {
489                window.paint_path(path, bg);
490            }
491        },
492    )
493    .absolute()
494    .top_0()
495    .bottom_0()
496    .left(-curve)
497    .right(-curve)
498}
499
500/// Adds a quarter circle from `from` to `to`, whose tangents meet at `corner`.
501fn quarter_circle_to(
502    path: &mut PathBuilder,
503    from: Point<Pixels>,
504    corner: Point<Pixels>,
505    to: Point<Pixels>,
506) {
507    // Control point distance that makes a cubic Bézier a quarter circle.
508    const K: f32 = 0.552_284_8;
509    path.cubic_bezier_to(to, from + (corner - from) * K, to + (corner - to) * K);
510}
511
512#[allow(dead_code)]
513struct TabStyle {
514    borders: Edges<Pixels>,
515    border_color: Hsla,
516    bg: Background,
517    fg: Hsla,
518    shadow: bool,
519    inner_bg: Background,
520}
521
522impl Default for TabStyle {
523    fn default() -> Self {
524        TabStyle {
525            borders: Edges::all(px(0.)),
526            border_color: gpui::transparent_white(),
527            bg: gpui::transparent_white().into(),
528            fg: gpui::transparent_white(),
529            shadow: false,
530            inner_bg: gpui::transparent_white().into(),
531        }
532    }
533}
534
535/// A Tab element for the [`super::TabBar`].
536#[derive(IntoElement)]
537pub struct Tab {
538    ix: usize,
539    base: gpui_base::Tab,
540    pub(super) label: Option<SharedString>,
541    aria_label: Option<SharedString>,
542    pub(super) icon: Option<Icon>,
543    prefix: Option<AnyElement>,
544    pub(super) tab_bar_prefix: Option<bool>,
545    suffix: Option<AnyElement>,
546    children: Vec<AnyElement>,
547    variant: TabVariant,
548    size: Size,
549    pub(super) disabled: bool,
550    pub(super) selected: bool,
551    pub(super) indicator_active: bool,
552    pub(super) indicator_ready: bool,
553    /// Animation epoch of the [`super::TabBar`] indicator; increments on every
554    /// tab switch. Used to key the selected tab's text color fade so it
555    /// restarts in sync with the indicator slide.
556    pub(super) indicator_epoch: u64,
557    /// Whether a [`TabVariant::Folder`] tab draws the divider after it.
558    pub(super) separator: bool,
559    /// Whether the [`super::TabBar`] reports the pointer over this tab. Kept
560    /// there rather than in a hover group, which would replace the caller's.
561    pub(super) hovered: bool,
562    pub(super) max_width: Option<Pixels>,
563    pub(super) on_click: Option<Rc<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>>,
564}
565
566impl From<&'static str> for Tab {
567    fn from(label: &'static str) -> Self {
568        Self::new().label(label)
569    }
570}
571
572impl From<String> for Tab {
573    fn from(label: String) -> Self {
574        Self::new().label(label)
575    }
576}
577
578impl From<SharedString> for Tab {
579    fn from(label: SharedString) -> Self {
580        Self::new().label(label)
581    }
582}
583
584impl From<Icon> for Tab {
585    fn from(icon: Icon) -> Self {
586        Self::default().icon(icon)
587    }
588}
589
590impl From<IconName> for Tab {
591    fn from(icon_name: IconName) -> Self {
592        Self::default().icon(Icon::new(icon_name))
593    }
594}
595
596impl Default for Tab {
597    fn default() -> Self {
598        Self {
599            ix: 0,
600            base: gpui_base::Tab::new(0usize),
601            label: None,
602            aria_label: None,
603            icon: None,
604            tab_bar_prefix: None,
605            children: Vec::new(),
606            disabled: false,
607            selected: false,
608            indicator_active: false,
609            indicator_ready: true,
610            indicator_epoch: 0,
611            separator: false,
612            hovered: false,
613            prefix: None,
614            suffix: None,
615            variant: TabVariant::default(),
616            size: Size::default(),
617            max_width: None,
618            on_click: None,
619        }
620    }
621}
622
623impl Tab {
624    /// Create a new tab with a label.
625    pub fn new() -> Self {
626        Self::default()
627    }
628
629    /// Set label for the tab.
630    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
631        self.label = Some(label.into());
632        self
633    }
634
635    /// Set the accessible label for the tab.
636    pub fn aria_label(mut self, label: impl Into<SharedString>) -> Self {
637        self.aria_label = Some(label.into());
638        self
639    }
640
641    fn a11y_label(&self) -> Option<SharedString> {
642        self.aria_label.clone().or_else(|| self.label.clone())
643    }
644
645    /// Set icon for the tab.
646    pub fn icon(mut self, icon: impl Into<Icon>) -> Self {
647        self.icon = Some(icon.into());
648        self
649    }
650
651    /// Set Tab Variant.
652    pub fn with_variant(mut self, variant: TabVariant) -> Self {
653        self.variant = variant;
654        self
655    }
656
657    /// Use Pill variant.
658    pub fn pill(mut self) -> Self {
659        self.variant = TabVariant::Pill;
660        self
661    }
662
663    /// Use outline variant.
664    pub fn outline(mut self) -> Self {
665        self.variant = TabVariant::Outline;
666        self
667    }
668
669    /// Use Segmented variant.
670    pub fn segmented(mut self) -> Self {
671        self.variant = TabVariant::Segmented;
672        self
673    }
674
675    /// Use Underline variant.
676    pub fn underline(mut self) -> Self {
677        self.variant = TabVariant::Underline;
678        self
679    }
680
681    /// Use Folder variant.
682    pub fn folder(mut self) -> Self {
683        self.variant = TabVariant::Folder;
684        self
685    }
686
687    /// Set the left side of the tab
688    pub fn prefix(mut self, prefix: impl IntoElement) -> Self {
689        self.prefix = Some(prefix.into_any_element());
690        self
691    }
692
693    /// Set the right side of the tab
694    pub fn suffix(mut self, suffix: impl IntoElement) -> Self {
695        self.suffix = Some(suffix.into_any_element());
696        self
697    }
698
699    /// Set disabled state to the tab, default false.
700    pub fn disabled(mut self, disabled: bool) -> Self {
701        self.disabled = disabled;
702        self
703    }
704
705    /// Set the click handler for the tab.
706    pub fn on_click(
707        mut self,
708        on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
709    ) -> Self {
710        self.on_click = Some(Rc::new(on_click));
711        self
712    }
713
714    /// Set index to the tab.
715    pub(crate) fn ix(mut self, ix: usize) -> Self {
716        self.ix = ix;
717        self.base = self.base.id(ix);
718        self
719    }
720
721    /// Set if the tab bar has a prefix.
722    pub(crate) fn tab_bar_prefix(mut self, tab_bar_prefix: bool) -> Self {
723        self.tab_bar_prefix = Some(tab_bar_prefix);
724        self
725    }
726
727    /// Set the maximum width of the tab, see [`super::TabBar::max_width`].
728    pub(super) fn max_width(mut self, max_width: Option<Pixels>) -> Self {
729        self.max_width = max_width;
730        self
731    }
732}
733
734impl ParentElement for Tab {
735    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
736        self.children.extend(elements);
737    }
738}
739
740impl Selectable for Tab {
741    fn selected(mut self, selected: bool) -> Self {
742        self.selected = selected;
743        self
744    }
745
746    fn is_selected(&self) -> bool {
747        self.selected
748    }
749}
750
751impl InteractiveElement for Tab {
752    fn interactivity(&mut self) -> &mut gpui::Interactivity {
753        self.base.interactivity()
754    }
755}
756
757impl StatefulInteractiveElement for Tab {}
758
759impl Styled for Tab {
760    fn style(&mut self) -> &mut gpui::StyleRefinement {
761        self.base.style()
762    }
763}
764
765impl Sizable for Tab {
766    fn with_size(mut self, size: impl Into<Size>) -> Self {
767        self.size = size.into();
768        self
769    }
770}
771
772impl RenderOnce for Tab {
773    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
774        let mut normal_style = self.variant.normal(cx);
775        let mut selected_style = self.variant.selected(cx);
776        let mut disabled_style = self.variant.disabled(self.selected, cx);
777        let mut hover_style = self.variant.hovered(self.selected, cx);
778        if self.disabled {
779            hover_style = self.variant.disabled(self.selected, cx);
780        }
781        let tab_bar_prefix = self.tab_bar_prefix.unwrap_or_default();
782        if !tab_bar_prefix {
783            // The first tab meets the bar's start edge, so it drops that border.
784            if self.ix == 0 && self.variant == TabVariant::Tab {
785                let rtl = gpui_base::LayoutDirection::global(cx).is_rtl();
786                for style in [
787                    &mut normal_style,
788                    &mut selected_style,
789                    &mut disabled_style,
790                    &mut hover_style,
791                ] {
792                    if rtl {
793                        style.borders.right = px(0.);
794                    } else {
795                        style.borders.left = px(0.);
796                    }
797                }
798            }
799        }
800        let tab_style = if self.disabled {
801            &disabled_style
802        } else if self.selected {
803            &selected_style
804        } else {
805            &normal_style
806        };
807        let radius = self.variant.radius(self.size, cx);
808        let inner_radius = self.variant.inner_radius(self.size, cx);
809        let inner_paddings = self.variant.inner_paddings(self.size);
810        let inner_margins = self.variant.inner_margins(self.size);
811        let inner_height = self.variant.inner_height(self.size);
812        let height = self.variant.height(self.size);
813        let aria_label = self.a11y_label();
814        let folder = self.variant == TabVariant::Folder;
815        let metrics = FolderTabMetrics::new(self.size, cx);
816        let has_prefix = self.prefix.is_some();
817
818        let segmented_indicator_active =
819            self.variant == TabVariant::Segmented && self.indicator_active;
820        let has_inline_inner_bg =
821            self.selected && segmented_indicator_active && !self.indicator_ready;
822        let inline_inner_bg = tab_style.inner_bg;
823        let (inner_bg, hover_inner_bg) = if segmented_indicator_active && self.indicator_ready {
824            (cx.theme().transparent.into(), cx.theme().transparent.into())
825        } else if has_inline_inner_bg {
826            (inline_inner_bg, inline_inner_bg)
827        } else {
828            (tab_style.inner_bg, hover_style.inner_bg)
829        };
830        let inner_shadow = tab_style.shadow && !segmented_indicator_active;
831
832        // When a sliding indicator is active and ready, it alone represents the
833        // selected state. Suppress the selected tab's own active background/border
834        // so the two don't overlap during the switch animation (Segmented already
835        // does this for its `inner_bg` above). Skip disabled tabs so a
836        // disabled-selected tab keeps its dimmed styling instead of the
837        // full-strength indicator color.
838        let suppress_active_visual =
839            self.selected && !self.disabled && self.indicator_active && self.indicator_ready;
840        // Pill paints its active state via the outer `bg`.
841        let selected_outer_bg = if suppress_active_visual && self.variant == TabVariant::Pill {
842            cx.theme().transparent.into()
843        } else {
844            selected_style.bg
845        };
846        // Underline paints its active state via the bottom `border_color`.
847        let selected_outer_border_color =
848            if suppress_active_visual && self.variant == TabVariant::Underline {
849                cx.theme().transparent
850            } else {
851                selected_style.border_color
852            };
853
854        // For Pill, the newly selected tab's text color (`primary_foreground`)
855        // would otherwise snap to white instantly while the indicator is still
856        // sliding into place. Fade it from the normal color in sync with the
857        // indicator slide (keyed on the indicator epoch so it restarts on each
858        // switch). `epoch == 0` is the initial layout (no slide), so we skip it.
859        let animate_fg = self.selected
860            && !self.disabled
861            && self.variant == TabVariant::Pill
862            && self.indicator_active
863            && self.indicator_ready
864            && self.indicator_epoch > 0;
865        let fg_from = self.variant.normal(cx).fg;
866        let fg_to = tab_style.fg;
867        // Icon-only tabs are fixed-size and exempt from `max_width`.
868        let max_width = self.max_width.filter(|_| self.icon.is_none());
869
870        let inner_content = h_flex()
871            .flex_1()
872            .h(inner_height)
873            .line_height(relative(1.25))
874            .whitespace_nowrap()
875            .items_center()
876            .justify_center()
877            .overflow_hidden()
878            .margins(inner_margins)
879            // Normally the label decides the tab width, so it never shrinks. With
880            // `max_width` it is the one part that gives way.
881            .map(|this| match max_width {
882                Some(_) => this.flex_auto(),
883                None => this.flex_shrink_0(),
884            })
885            .map(|this| match self.icon {
886                // `flex_1()` above zeroes the basis, so `w` alone collapses the
887                // box to the icon; `min_w` holds the width it asks for.
888                Some(icon) => this
889                    .w(inner_height * 1.25)
890                    .min_w(inner_height * 1.25)
891                    .child(icon.map(|this| match self.size {
892                        Size::XSmall => this.size_2p5(),
893                        Size::Small => this.size_3p5(),
894                        Size::Large => this.size_4(),
895                        _ => this.size_4(),
896                    })),
897                None => this
898                    .paddings(inner_paddings)
899                    .map(|this| match (self.label, max_width) {
900                        // Text always takes its natural width, so it needs a box
901                        // that is allowed to shrink to ellipsize inside of.
902                        (Some(label), Some(_)) => this.child(
903                            div()
904                                .min_w_0()
905                                .whitespace_nowrap()
906                                .text_ellipsis()
907                                .child(label),
908                        ),
909                        (Some(label), None) => this.child(label),
910                        (None, _) => this,
911                    })
912                    .children(self.children)
913                    // With the prefix's gap, 8px between icon and title, as in a Button.
914                    .when(folder && has_prefix, |this| this.ps(px(4.), cx)),
915            })
916            .bg(inner_bg)
917            .rounded(inner_radius)
918            .when(inner_shadow, |this| this.shadow_xs())
919            .hover(|this| this.bg(hover_inner_bg).rounded(inner_radius));
920
921        let inner_element = if animate_fg {
922            inner_content
923                .with_animation(
924                    ElementId::NamedInteger("tab-fg".into(), self.indicator_epoch),
925                    Animation::new(Duration::from_millis(200)).with_easing(ease_in_out_cubic),
926                    move |this, delta| this.text_color(Lerp::lerp(&fg_from, &fg_to, delta)),
927                )
928                .into_any_element()
929        } else {
930            inner_content.into_any_element()
931        };
932
933        let ring = cx.theme().ring;
934        self.base
935            .id(self.ix)
936            .selected(self.selected)
937            .disabled(self.disabled)
938            .when_some(aria_label, |this, label| this.accessibility_label(label))
939            .styles(|styles| {
940                styles
941                    .selected(|style| {
942                        style
943                            .text_color(selected_style.fg)
944                            .bg(selected_outer_bg)
945                            .border_l(selected_style.borders.left)
946                            .border_r(selected_style.borders.right)
947                            .border_t(selected_style.borders.top)
948                            .border_b(selected_style.borders.bottom)
949                            .border_color(selected_outer_border_color)
950                    })
951                    .disabled(|style| {
952                        style
953                            .text_color(disabled_style.fg)
954                            .bg(disabled_style.bg)
955                            .border_l(disabled_style.borders.left)
956                            .border_r(disabled_style.borders.right)
957                            .border_t(disabled_style.borders.top)
958                            .border_b(disabled_style.borders.bottom)
959                            .border_color(disabled_style.border_color)
960                    })
961            })
962            // Keyboard focus (the tab list roves it with the arrow keys) gets
963            // the theme ring. An inset shadow draws it inside the tab, so the
964            // bar neither shifts nor clips it as focus moves.
965            .focus_visible(|style| {
966                style.shadow(vec![gpui::BoxShadow {
967                    color: ring,
968                    offset: point(px(0.), px(0.)),
969                    blur_radius: px(0.),
970                    spread_radius: px(2.),
971                    inset: true,
972                }])
973            })
974            .relative()
975            // Prefix, label and suffix read from the start edge.
976            .flex_row_dir(cx)
977            // Wrapping would move the overflow onto a clipped second line instead
978            // of letting the label shrink, so a capped tab lays out on one line.
979            .map(|this| match max_width {
980                Some(max_width) => this.flex_nowrap().max_w(max_width),
981                None => this.flex_wrap(),
982            })
983            .gap_1()
984            .items_center()
985            .flex_shrink_0()
986            .h(height)
987            // A folder tab's curves reach past its bounds.
988            .when(!folder, |this| this.overflow_hidden())
989            .map(|this| match self.size {
990                Size::XSmall => this.text_xs(),
991                Size::Large => this.text_base(),
992                _ => this.text_sm(),
993            })
994            .rounded(radius)
995            .when(folder, |this| {
996                this.px(metrics.padding_x).pb(metrics.top_padding)
997            })
998            .when(!self.selected && !self.disabled, |this| {
999                this.text_color(normal_style.fg)
1000                    .bg(normal_style.bg)
1001                    .border_l(normal_style.borders.left)
1002                    .border_r(normal_style.borders.right)
1003                    .border_t(normal_style.borders.top)
1004                    .border_b(normal_style.borders.bottom)
1005                    .border_color(normal_style.border_color)
1006            })
1007            .hover(|this| {
1008                // Always register the hover style: GPUI only refreshes the cached
1009                // hover state while one is present. If the selected tab skipped it,
1010                // the stale state would keep hover colors after unselecting.
1011                if self.selected || self.disabled {
1012                    return this;
1013                }
1014                this.text_color(hover_style.fg)
1015                    .bg(hover_style.bg)
1016                    .border_l(hover_style.borders.left)
1017                    .border_r(hover_style.borders.right)
1018                    .border_t(hover_style.borders.top)
1019                    .border_b(hover_style.borders.bottom)
1020                    .border_color(hover_style.border_color)
1021                    .rounded(radius)
1022            })
1023            .when(folder && self.selected, |this| {
1024                this.child(folder_tab_shape(
1025                    metrics,
1026                    cx.theme().tokens.tab_active.into(),
1027                ))
1028            })
1029            .when(
1030                folder && self.hovered && !self.selected && !self.disabled,
1031                |this| {
1032                    this.child(
1033                        div()
1034                            .absolute()
1035                            .top_0()
1036                            .left_0()
1037                            .right_0()
1038                            .bottom(metrics.top_padding)
1039                            .rounded(metrics.radius)
1040                            .bg(cx.theme().tokens.secondary),
1041                    )
1042                },
1043            )
1044            // In the gap after the tab (on its end edge), on a whole pixel, level
1045            // with the content.
1046            .when(folder && self.separator, |this| {
1047                this.child(
1048                    div()
1049                        .absolute()
1050                        .inset_e(-(FOLDER_TAB_GAP / 2.), cx)
1051                        .top((height - metrics.top_padding - metrics.separator_height) / 2.)
1052                        .w(px(1.))
1053                        .h(metrics.separator_height)
1054                        .bg(cx.theme().border),
1055                )
1056            })
1057            .when(has_inline_inner_bg, |this| {
1058                this.child(
1059                    div()
1060                        .absolute()
1061                        .left_0()
1062                        .right_0()
1063                        .top_0()
1064                        .bottom_0()
1065                        .flex()
1066                        .items_center()
1067                        .child(
1068                            div()
1069                                .w_full()
1070                                .h(inner_height)
1071                                .bg(inline_inner_bg)
1072                                .rounded(inner_radius)
1073                                .when(tab_style.shadow, |this| this.shadow_sm()),
1074                        ),
1075                )
1076            })
1077            // Under `max_width` the label is the only part that gives way, so
1078            // hold the prefix and suffix (e.g. a close button) at their full size.
1079            .when_some(self.prefix, |this, prefix| {
1080                this.child(
1081                    div()
1082                        .when_some(max_width, |this, _| this.flex_shrink_0())
1083                        .child(prefix),
1084                )
1085            })
1086            .child(inner_element)
1087            .when_some(self.suffix, |this, suffix| {
1088                this.child(
1089                    div()
1090                        .when_some(max_width, |this, _| this.flex_shrink_0())
1091                        .child(suffix),
1092                )
1093            })
1094            .when_some(self.on_click.clone(), |this, on_click| {
1095                this.on_click(move |event, window, cx| on_click(event, window, cx))
1096            })
1097    }
1098}
1099
1100#[cfg(test)]
1101mod tests {
1102    use super::*;
1103    use crate::tab::TabBar;
1104    use gpui::{Context, Render, TestAppContext, VisualTestContext};
1105
1106    const VARIANTS: [TabVariant; 6] = [
1107        TabVariant::Tab,
1108        TabVariant::Outline,
1109        TabVariant::Pill,
1110        TabVariant::Segmented,
1111        TabVariant::Underline,
1112        TabVariant::Folder,
1113    ];
1114
1115    const LONG_LABEL: &str = "Account Settings & Preferences";
1116
1117    /// One [`TabBar`], optionally capped, holding the tab `build` returns.
1118    struct TabBarTest {
1119        variant: TabVariant,
1120        max_width: Option<Pixels>,
1121        build: fn(Tab) -> Tab,
1122    }
1123
1124    impl Render for TabBarTest {
1125        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1126            TabBar::new("tabs")
1127                .with_variant(self.variant)
1128                .selected_index(0)
1129                .when_some(self.max_width, |this, width| this.max_width(width))
1130                .child((self.build)(
1131                    Tab::new().debug_selector(|| "tab".to_string()),
1132                ))
1133        }
1134    }
1135
1136    fn show(
1137        cx: &mut TestAppContext,
1138        variant: TabVariant,
1139        max_width: Option<Pixels>,
1140        build: fn(Tab) -> Tab,
1141    ) -> &mut VisualTestContext {
1142        cx.update(crate::init);
1143        let (_, cx) = cx.add_window_view(|_, _| TabBarTest {
1144            variant,
1145            max_width,
1146            build,
1147        });
1148        cx.run_until_parked();
1149        cx
1150    }
1151
1152    /// Outer width of a labelled tab in every variant, capped or not.
1153    fn variant_widths(
1154        cx: &mut TestAppContext,
1155        build: fn(Tab) -> Tab,
1156        max_width: Option<Pixels>,
1157    ) -> Vec<Pixels> {
1158        VARIANTS
1159            .into_iter()
1160            .map(|variant| {
1161                show(cx, variant, max_width, build)
1162                    .debug_bounds("tab")
1163                    .expect("tab not rendered")
1164                    .size
1165                    .width
1166            })
1167            .collect()
1168    }
1169
1170    #[gpui::test]
1171    fn a11y_label_defaults_to_visible_label(_cx: &mut TestAppContext) {
1172        let tab = Tab::new().label("Account");
1173
1174        assert_eq!(tab.a11y_label(), Some("Account".into()));
1175    }
1176
1177    #[gpui::test]
1178    fn explicit_a11y_label_overrides_visible_label(_cx: &mut TestAppContext) {
1179        let tab = Tab::new().label("Acct").aria_label("Account settings");
1180
1181        assert_eq!(tab.a11y_label(), Some("Account settings".into()));
1182    }
1183
1184    #[gpui::test]
1185    fn max_width_leaves_short_tabs_untouched(cx: &mut TestAppContext) {
1186        // The box the cap wraps the label in must not report a different
1187        // intrinsic width than the bare label it replaces.
1188        let build: fn(Tab) -> Tab = |tab| tab.label("Go");
1189
1190        let uncapped = variant_widths(cx, build, None);
1191        let capped = variant_widths(cx, build, Some(px(200.)));
1192
1193        assert_eq!(uncapped, capped, "a tab under the cap must not be resized");
1194    }
1195
1196    #[gpui::test]
1197    fn max_width_caps_long_tabs(cx: &mut TestAppContext) {
1198        let build: fn(Tab) -> Tab = |tab| tab.label(LONG_LABEL);
1199
1200        let uncapped = variant_widths(cx, build, None);
1201        let capped = variant_widths(cx, build, Some(px(120.)));
1202
1203        for (variant, (uncapped, capped)) in
1204            VARIANTS.into_iter().zip(uncapped.into_iter().zip(capped))
1205        {
1206            assert!(
1207                uncapped > px(120.),
1208                "{variant:?} is not long enough to exercise the cap ({uncapped:?})"
1209            );
1210            assert!(
1211                capped <= px(120.),
1212                "{variant:?} width {capped:?} exceeds max_width"
1213            );
1214        }
1215    }
1216
1217    #[gpui::test]
1218    fn max_width_keeps_prefix_and_suffix_intact(cx: &mut TestAppContext) {
1219        let cx = show(cx, TabVariant::Segmented, Some(px(140.)), |tab| {
1220            tab.prefix(Icon::new(IconName::BookOpen))
1221                .label(LONG_LABEL)
1222                .suffix(div().size(px(16.)).debug_selector(|| "suffix".to_string()))
1223        });
1224
1225        let tab = cx.debug_bounds("tab").expect("tab not rendered");
1226        let suffix = cx.debug_bounds("suffix").expect("suffix not rendered");
1227
1228        assert!(tab.size.width <= px(140.));
1229        assert_eq!(
1230            suffix.size.width,
1231            px(16.),
1232            "the label should absorb the truncation, not the suffix"
1233        );
1234        assert!(
1235            suffix.right() <= tab.right(),
1236            "suffix must stay within the tab"
1237        );
1238        // A wrapping tab pushes the suffix onto a second line, which the fixed
1239        // tab height then clips: it keeps its size and stays inside the tab,
1240        // but lands back at the left edge instead of after the label.
1241        assert!(
1242            suffix.left() > tab.center().x,
1243            "suffix must follow the label, not wrap below it"
1244        );
1245    }
1246
1247    #[gpui::test]
1248    fn a_right_to_left_tab_puts_its_prefix_on_the_right(cx: &mut TestAppContext) {
1249        cx.update(|cx| {
1250            crate::init(cx);
1251            gpui_base::LayoutDirection::Rtl.set_global(cx);
1252        });
1253        let cx = show(cx, TabVariant::Tab, None, |tab| {
1254            tab.prefix(div().size(px(16.)).debug_selector(|| "prefix".to_string()))
1255                .label("Label")
1256                .suffix(div().size(px(16.)).debug_selector(|| "suffix".to_string()))
1257        });
1258
1259        let prefix = cx.debug_bounds("prefix").expect("prefix not rendered");
1260        let suffix = cx.debug_bounds("suffix").expect("suffix not rendered");
1261        assert!(
1262            suffix.right() < prefix.left(),
1263            "the suffix ends the row on the left: {suffix:?} {prefix:?}"
1264        );
1265    }
1266
1267    /// Icon-only tabs are sized to a square by construction, so the cap has to
1268    /// leave them alone however narrow it is.
1269    #[gpui::test]
1270    fn max_width_exempts_icon_only_tabs(cx: &mut TestAppContext) {
1271        let build: fn(Tab) -> Tab = |tab| tab.icon(Icon::new(IconName::BookOpen));
1272        let width = |cx: &mut TestAppContext, max_width| {
1273            show(cx, TabVariant::Tab, max_width, build)
1274                .debug_bounds("tab")
1275                .expect("tab not rendered")
1276                .size
1277                .width
1278        };
1279
1280        let uncapped = width(cx, None);
1281        assert!(
1282            uncapped > px(16.),
1283            "the cap has to be narrower than the icon tab to be meaningful"
1284        );
1285        assert_eq!(
1286            width(cx, Some(px(16.))),
1287            uncapped,
1288            "an icon-only tab must ignore max_width"
1289        );
1290    }
1291
1292    /// An icon-only tab keeps the room its content box asks for, so the icon has
1293    /// space on both sides instead of the tabs packing icon against icon.
1294    #[gpui::test]
1295    fn icon_only_tabs_keep_their_width(cx: &mut TestAppContext) {
1296        let build: fn(Tab) -> Tab = |tab| tab.icon(Icon::new(IconName::BookOpen));
1297        for variant in VARIANTS {
1298            let width = show(cx, variant, None, build)
1299                .debug_bounds("tab")
1300                .expect("tab not rendered")
1301                .size
1302                .width;
1303            let content = variant.inner_height(Size::default()) * 1.25;
1304            assert!(
1305                width >= content,
1306                "{variant:?}: icon-only tab is {width:?}, narrower than its {content:?} content"
1307            );
1308        }
1309    }
1310}