gpui-material-components 0.3.2

Material 3 Expressive desktop components for GPUI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
use std::{cell::Cell, rc::Rc};

use gpui::{
    AnyElement, App, AvailableSpace, BorderStyle, Bounds, ContentMask, Corners, ElementId, Hsla,
    InteractiveElement, IntoElement, ParentElement, Pixels, RenderOnce, Role, ScrollHandle,
    SharedString, StatefulInteractiveElement, Styled, Window, canvas, div, point, px, quad, size,
};
use gpui_material_foundation::{animate, current_material_theme};
use gpui_material_theme::{CornerShape, Direction, MotionKind, MotionSpec, MotionSpeed};

use super::items::{NavigationItems, Presentation};

/// Visual hierarchy variant for Material [`Tabs`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TabVariant {
    /// Top-level primary tabs with stacked icons and rounded active indicator.
    #[default]
    Primary,
    /// Sub-level secondary tabs with inline layout and full-width active indicator.
    Secondary,
}

/// Optional tab row pigments. Per-tab overrides take precedence over `content`.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct TabsColors {
    /// Background color override for the tab row container.
    pub container: Option<Hsla>,
    /// Default foreground color override for tab labels and icons.
    pub content: Option<Hsla>,
    /// Color override for the bottom divider line.
    pub divider: Option<Hsla>,
}

/// Width of the indicator relative to the selected tab.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum TabIndicatorWidth {
    /// Use the Material default for the active [`TabVariant`] (content-fitted for Primary, tab-width for Secondary).
    #[default]
    Default,
    /// Match the full width of the selected tab cell.
    Tab,
    /// Match the width of the selected tab's label/icon content.
    Content,
    /// Use an explicit fixed width in logical pixels.
    Fixed(Pixels),
}

/// Overrides for the indicator that tracks the selected tab.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct TabIndicatorStyle {
    /// Width sizing mode for the active indicator.
    pub width: TabIndicatorWidth,
    /// Height override for the indicator bar in logical pixels.
    pub height: Option<Pixels>,
    /// Fill color override for the indicator.
    pub color: Option<Hsla>,
    /// Corner shape override for the indicator.
    pub shape: Option<CornerShape>,
    /// Motion specification used when animating the indicator between tabs.
    pub motion: Option<MotionSpec>,
}

/// Geometry and tint supplied to a decorative custom indicator.
#[derive(Clone, Debug, PartialEq)]
pub struct TabIndicatorLayout {
    /// ID of the currently selected tab.
    pub selected: SharedString,
    /// Resolved bounds of the indicator within the tab strip.
    pub bounds: Bounds<Pixels>,
    /// Bounds of the selected tab cell within the tab strip.
    pub tab_bounds: Bounds<Pixels>,
    /// Measured width of the selected tab's content.
    pub content_width: Pixels,
    /// Resolved indicator tint color.
    pub color: Hsla,
    /// Active layout direction from the window theme.
    pub direction: Direction,
}

type Indicator = Box<dyn Fn(TabIndicatorLayout) -> AnyElement>;

pub(super) struct TabOptions {
    pub colors: TabsColors,
    pub scroll: Option<ScrollHandle>,
    pub edge_padding: Pixels,
    pub min_tab_width: Pixels,
    pub divider: Option<AnyElement>,
    pub indicator_style: Option<TabIndicatorStyle>,
    pub indicator_content: Option<Indicator>,
}

impl Default for TabOptions {
    fn default() -> Self {
        Self {
            colors: TabsColors::default(),
            scroll: None,
            edge_padding: px(52.),
            min_tab_width: px(90.),
            divider: None,
            indicator_style: None,
            indicator_content: None,
        }
    }
}

/// A fixed Material tab row by default. Enable scrolling for long tab lists.
#[derive(IntoElement)]
pub struct Tabs {
    items: NavigationItems,
    variant: TabVariant,
    scrollable: bool,
    options: TabOptions,
}

impl Tabs {
    /// Creates a fixed primary Material tab row from the given controlled [`NavigationItems`].
    pub fn new(items: NavigationItems) -> Self {
        Self {
            items,
            variant: TabVariant::Primary,
            scrollable: false,
            options: TabOptions::default(),
        }
    }

    /// Sets whether tabs use [`TabVariant::Primary`] (default) or [`TabVariant::Secondary`] styling.
    pub fn variant(mut self, variant: TabVariant) -> Self {
        self.variant = variant;
        self
    }

    /// Enables or disables horizontal scrolling for long tab lists (default `false`).
    pub fn scrollable(mut self, scrollable: bool) -> Self {
        self.scrollable = scrollable;
        self
    }

    /// Uses a caller-owned handle when horizontal scrolling is enabled.
    pub fn scroll_handle(mut self, handle: &ScrollHandle) -> Self {
        self.options.scroll = Some(handle.clone());
        self
    }

