Skip to main content

gpui_material_components/navigation/
tabs.rs

1use std::{cell::Cell, rc::Rc};
2
3use gpui::{
4    AnyElement, App, AvailableSpace, BorderStyle, Bounds, ContentMask, Corners, ElementId, Hsla,
5    InteractiveElement, IntoElement, ParentElement, Pixels, RenderOnce, Role, ScrollHandle,
6    SharedString, StatefulInteractiveElement, Styled, Window, canvas, div, point, px, quad, size,
7};
8use gpui_material_foundation::{animate, window_material_theme};
9use gpui_material_theme::{CornerShape, Direction, MotionKind, MotionSpec, MotionSpeed};
10
11use super::items::{NavigationItems, Presentation};
12
13#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
14pub enum TabVariant {
15    #[default]
16    Primary,
17    Secondary,
18}
19
20/// Optional tab row pigments. Per-tab overrides take precedence over `content`.
21#[derive(Clone, Copy, Debug, Default, PartialEq)]
22pub struct TabsColors {
23    pub container: Option<Hsla>,
24    pub content: Option<Hsla>,
25    pub divider: Option<Hsla>,
26}
27
28/// Width of the indicator relative to the selected tab.
29#[derive(Clone, Copy, Debug, Default, PartialEq)]
30pub enum TabIndicatorWidth {
31    #[default]
32    Default,
33    Tab,
34    Content,
35    Fixed(Pixels),
36}
37
38/// Overrides for the indicator that tracks the selected tab.
39#[derive(Clone, Copy, Debug, Default, PartialEq)]
40pub struct TabIndicatorStyle {
41    pub width: TabIndicatorWidth,
42    pub height: Option<Pixels>,
43    pub color: Option<Hsla>,
44    pub shape: Option<CornerShape>,
45    pub motion: Option<MotionSpec>,
46}
47
48/// Geometry and tint supplied to a decorative custom indicator.
49#[derive(Clone, Debug, PartialEq)]
50pub struct TabIndicatorLayout {
51    pub selected: SharedString,
52    pub bounds: Bounds<Pixels>,
53    pub tab_bounds: Bounds<Pixels>,
54    pub content_width: Pixels,
55    pub color: Hsla,
56    pub direction: Direction,
57}
58
59type Indicator = Box<dyn Fn(TabIndicatorLayout) -> AnyElement>;
60
61pub(super) struct TabOptions {
62    pub colors: TabsColors,
63    pub scroll: Option<ScrollHandle>,
64    pub edge_padding: Pixels,
65    pub min_tab_width: Pixels,
66    pub divider: Option<AnyElement>,
67    pub indicator_style: Option<TabIndicatorStyle>,
68    pub indicator_content: Option<Indicator>,
69}
70
71impl Default for TabOptions {
72    fn default() -> Self {
73        Self {
74            colors: TabsColors::default(),
75            scroll: None,
76            edge_padding: px(52.),
77            min_tab_width: px(90.),
78            divider: None,
79            indicator_style: None,
80            indicator_content: None,
81        }
82    }
83}
84
85/// A fixed Material tab row by default. Enable scrolling for long tab lists.
86#[derive(IntoElement)]
87pub struct Tabs {
88    items: NavigationItems,
89    variant: TabVariant,
90    scrollable: bool,
91    options: TabOptions,
92}
93
94impl Tabs {
95    pub fn new(items: NavigationItems) -> Self {
96        Self {
97            items,
98            variant: TabVariant::Primary,
99            scrollable: false,
100            options: TabOptions::default(),
101        }
102    }
103
104    pub fn variant(mut self, variant: TabVariant) -> Self {
105        self.variant = variant;
106        self
107    }
108
109    pub fn scrollable(mut self, scrollable: bool) -> Self {
110        self.scrollable = scrollable;
111        self
112    }
113
114    /// Uses a caller-owned handle when horizontal scrolling is enabled.
115    pub fn scroll_handle(mut self, handle: &ScrollHandle) -> Self {
116        self.options.scroll = Some(handle.clone());
117        self
118    }
119
120    /// Sets the logical start and end padding for scrolling tabs.
121    pub fn edge_padding(mut self, padding: Pixels) -> Self {
122        self.options.edge_padding = length(padding).unwrap_or(px(52.));
123        self
124    }
125
126    /// Sets the minimum width of a scrolling tab.
127    pub fn min_tab_width(mut self, width: Pixels) -> Self {
128        self.options.min_tab_width = length(width).unwrap_or(px(90.));
129        self
130    }
131
132    pub fn colors(mut self, colors: TabsColors) -> Self {
133        self.options.colors = colors;
134        self
135    }
136
137    /// Replaces the row's decorative bottom divider.
138    pub fn divider(mut self, divider: impl IntoElement) -> Self {
139        self.options.divider = Some(divider.into_any_element());
140        self
141    }
142
143    pub fn indicator_style(mut self, style: TabIndicatorStyle) -> Self {
144        self.options.indicator_style = Some(style);
145        self
146    }
147
148    /// Builds a decorative indicator constrained to the resolved indicator bounds.
149    pub fn indicator_content<E: IntoElement>(
150        mut self,
151        content: impl Fn(TabIndicatorLayout) -> E + 'static,
152    ) -> Self {
153        self.options.indicator_content =
154            Some(Box::new(move |layout| content(layout).into_any_element()));
155        self
156    }
157}
158
159impl RenderOnce for Tabs {
160    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
161        self.items.render_row_with_tabs(
162            Presentation::Tabs(self.variant, self.scrollable),
163            Some(self.options),
164            window,
165            cx,
166        )
167    }
168}
169
170fn length(value: Pixels) -> Option<Pixels> {
171    let value_f = f32::from(value);
172    (value_f.is_finite() && value_f >= 0.).then_some(value)
173}
174
175#[derive(Default)]
176pub(super) struct TabReveal {
177    selection: Option<SharedString>,
178    focus: Option<SharedString>,
179    target: Option<SharedString>,
180    order: Vec<SharedString>,
181    geometry: Option<(Pixels, Pixels, Pixels, Pixels)>,
182}
183
184impl TabReveal {
185    pub(super) fn choose(
186        &mut self,
187        selected: Option<&SharedString>,
188        focused: Option<&SharedString>,
189        order: Vec<SharedString>,
190        scroll: &ScrollHandle,
191    ) -> Option<usize> {
192        let old_target = self.target.clone();
193        if self.selection.as_ref() != selected {
194            self.target = selected.or(focused).cloned();
195        } else if let Some(focused) =
196            focused.filter(|focused| self.focus.as_ref() != Some(*focused))
197        {
198            self.target = Some(focused.clone());
199        }
200        self.selection = selected.cloned();
201        self.focus = focused.cloned();
202        if self.target.as_ref().is_none_or(|id| !order.contains(id)) {
203            self.target = selected
204                .filter(|id| order.contains(id))
205                .or(focused)
206                .cloned();
207        }
208        let index = self
209            .target
210            .as_ref()
211            .and_then(|id| order.iter().position(|item| item == id));
212        if self.order != order || self.target != old_target || scroll.bounds().size.width == px(0.)
213        {
214            self.geometry = None;
215            if let Some(index) = index {
216                scroll.scroll_to_item(index);
217            }
218        }
219        self.order = order;
220        index
221    }
222
223    pub(super) fn observe_geometry(
224        &mut self,
225        index: usize,
226        scroll: &ScrollHandle,
227        window: &mut Window,
228    ) {
229        let Some(tab) = scroll.bounds_for_item(index) else {
230            return;
231        };
232        let viewport = scroll.bounds();
233        let width = viewport.size.width;
234        let left = tab.left() - viewport.left();
235        let geometry = (width, left, tab.size.width, scroll.max_offset().x);
236        if self.geometry.replace(geometry) == Some(geometry) {
237            return;
238        }
239        let visible_left = left + scroll.offset().x;
240        if visible_left < px(0.) || visible_left + tab.size.width.min(width) > width {
241            scroll.scroll_to_item(index);
242            window.request_animation_frame();
243        }
244    }
245}
246
247#[derive(Default)]
248pub(super) struct TabIndicatorTarget {
249    pub tab_bounds: Cell<Option<Bounds<Pixels>>>,
250    pub content_width: Cell<Pixels>,
251}
252
253pub(super) struct TabDecoration {
254    pub row: ElementId,
255    pub selected: SharedString,
256    pub variant: TabVariant,
257    pub direction: Direction,
258    pub target: Rc<TabIndicatorTarget>,
259    pub scroll: Option<ScrollHandle>,
260    pub style: TabIndicatorStyle,
261    pub content: Option<Indicator>,
262    pub color: Hsla,
263    pub has_default_divider: bool,
264}
265
266impl TabDecoration {
267    pub(super) fn element(self) -> impl IntoElement {
268        canvas(
269            move |viewport, window, cx| {
270                let tab = self.target.tab_bounds.get()?;
271                let offset = self
272                    .scroll
273                    .as_ref()
274                    .map_or(px(0.), |handle| handle.offset().x);
275                let content_width = self.target.content_width.get().min(tab.size.width);
276                let default_width = if self.variant == TabVariant::Primary {
277                    (tab.size.width - px(4.)).max(px(0.)) * (2. / 3.)
278                } else {
279                    (tab.size.width - px(4.)).max(px(0.))
280                };
281                let width = match self.style.width {
282                    TabIndicatorWidth::Default => default_width,
283                    TabIndicatorWidth::Tab => tab.size.width,
284                    TabIndicatorWidth::Content => content_width.max(px(24.)),
285                    TabIndicatorWidth::Fixed(width) => length(width).unwrap_or(default_width),
286                }
287                .min(tab.size.width);
288                let divider_height = if self.has_default_divider {
289                    px(1.)
290                } else {
291                    px(0.)
292                };
293                let height = self
294                    .style
295                    .height
296                    .and_then(length)
297                    .unwrap_or(px(if self.variant == TabVariant::Primary {
298                        3.
299                    } else {
300                        2.
301                    }))
302                    .min((viewport.size.height - divider_height).max(px(0.)));
303                let motion = if cx.reduce_motion() {
304                    MotionSpec::Instant
305                } else {
306                    self.style.motion.unwrap_or_else(|| {
307                        window_material_theme(window, cx).motion.spec(
308                            MotionKind::Spatial,
309                            MotionSpeed::Fast,
310                            false,
311                        )
312                    })
313                };
314                // Animate within the unscrolled strip so caller-driven scrolling
315                // translates the indicator together with its tab immediately.
316                let center = animate(
317                    (self.row.clone(), "indicator-center"),
318                    f32::from(tab.center().x - viewport.left()),
319                    motion,
320                    window,
321                    cx,
322                );
323                let width = px(animate(
324                    (self.row.clone(), "indicator-width"),
325                    f32::from(width),
326                    motion,
327                    window,
328                    cx,
329                ))
330                .clamp(px(0.), viewport.size.width.max(tab.size.width));
331                if width == px(0.) || height == px(0.) {
332                    return None;
333                }
334                let edge = viewport.bottom() - divider_height;
335                let bounds = Bounds::new(
336                    point(
337                        viewport.left() + offset + px(center) - width / 2.,
338                        edge - height,
339                    ),
340                    size(width, height),
341                );
342                let tab_bounds = Bounds::new(tab.origin + point(offset, px(0.)), tab.size);
343                let layout = TabIndicatorLayout {
344                    selected: self.selected,
345                    bounds,
346                    tab_bounds,
347                    content_width,
348                    color: self.color,
349                    direction: self.direction,
350                };
351                let mask = ContentMask { bounds: viewport };
352                let child = self.content.map(|content| {
353                    let mut child = decorative_slot(
354                        (self.row, "custom-indicator").into(),
355                        content(layout.clone()),
356                    )
357                    .w(width)
358                    .h(height)
359                    .text_color(self.color)
360                    .into_any_element();
361                    window.with_content_mask(Some(mask), |window| {
362                        child.prepaint_as_root(
363                            bounds.origin,
364                            bounds.size.map(AvailableSpace::Definite),
365                            window,
366                            cx,
367                        );
368                    });
369                    child
370                });
371                let shape = self
372                    .style
373                    .shape
374                    .unwrap_or(if self.variant == TabVariant::Primary {
375                        CornerShape::Radii([3., 3., 0., 0.])
376                    } else {
377                        CornerShape::Radii([0.; 4])
378                    });
379                Some((layout, mask, child, shape))
380            },
381            |_, state, window, cx| {
382                if let Some((layout, mask, child, shape)) = state {
383                    window.with_content_mask(Some(mask), |window| {
384                        if let Some(mut child) = child {
385                            child.paint(window, cx);
386                        } else {
387                            let rect = layout.bounds;
388                            let [top_left, top_right, bottom_right, bottom_left] = shape
389                                .radii(
390                                    rect.size.width.into(),
391                                    rect.size.height.into(),
392                                    layout.direction,
393                                )
394                                .map(px);
395                            window.paint_quad(quad(
396                                rect,
397                                Corners {
398                                    top_left,
399                                    top_right,
400                                    bottom_right,
401                                    bottom_left,
402                                },
403                                layout.color,
404                                px(0.),
405                                gpui::transparent_black(),
406                                BorderStyle::Solid,
407                            ));
408                        }
409                    });
410                }
411            },
412        )
413        .absolute()
414        .inset_0()
415    }
416}
417
418pub(super) fn decorative_slot(
419    id: ElementId,
420    content: impl IntoElement,
421) -> gpui::Stateful<gpui::Div> {
422    div()
423        .id(id)
424        .role(Role::Group)
425        .a11y_synthetic_children(|tree| tree.parent_node().set_hidden())
426        .min_w_0()
427        .max_w_full()
428        .overflow_hidden()
429        .child(content)
430}