Skip to main content

gpui_component/tab/
tab_bar.rs

1use std::{cell::RefCell, rc::Rc, time::Duration};
2
3use gpui::{
4    Anchor, AnyElement, App, Background, Bounds, Edges, ElementId, InteractiveElement, IntoElement,
5    ParentElement, Pixels, RenderOnce, ScrollHandle, SharedString, StatefulInteractiveElement as _,
6    StyleRefinement, Styled, Window, div, prelude::FluentBuilder as _, px,
7};
8use gpui_base::{Spring, spring};
9use rust_i18n::t;
10use smallvec::SmallVec;
11
12use super::{Tab, TabVariant};
13use crate::button::{Button, ButtonVariants as _};
14use crate::menu::{DropdownMenu as _, PopupMenuItem};
15use crate::{
16    ActiveTheme, ElementExt, Icon, InteractiveElementExt as _, Selectable, Sizable, Size,
17    StyledExt, h_flex, styled::raised_shadow,
18};
19
20/// Slide motion for the selected-tab indicator.
21///
22/// Slightly underdamped, so the indicator arrives with a hint of weight rather
23/// than stopping dead. Settling is measured in pixels, so the tolerance is
24/// coarsened from the normalized default to end the animation once the
25/// remaining travel is sub-pixel.
26const INDICATOR_SPRING: Spring = Spring::new(Duration::from_millis(250))
27    .with_damping(0.85)
28    .with_epsilon(0.1);
29
30struct TabIndicatorBounds {
31    container: Bounds<Pixels>,
32    tabs: Vec<Bounds<Pixels>>,
33}
34
35impl TabIndicatorBounds {
36    fn new(num_tabs: usize) -> Self {
37        Self {
38            container: Bounds::default(),
39            tabs: vec![Bounds::default(); num_tabs],
40        }
41    }
42
43    fn resize(&mut self, num_tabs: usize) {
44        self.tabs.resize(num_tabs, Bounds::default());
45    }
46}
47
48/// A TabBar element that contains multiple [`Tab`] items.
49#[derive(IntoElement)]
50pub struct TabBar {
51    id: ElementId,
52    base: gpui_base::Tabs,
53    style: StyleRefinement,
54    scroll_handle: Option<ScrollHandle>,
55    prefix: Option<AnyElement>,
56    suffix: Option<AnyElement>,
57    children: SmallVec<[Tab; 2]>,
58    last_empty_space: AnyElement,
59    selected_index: Option<usize>,
60    variant: TabVariant,
61    size: Size,
62    menu: bool,
63    max_width: Option<Pixels>,
64    on_click: Option<Rc<dyn Fn(&usize, &mut Window, &mut App) + 'static>>,
65}
66
67impl TabBar {
68    /// Create a new TabBar.
69    pub fn new(id: impl Into<ElementId>) -> Self {
70        let id = id.into();
71        Self {
72            id: id.clone(),
73            base: gpui_base::Tabs::new(id).px(px(-1.)),
74            style: StyleRefinement::default(),
75            children: SmallVec::new(),
76            scroll_handle: None,
77            prefix: None,
78            suffix: None,
79            variant: TabVariant::default(),
80            size: Size::default(),
81            last_empty_space: div().w_3().into_any_element(),
82            selected_index: None,
83            on_click: None,
84            menu: false,
85            max_width: None,
86        }
87    }
88
89    /// Set the Tab variant, all children will inherit the variant.
90    pub fn with_variant(mut self, variant: TabVariant) -> Self {
91        self.variant = variant;
92        self
93    }
94
95    /// Set the Tab variant to Pill, all children will inherit the variant.
96    pub fn pill(mut self) -> Self {
97        self.variant = TabVariant::Pill;
98        self
99    }
100
101    /// Set the Tab variant to Outline, all children will inherit the variant.
102    pub fn outline(mut self) -> Self {
103        self.variant = TabVariant::Outline;
104        self
105    }
106
107    /// Set the Tab variant to Segmented, all children will inherit the variant.
108    pub fn segmented(mut self) -> Self {
109        self.variant = TabVariant::Segmented;
110        self
111    }
112
113    /// Set the Tab variant to Underline, all children will inherit the variant.
114    pub fn underline(mut self) -> Self {
115        self.variant = TabVariant::Underline;
116        self
117    }
118
119    /// Set whether to show the menu button when tabs overflow, default is false.
120    pub fn menu(mut self, menu: bool) -> Self {
121        self.menu = menu;
122        self
123    }
124
125    /// Set the maximum width of each tab. Labels longer than this width are
126    /// truncated with an ellipsis. Does not apply to icon-only tabs. The
127    /// overflow menu still shows the full label.
128    pub fn max_width(mut self, width: impl Into<Pixels>) -> Self {
129        self.max_width = Some(width.into());
130        self
131    }
132
133    /// Track the scroll of the TabBar.
134    pub fn track_scroll(mut self, scroll_handle: &ScrollHandle) -> Self {
135        self.scroll_handle = Some(scroll_handle.clone());
136        self
137    }
138
139    /// Set the prefix element of the TabBar
140    pub fn prefix(mut self, prefix: impl IntoElement) -> Self {
141        self.prefix = Some(prefix.into_any_element());
142        self
143    }
144
145    /// Set the suffix element of the TabBar
146    pub fn suffix(mut self, suffix: impl IntoElement) -> Self {
147        self.suffix = Some(suffix.into_any_element());
148        self
149    }
150
151    /// Add children of the TabBar, all children will inherit the variant.
152    pub fn children(mut self, children: impl IntoIterator<Item = impl Into<Tab>>) -> Self {
153        self.children.extend(children.into_iter().map(Into::into));
154        self
155    }
156
157    /// Add child of the TabBar, tab will inherit the variant.
158    pub fn child(mut self, child: impl Into<Tab>) -> Self {
159        self.children.push(child.into());
160        self
161    }
162
163    /// Set the selected index of the TabBar.
164    pub fn selected_index(mut self, index: usize) -> Self {
165        self.selected_index = Some(index);
166        self
167    }
168
169    /// Set the last empty space element of the TabBar.
170    pub fn last_empty_space(mut self, last_empty_space: impl IntoElement) -> Self {
171        self.last_empty_space = last_empty_space.into_any_element();
172        self
173    }
174
175    /// Set the on_click callback of the TabBar, the first parameter is the index of the clicked tab.
176    ///
177    /// When this is set, the children's on_click will be ignored.
178    pub fn on_click<F>(mut self, on_click: F) -> Self
179    where
180        F: Fn(&usize, &mut Window, &mut App) + 'static,
181    {
182        self.on_click = Some(Rc::new(on_click));
183        self
184    }
185
186    /// Render the sliding indicator element for animated tab switching.
187    ///
188    /// Returns the indicator element together with the current animation
189    /// `epoch`, which increments on every tab switch. Tabs key their own
190    /// transitions (e.g. text color fade) on this epoch so they restart in sync
191    /// with the indicator slide.
192    fn render_indicator(
193        &self,
194        bounds_rc: &Option<Rc<RefCell<TabIndicatorBounds>>>,
195        inset: Pixels,
196        window: &mut Window,
197        cx: &mut App,
198    ) -> Option<(AnyElement, u64)> {
199        let has_indicator = matches!(
200            self.variant,
201            TabVariant::Segmented | TabVariant::Pill | TabVariant::Underline
202        );
203        let num_tabs = self.children.len();
204        let selected_ix = self.selected_index.unwrap_or(usize::MAX);
205
206        if !(has_indicator && num_tabs > 0 && selected_ix < num_tabs) {
207            return None;
208        }
209
210        let prev_key = format!("{}-tab-prev", self.id);
211        let anim_key = format!("{}-tab-anim", self.id);
212        let init_key = format!("{}-tab-init", self.id);
213
214        let prev_selected = window.use_keyed_state(prev_key, cx, |_, _| selected_ix);
215        // (to_left, to_width, epoch)
216        let anim_params = window.use_keyed_state(anim_key, cx, |_, _| (px(0.), px(0.), 0u64));
217        let initialized = window.use_keyed_state(init_key, cx, |_, _| false);
218
219        // First frame: trigger re-render to capture bounds via on_prepaint
220        if !*initialized.read(cx) {
221            initialized.update(cx, |v, _| *v = true);
222        }
223
224        self.update_anim_params(selected_ix, bounds_rc, &prev_selected, &anim_params, cx);
225
226        let (to_left, to_width, epoch) = *anim_params.read(cx);
227        if to_width <= px(0.) {
228            return None;
229        }
230
231        // The springs hold the indicator's own position and velocity, so a tab
232        // switched again mid-slide is redirected from where the indicator
233        // actually is rather than restarted from the tab it left.
234        let indicator_key = format!("{}-tab-indicator", self.id);
235        let left = spring(
236            (indicator_key.clone(), "left"),
237            to_left,
238            INDICATOR_SPRING,
239            window,
240            cx,
241        );
242        let width = spring(
243            (indicator_key, "width"),
244            to_width,
245            INDICATOR_SPRING,
246            window,
247            cx,
248        );
249
250        let variant = self.variant;
251        let size = self.size;
252        let inner_height = variant.inner_height(size);
253        let inner_radius = variant.inner_radius(size, cx);
254
255        let indicator = div()
256            .absolute()
257            .top_0()
258            .bottom_0()
259            .left(left + inset)
260            .w(width)
261            .map(|el| match variant {
262                TabVariant::Segmented => el.flex().items_center().child(
263                    div()
264                        .w_full()
265                        .h(inner_height)
266                        .bg(cx.theme().tokens.background)
267                        .rounded(inner_radius)
268                        .shadow(raised_shadow()),
269                ),
270                TabVariant::Pill => el.flex().items_center().child(
271                    div()
272                        .size_full()
273                        .bg(cx.theme().tokens.primary)
274                        .rounded(cx.theme().radius_full()),
275                ),
276                TabVariant::Underline => el.child(
277                    div()
278                        .absolute()
279                        .left_0()
280                        .right_0()
281                        .bottom_0()
282                        .h(px(2.))
283                        .bg(cx.theme().tokens.primary),
284                ),
285                _ => el,
286            });
287
288        Some((indicator.into_any_element(), epoch))
289    }
290
291    /// Update animation parameters based on current and previous selection.
292    fn update_anim_params(
293        &self,
294        selected_ix: usize,
295        bounds_rc: &Option<Rc<RefCell<TabIndicatorBounds>>>,
296        prev_selected: &gpui::Entity<usize>,
297        anim_params: &gpui::Entity<(Pixels, Pixels, u64)>,
298        cx: &mut App,
299    ) {
300        let rc = match bounds_rc {
301            Some(rc) => rc,
302            None => return,
303        };
304
305        let prev_ix = *prev_selected.read(cx);
306        let bounds = rc.borrow();
307        let container = bounds.container;
308
309        if container.size.width == px(0.) {
310            if prev_ix != selected_ix {
311                prev_selected.update(cx, |v, _| *v = selected_ix);
312            }
313            return;
314        }
315
316        if prev_ix != selected_ix {
317            if let Some(to_b) = bounds.tabs.get(selected_ix) {
318                let left = to_b.origin.x - container.origin.x;
319                let width = to_b.size.width;
320                // Only a switch away from a tab that still exists restarts the
321                // tabs' own epoch-keyed transitions.
322                let epoch = anim_params.read(cx).2;
323                let epoch = match bounds.tabs.get(prev_ix) {
324                    Some(_) => epoch + 1,
325                    None => epoch,
326                };
327                anim_params.update(cx, |v, _| *v = (left, width, epoch));
328            }
329            drop(bounds);
330            prev_selected.update(cx, |v, _| *v = selected_ix);
331            return;
332        }
333
334        if let Some(to_b) = bounds.tabs.get(selected_ix) {
335            let left = to_b.origin.x - container.origin.x;
336            let width = to_b.size.width;
337            let (to_left, to_width, epoch) = *anim_params.read(cx);
338
339            if left != to_left || width != to_width {
340                anim_params.update(cx, |v, _| *v = (left, width, epoch));
341            }
342        }
343    }
344}
345
346impl Styled for TabBar {
347    fn style(&mut self) -> &mut StyleRefinement {
348        &mut self.style
349    }
350}
351
352impl Sizable for TabBar {
353    fn with_size(mut self, size: impl Into<Size>) -> Self {
354        self.size = size.into();
355        self
356    }
357}
358
359impl RenderOnce for TabBar {
360    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
361        let default_gap = match self.size {
362            Size::Small | Size::XSmall => px(8.),
363            Size::Large => px(16.),
364            _ => px(12.),
365        };
366        let (bg, paddings, gap): (Background, _, _) = match self.variant {
367            TabVariant::Tab => {
368                let padding = Edges::all(px(0.));
369                (cx.theme().tokens.tab_bar.into(), padding, px(0.))
370            }
371            TabVariant::Outline => {
372                let padding = Edges::all(px(0.));
373                (cx.theme().transparent.into(), padding, default_gap)
374            }
375            TabVariant::Pill => {
376                let padding = Edges::all(px(0.));
377                (cx.theme().transparent.into(), padding, px(4.))
378            }
379            TabVariant::Segmented => {
380                let padding_x = match self.size {
381                    Size::XSmall => px(2.),
382                    Size::Small => px(3.),
383                    _ => px(4.),
384                };
385                let padding = Edges {
386                    left: padding_x,
387                    right: padding_x,
388                    ..Default::default()
389                };
390
391                (cx.theme().tokens.tab_bar_segmented.into(), padding, px(2.))
392            }
393            TabVariant::Underline => {
394                // This gap is same as the tab inner_paddings
395                let gap = match self.size {
396                    Size::XSmall => px(10.),
397                    Size::Small => px(12.),
398                    Size::Large => px(20.),
399                    _ => px(16.),
400                };
401
402                (cx.theme().transparent.into(), Edges::all(px(0.)), gap)
403            }
404        };
405
406        let has_indicator = matches!(
407            self.variant,
408            TabVariant::Segmented | TabVariant::Pill | TabVariant::Underline
409        );
410        let num_tabs = self.children.len();
411
412        // Bounds tracking for tab indicator animation.
413        // Uses Rc<RefCell> to avoid triggering re-renders from prepaint writes.
414        let bounds_rc = if has_indicator && num_tabs > 0 {
415            let rc: Rc<RefCell<TabIndicatorBounds>> = window
416                .use_keyed_state(format!("{}-tab-bounds", self.id), cx, |_, _| {
417                    Rc::new(RefCell::new(TabIndicatorBounds::new(num_tabs)))
418                })
419                .read(cx)
420                .clone();
421            rc.borrow_mut().resize(num_tabs);
422            Some(rc)
423        } else {
424            None
425        };
426
427        let padding_x = paddings.left;
428        let indicator = self.render_indicator(&bounds_rc, padding_x, window, cx);
429        let indicator_epoch = indicator.as_ref().map(|(_, epoch)| *epoch).unwrap_or(0);
430        let indicator_element = indicator.map(|(el, _)| el);
431        let indicator_ready = indicator_element.is_some();
432
433        let has_suffix_or_menu = self.suffix.is_some() || self.menu;
434        let mut item_metas: Vec<(Option<SharedString>, Option<Icon>, bool)> = Vec::new();
435        let selected_index = self.selected_index;
436        let on_click = self.on_click.clone();
437        let tabs = self.base;
438        let mut rendered_tabs = Vec::with_capacity(self.children.len());
439        let max_width = self.max_width;
440
441        for (ix, child) in self.children.into_iter().enumerate() {
442            item_metas.push((child.label.clone(), child.icon.clone(), child.disabled));
443            let tab_bar_prefix = child.tab_bar_prefix.unwrap_or(true);
444            let mut tab = child
445                .ix(ix)
446                .tab_bar_prefix(tab_bar_prefix)
447                .max_width(max_width)
448                .with_variant(self.variant)
449                .with_size(self.size);
450            tab.indicator_active = has_indicator;
451            tab.indicator_ready = indicator_ready;
452            tab.indicator_epoch = indicator_epoch;
453            let tab = tab
454                .when_some(selected_index, |tab, selected_index| {
455                    tab.selected(selected_index == ix)
456                })
457                .when_some(self.on_click.clone(), move |tab, on_click| {
458                    tab.on_click(move |_, window, cx| on_click(&ix, window, cx))
459                });
460
461            rendered_tabs.push(if let Some(ref rc) = bounds_rc {
462                let rc = rc.clone();
463                div()
464                    .flex_shrink_0()
465                    .on_prepaint(move |bounds, _, _| {
466                        if let Some(slot) = rc.borrow_mut().tabs.get_mut(ix) {
467                            *slot = bounds;
468                        }
469                    })
470                    .child(tab)
471                    .into_any_element()
472            } else {
473                tab.into_any_element()
474            });
475        }
476
477        tabs.group("tab-bar")
478            .relative()
479            .flex()
480            .items_center()
481            .bg(bg)
482            .text_color(cx.theme().tab_foreground)
483            .when(
484                self.variant == TabVariant::Underline || self.variant == TabVariant::Tab,
485                |this| {
486                    this.child(
487                        div()
488                            .id("border-b")
489                            .absolute()
490                            .left_0()
491                            .bottom_0()
492                            .size_full()
493                            .border_b_1()
494                            .border_color(cx.theme().border),
495                    )
496                },
497            )
498            .rounded(self.variant.tab_bar_radius(self.size, cx))
499            .paddings(paddings)
500            .refine_style(&self.style)
501            .when_some(self.prefix, |this, prefix| this.child(prefix))
502            .child(
503                h_flex()
504                    .id("tabs")
505                    .flex_1()
506                    .mx(-padding_x)
507                    .px(padding_x)
508                    .overflow_x_hidden()
509                    .child(
510                        h_flex()
511                            .id("tabs-inner")
512                            .mx(-padding_x)
513                            .px(padding_x)
514                            .relative()
515                            .gap(gap)
516                            .overflow_x_scroll()
517                            .lock_scroll_axis()
518                            .when_some(self.scroll_handle, |this, scroll_handle| {
519                                this.track_scroll(&scroll_handle)
520                            })
521                            .when_some(bounds_rc.clone(), |this, rc| {
522                                this.on_prepaint(move |bounds, _, _| {
523                                    rc.borrow_mut().container = bounds;
524                                })
525                            })
526                            .when_some(indicator_element, |this, ind| this.child(ind))
527                            .children(rendered_tabs)
528                            .when(has_suffix_or_menu, |this| this.child(self.last_empty_space)),
529                    ),
530            )
531            .when(self.menu, |this| {
532                this.child(
533                    Button::new("more")
534                        .xsmall()
535                        .ghost()
536                        .dropdown_caret(true)
537                        .dropdown_menu(move |mut this, _, _| {
538                            this = this.scrollable(true);
539                            for (ix, (label, icon, disabled)) in item_metas.iter().enumerate() {
540                                let base = if let Some(label) = label.clone() {
541                                    PopupMenuItem::new(label)
542                                } else if let Some(icon) = icon.clone() {
543                                    PopupMenuItem::element(move |_, _| icon.clone())
544                                } else {
545                                    PopupMenuItem::new(t!("Dock.Unnamed"))
546                                };
547                                this = this.item(
548                                    base.checked(selected_index == Some(ix))
549                                        .disabled(*disabled)
550                                        .when_some(on_click.clone(), |this, on_click| {
551                                            this.on_click(move |_, window, cx| {
552                                                on_click(&ix, window, cx)
553                                            })
554                                        }),
555                                );
556                            }
557
558                            this
559                        })
560                        .anchor(Anchor::TopRight),
561                )
562            })
563            .when_some(self.suffix, |this, suffix| this.child(suffix))
564    }
565}
566
567#[cfg(test)]
568mod tests {
569    use std::{cell::Cell, rc::Rc};
570
571    use gpui::{Context, Modifiers, Render, TestAppContext};
572
573    use super::*;
574
575    struct Harness {
576        group_handler: bool,
577        disabled: bool,
578        child_clicks: Rc<Cell<usize>>,
579        group_clicks: Rc<Cell<usize>>,
580    }
581
582    impl Render for Harness {
583        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
584            let child_clicks = self.child_clicks.clone();
585            let group_clicks = self.group_clicks.clone();
586            TabBar::new("tabs")
587                .w(px(240.))
588                .child(
589                    Tab::new()
590                        .debug_selector(|| "first-tab".into())
591                        .disabled(self.disabled)
592                        .label("First")
593                        .on_click(move |_, _, _| child_clicks.set(child_clicks.get() + 1)),
594                )
595                .when(self.group_handler, |tabs| {
596                    tabs.on_click(move |ix, _, _| group_clicks.set(*ix + 1))
597                })
598        }
599    }
600
601    fn harness(
602        cx: &mut TestAppContext,
603        group_handler: bool,
604        disabled: bool,
605    ) -> (
606        &mut gpui::VisualTestContext,
607        Rc<Cell<usize>>,
608        Rc<Cell<usize>>,
609    ) {
610        cx.update(crate::theme::init);
611        let child_clicks = Rc::new(Cell::new(0));
612        let group_clicks = Rc::new(Cell::new(0));
613        let (_, cx) = cx.add_window_view({
614            let child_clicks = child_clicks.clone();
615            let group_clicks = group_clicks.clone();
616            move |_, _| Harness {
617                group_handler,
618                disabled,
619                child_clicks,
620                group_clicks,
621            }
622        });
623        cx.update(|window, cx| window.draw(cx).clear(cx));
624        (cx, child_clicks, group_clicks)
625    }
626
627    #[gpui::test]
628    fn group_callback_overrides_child_callback(cx: &mut TestAppContext) {
629        let (cx, child_clicks, group_clicks) = harness(cx, true, false);
630        let position = cx.debug_bounds("first-tab").unwrap().center();
631        cx.simulate_click(position, Modifiers::default());
632        assert_eq!(child_clicks.get(), 0);
633        assert_eq!(group_clicks.get(), 1);
634    }
635
636    #[gpui::test]
637    fn child_callback_is_preserved_without_group_callback(cx: &mut TestAppContext) {
638        let (cx, child_clicks, group_clicks) = harness(cx, false, false);
639        let position = cx.debug_bounds("first-tab").unwrap().center();
640        cx.simulate_click(position, Modifiers::default());
641        assert_eq!(child_clicks.get(), 1);
642        assert_eq!(group_clicks.get(), 0);
643    }
644
645    #[gpui::test]
646    fn disabled_tab_suppresses_child_and_group_callbacks(cx: &mut TestAppContext) {
647        let (cx, child_clicks, group_clicks) = harness(cx, true, true);
648        let position = cx.debug_bounds("first-tab").unwrap().center();
649        cx.simulate_click(position, Modifiers::default());
650        assert_eq!(child_clicks.get(), 0);
651        assert_eq!(group_clicks.get(), 0);
652    }
653
654    struct ContentHarness;
655
656    impl Render for ContentHarness {
657        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
658            TabBar::new("content-tabs").w(px(320.)).child(
659                Tab::new()
660                    .prefix(div().debug_selector(|| "tab-prefix".into()).child("P"))
661                    .child(div().debug_selector(|| "tab-child".into()).child("Content"))
662                    .suffix(div().debug_selector(|| "tab-suffix".into()).child("S")),
663            )
664        }
665    }
666
667    #[gpui::test]
668    fn prefix_content_and_suffix_keep_their_order(cx: &mut TestAppContext) {
669        cx.update(crate::theme::init);
670        let (_, cx) = cx.add_window_view(|_, _| ContentHarness);
671        cx.update(|window, cx| window.draw(cx).clear(cx));
672
673        let prefix = cx.debug_bounds("tab-prefix").unwrap();
674        let child = cx.debug_bounds("tab-child").unwrap();
675        let suffix = cx.debug_bounds("tab-suffix").unwrap();
676        assert!(prefix.origin.x < child.origin.x);
677        assert!(child.origin.x < suffix.origin.x);
678        assert!(prefix.size.width > px(0.));
679        assert!(child.size.width > px(0.));
680        assert!(suffix.size.width > px(0.));
681    }
682}