    /// Sets the logical start and end padding for scrolling tabs.
    pub fn edge_padding(mut self, padding: Pixels) -> Self {
        self.options.edge_padding = length(padding).unwrap_or(px(52.));
        self
    }

    /// Sets the minimum width of a scrolling tab.
    pub fn min_tab_width(mut self, width: Pixels) -> Self {
        self.options.min_tab_width = length(width).unwrap_or(px(90.));
        self
    }

    /// Overrides container, default content, and divider colors for the tab row.
    pub fn colors(mut self, colors: TabsColors) -> Self {
        self.options.colors = colors;
        self
    }

    /// Replaces the row's decorative bottom divider.
    pub fn divider(mut self, divider: impl IntoElement) -> Self {
        self.options.divider = Some(divider.into_any_element());
        self
    }

    /// Overrides the active indicator's width, height, color, shape, and motion.
    pub fn indicator_style(mut self, style: TabIndicatorStyle) -> Self {
        self.options.indicator_style = Some(style);
        self
    }

    /// Builds a decorative indicator constrained to the resolved indicator bounds.
    pub fn indicator_content<E: IntoElement>(
        mut self,
        content: impl Fn(TabIndicatorLayout) -> E + 'static,
    ) -> Self {
        self.options.indicator_content =
            Some(Box::new(move |layout| content(layout).into_any_element()));
        self
    }
}

impl RenderOnce for Tabs {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        self.items.render_row_with_tabs(
            Presentation::Tabs(self.variant, self.scrollable),
            Some(self.options),
            window,
            cx,
        )
    }
}

fn length(value: Pixels) -> Option<Pixels> {
    let value_f = f32::from(value);
    (value_f.is_finite() && value_f >= 0.).then_some(value)
}

#[derive(Default)]
pub(super) struct TabReveal {
    selection: Option<SharedString>,
    focus: Option<SharedString>,
    target: Option<SharedString>,
    order: Vec<SharedString>,
    geometry: Option<(Pixels, Pixels, Pixels, Pixels)>,
}

impl TabReveal {
    pub(super) fn choose(
        &mut self,
        selected: Option<&SharedString>,
        focused: Option<&SharedString>,
        items: &[super::items::NavigationItem],
        scroll: &ScrollHandle,
    ) -> Option<usize> {
        let order_unchanged = self.order.len() == items.len()
            && self
                .order
                .iter()
                .zip(items)
                .all(|(existing, item)| existing == &item.id);
        if !order_unchanged {
            self.order = items.iter().map(|item| item.id.clone()).collect();
        }
        let old_target = self.target.clone();
        if self.selection.as_ref() != selected {
            self.target = selected.or(focused).cloned();
        } else if let Some(focused) =
            focused.filter(|focused| self.focus.as_ref() != Some(*focused))
        {
            self.target = Some(focused.clone());
        }
        self.selection = selected.cloned();
        self.focus = focused.cloned();
        if self
            .target
            .as_ref()
            .is_none_or(|id| !self.order.contains(id))
        {
            self.target = selected
                .filter(|id| self.order.contains(id))
                .or(focused)
                .cloned();
        }
        let index = self
            .target
            .as_ref()
            .and_then(|id| self.order.iter().position(|item| item == id));
        if !order_unchanged || self.target != old_target || scroll.bounds().size.width == px(0.) {
            self.geometry = None;
            if let Some(index) = index {
                scroll.scroll_to_item(index);
            }
        }
        index
    }

    pub(super) fn observe_geometry(
        &mut self,
        index: usize,
        scroll: &ScrollHandle,
        window: &mut Window,
    ) {
        let Some(tab) = scroll.bounds_for_item(index) else {
            return;
        };
        let viewport = scroll.bounds();
        let width = viewport.size.width;
        let left = tab.left() - viewport.left();
        let geometry = (width, left, tab.size.width, scroll.max_offset().x);
        if self.geometry.replace(geometry) == Some(geometry) {
            return;
        }
        let visible_left = left + scroll.offset().x;
        if visible_left < px(0.) || visible_left + tab.size.width.min(width) > width {
            scroll.scroll_to_item(index);
            window.request_animation_frame();
        }
    }
}

#[derive(Default)]
pub(super) struct TabIndicatorTarget {
    pub tab_bounds: Cell<Option<Bounds<Pixels>>>,
    pub content_width: Cell<Pixels>,
}

pub(super) struct TabDecoration {
    pub row: ElementId,
    pub selected: SharedString,
    pub variant: TabVariant,
    pub direction: Direction,
    pub target: Rc<TabIndicatorTarget>,
    pub scroll: Option<ScrollHandle>,
    pub style: TabIndicatorStyle,
    pub content: Option<Indicator>,
    pub color: Hsla,
    pub has_default_divider: bool,
}

impl TabDecoration {
    pub(super) fn element(self) -> impl IntoElement {
        canvas(
            move |viewport, window, cx| {
                let tab = self.target.tab_bounds.get()?;
                let offset = self
                    .scroll
                    .as_ref()
                    .map_or(px(0.), |handle| handle.offset().x);
                let content_width = self.target.content_width.get().min(tab.size.width);
                let default_width = if self.variant == TabVariant::Primary {
                    (tab.size.width - px(4.)).max(px(0.)) * (2. / 3.)
                } else {
                    (tab.size.width - px(4.)).max(px(0.))
                };
                let width = match self.style.width {
                    TabIndicatorWidth::Default => default_width,
                    TabIndicatorWidth::Tab => tab.size.width,
                    TabIndicatorWidth::Content => content_width.max(px(24.)),
                    TabIndicatorWidth::Fixed(width) => length(width).unwrap_or(default_width),
                }
                .min(tab.size.width);
                let divider_height = if self.has_default_divider {
                    px(1.)
                } else {
                    px(0.)
                };
                let height = self
                    .style
                    .height
                    .and_then(length)
                    .unwrap_or(px(if self.variant == TabVariant::Primary {
                        3.
                    } else {
                        2.
                    }))
                    .min((viewport.size.height - divider_height).max(px(0.)));
                let motion = if cx.reduce_motion() {
                    MotionSpec::Instant
                } else {
                    self.style.motion.unwrap_or_else(|| {
                        current_material_theme(window, cx).motion.spec(
                            MotionKind::Spatial,
                            MotionSpeed::Fast,
                            false,
                        )
                    })
                };
                // Animate within the unscrolled strip so caller-driven scrolling
                // translates the indicator together with its tab immediately.
                let center = animate(
                    (self.row.clone(), "indicator-center"),
                    f32::from(tab.center().x - viewport.left()),
                    motion,
                    window,
                    cx,
                );
                let width = px(animate(
                    (self.row.clone(), "indicator-width"),
                    f32::from(width),
                    motion,
                    window,
                    cx,
                ))
                .clamp(px(0.), viewport.size.width.max(tab.size.width));
                if width == px(0.) || height == px(0.) {
                    return None;
                }
                let edge = viewport.bottom() - divider_height;
                let bounds = Bounds::new(
                    point(
                        viewport.left() + offset + px(center) - width / 2.,
                        edge - height,
                    ),
                    size(width, height),
                );
                let tab_bounds = Bounds::new(tab.origin + point(offset, px(0.)), tab.size);
                let layout = TabIndicatorLayout {
                    selected: self.selected,
                    bounds,
                    tab_bounds,
                    content_width,
                    color: self.color,
                    direction: self.direction,
                };
                let mask = ContentMask { bounds: viewport };
                let child = self.content.map(|content| {
                    let mut child = decorative_slot(
                        (self.row, "custom-indicator").into(),
                        content(layout.clone()),
                    )
                    .w(width)
                    .h(height)
                    .text_color(self.color)
                    .into_any_element();
                    window.with_content_mask(Some(mask), |window| {
                        child.prepaint_as_root(
                            bounds.origin,
                            bounds.size.map(AvailableSpace::Definite),
                            window,
                            cx,
                        );
                    });
                    child
                });
                let shape = self
                    .style
                    .shape
                    .unwrap_or(if self.variant == TabVariant::Primary {
                        CornerShape::Radii([3., 3., 0., 0.])
                    } else {
                        CornerShape::Radii([0.; 4])
                    });
                Some((layout, mask, child, shape))
            },
            |_, state, window, cx| {
                if let Some((layout, mask, child, shape)) = state {
                    window.with_content_mask(Some(mask), |window| {
                        if let Some(mut child) = child {
                            child.paint(window, cx);
                        } else {
                            let rect = layout.bounds;
                            let [top_left, top_right, bottom_right, bottom_left] = shape
                                .radii(
                                    rect.size.width.into(),
                                    rect.size.height.into(),
                                    layout.direction,
                                )
                                .map(px);
                            window.paint_quad(quad(
                                rect,
                                Corners {
                                    top_left,
                                    top_right,
                                    bottom_right,
                                    bottom_left,
                                },
                                layout.color,
                                px(0.),
                                gpui::transparent_black(),
                                BorderStyle::Solid,
                            ));
                        }
                    });
                }
            },
        )
        .absolute()
        .inset_0()
    }
}

pub(super) fn decorative_slot(
    id: ElementId,
    content: impl IntoElement,
) -> gpui::Stateful<gpui::Div> {
    div()
        .id(id)
        .role(Role::Group)
        .a11y_synthetic_children(|tree| tree.parent_node().set_hidden())
        .min_w_0()
        .max_w_full()
        .overflow_hidden()
        .child(content)
}