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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
use gpui::{
    AnyElement, App, Div, ElementId, Entity, Hsla, InteractiveElement, IntoElement, ParentElement,
    Pixels, RenderOnce, Role, ScrollHandle, SharedString, StatefulInteractiveElement, Styled,
    TextAlign, Window, div, prelude::FluentBuilder, px,
};
use gpui_base::TestSupportExt;
use gpui_material_foundation::{animate, color, current_material_theme, text_style};
use gpui_material_theme::{
    ColorRole, Direction, MotionKind, MotionSpec, MotionSpeed, TypeRole, TypographyEmphasis,
};

mod actions;
mod scroll;

pub use actions::{AppBarColumn, AppBarItem, AppBarMenuState, AppBarRow};
use scroll::length;
pub use scroll::{AppBarScrollBehavior, AppBarScrollState};

/// Layout and typography variant for a Material top [`AppBar`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum AppBarVariant {
    /// Single-row bar with start-aligned title.
    #[default]
    Small,
    /// Single-row bar with centered title.
    Centered,
    /// Collapsible two-row bar with medium expanded headline typography.
    MediumFlexible,
    /// Collapsible two-row bar with large expanded display typography.
    LargeFlexible,
    /// Two-row bar supporting a custom second row below the expanded heading.
    TwoRows,
}

impl AppBarVariant {
    fn two_rows(self) -> bool {
        matches!(
            self,
            Self::MediumFlexible | Self::LargeFlexible | Self::TwoRows
        )
    }

    fn expansion(self, subtitle: bool) -> f32 {
        match (self, subtitle) {
            (Self::MediumFlexible | Self::TwoRows, false) => 48.,
            (Self::MediumFlexible | Self::TwoRows, true) => 72.,
            (Self::LargeFlexible, false) => 56.,
            (Self::LargeFlexible, true) => 88.,
            _ => 0.,
        }
    }

    fn expanded_roles(self) -> (TypeRole, TypeRole) {
        if self == Self::LargeFlexible {
            (TypeRole::DisplaySmall, TypeRole::TitleMedium)
        } else {
            (TypeRole::HeadlineMedium, TypeRole::LabelLarge)
        }
    }
}

/// Logical alignment for a title or subtitle.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum AppBarAlignment {
    /// Align to the logical start edge (left in LTR, right in RTL).
    #[default]
    Start,
    /// Center horizontally.
    Center,
    /// Align to the logical end edge (right in LTR, left in RTL).
    End,
}

impl AppBarAlignment {
    fn resolve(self, direction: Direction) -> TextAlign {
        match (self, direction) {
            (Self::Center, _) => TextAlign::Center,
            (Self::Start, Direction::Ltr) | (Self::End, Direction::Rtl) => TextAlign::Left,
            _ => TextAlign::Right,
        }
    }
}

/// Per-instance pigments. Missing fields use the window theme.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct AppBarColors {
    /// Container background color when not scrolled.
    pub container: Option<Hsla>,
    /// Container background color when content is scrolled beneath the bar.
    pub scrolled_container: Option<Hsla>,
    /// Foreground tint for the leading navigation icon slot.
    pub navigation: Option<Hsla>,
    /// Foreground color for the title text.
    pub title: Option<Hsla>,
    /// Foreground color for the subtitle text.
    pub subtitle: Option<Hsla>,
    /// Foreground tint for trailing action controls.
    pub actions: Option<Hsla>,
}

/// Logical insets within each app bar row.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct AppBarPadding {
    /// Top padding in logical pixels.
    pub top: Pixels,
    /// Logical end padding in logical pixels.
    pub end: Pixels,
    /// Bottom padding in logical pixels.
    pub bottom: Pixels,
    /// Logical start padding in logical pixels.
    pub start: Pixels,
}

impl AppBarPadding {
    fn apply(self, row: Div, direction: Direction) -> Div {
        let (left, right) = if direction == Direction::Rtl {
            (self.end, self.start)
        } else {
            (self.start, self.end)
        };
        let resolve = |value| px(length(value).unwrap_or(0.));
        row.pl(resolve(left))
            .pr(resolve(right))
            .pt(resolve(self.top))
            .pb(resolve(self.bottom))
    }
}

type HeadingContent = Box<dyn FnOnce(bool) -> AnyElement>;

#[derive(Default)]
struct Heading {
    text: Option<SharedString>,
    content: Option<HeadingContent>,
    alignment: Option<AppBarAlignment>,
    max_lines: Option<usize>,
}

impl Heading {
    fn has_content(&self) -> bool {
        self.text.is_some() || self.content.is_some()
    }

    fn additional_height(&self, role: TypeRole) -> f32 {
        if self.content.is_some() || self.text.is_none() {
            return 0.;
        }
        self.max_lines.unwrap_or(1).saturating_sub(1) as f32
            * role.style(TypographyEmphasis::Baseline).line_height
    }

    fn render(
        self,
        expanded: bool,
        role: TypeRole,
        style: HeadingStyle,
        window: &Window,
        cx: &App,
    ) -> Option<Div> {
        let alignment = self
            .alignment
            .unwrap_or(style.alignment)
            .resolve(style.direction);
        let label = text_style(
            div().min_w_0().text_align(alignment),
            role.style(TypographyEmphasis::Baseline),
            style.font_scale,
            window,
            cx,
        )
        .text_color(style.color);
        if let Some(build) = self.content {
            return Some(aligned_content(alignment).child(label.child(build(expanded))));
        }
        let lines = self.max_lines.unwrap_or(1);
        self.text.map(|text| {
            label
                .when_else(lines == 1, Styled::truncate, |label| {
                    label.line_clamp(lines)
                })
                .child(text)
        })
    }
}

fn aligned_content(alignment: TextAlign) -> Div {
    div()
        .flex()
        .min_w_0()
        .when(alignment == TextAlign::Center, Styled::justify_center)
        .when(alignment == TextAlign::Right, Styled::justify_end)
}

#[derive(Clone, Copy)]
struct HeadingStyle {
    direction: Direction,
    alignment: AppBarAlignment,
    font_scale: f32,
    color: Hsla,
}

/// Top app bar with caller-owned navigation, headings, actions, and optional search.
#[derive(IntoElement)]
pub struct AppBar {
    id: ElementId,
    title: Heading,
    subtitle: Heading,
    variant: AppBarVariant,
    navigation: Option<AnyElement>,
    actions: Option<AnyElement>,
    search: Option<AnyElement>,
    logo: Option<AnyElement>,
    second_row: Option<AnyElement>,
    colors: AppBarColors,
    padding: Option<AppBarPadding>,
    collapsed_height: Option<f32>,
    expanded_height: Option<f32>,
    scroll: Option<ScrollHandle>,
    scroll_state: Option<Entity<AppBarScrollState>>,
    scroll_behavior: Option<AppBarScrollBehavior>,
    scroll_enabled: bool,
    scroll_motion: Option<MotionSpec>,
    font_scale: f32,
}

impl AppBar {
    /// Creates a small top app bar with the given element ID and title.
    pub fn new(id: impl Into<ElementId>, title: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            title: Heading {
                text: Some(title.into()),
                ..Heading::default()
            },
            subtitle: Heading::default(),
            variant: AppBarVariant::Small,
            navigation: None,
            actions: None,
            search: None,
            logo: None,
            second_row: None,
            colors: AppBarColors::default(),
            padding: None,
            collapsed_height: None,
            expanded_height: None,
            scroll: None,
            scroll_state: None,
            scroll_behavior: None,
            scroll_enabled: true,
            scroll_motion: None,
            font_scale: 1.,
        }
    }

    /// Sets the app bar layout variant (default [`AppBarVariant::Small`]).
    pub fn variant(mut self, variant: AppBarVariant) -> Self {
        self.variant = variant;
        self
    }

    /// Sets the secondary subtitle text displayed beneath the title.
    pub fn subtitle(mut self, subtitle: impl Into<SharedString>) -> Self {
        self.subtitle.text = Some(subtitle.into());
        self.subtitle.content = None;
        self
    }

    /// Replaces the visual title while keeping the constructor's accessible name.
    pub fn title_content(self, content: impl IntoElement + 'static) -> Self {
        self.title_for_rows(move |_| content)
    }

    /// Replaces the subtitle with custom content.
    pub fn subtitle_content(self, content: impl IntoElement + 'static) -> Self {
        self.subtitle_for_rows(move |_| content)
    }

    /// Builds the title for the currently displayed row.
    pub fn title_for_rows<E: IntoElement>(
        mut self,
        build: impl FnOnce(bool) -> E + 'static,
    ) -> Self {
        self.title.content = Some(Box::new(move |expanded| build(expanded).into_any_element()));
        self
    }

    /// Builds the subtitle for the currently displayed row.
    pub fn subtitle_for_rows<E: IntoElement>(
        mut self,
        build: impl FnOnce(bool) -> E + 'static,
    ) -> Self {
        self.subtitle.content = Some(Box::new(move |expanded| build(expanded).into_any_element()));
        self
    }

    /// Overrides the logical horizontal alignment of the title.
    pub fn title_alignment(mut self, alignment: AppBarAlignment) -> Self {
        self.title.alignment = Some(alignment);
        self
    }

    /// Overrides the logical horizontal alignment of the subtitle.
    pub fn subtitle_alignment(mut self, alignment: AppBarAlignment) -> Self {
        self.subtitle.alignment = Some(alignment);
        self
    }

    /// Sets the maximum line count for plain title text (clamped to at least 1).
    pub fn title_max_lines(mut self, lines: usize) -> Self {
        self.title.max_lines = Some(lines.max(1));
        self
    }

    /// Sets the maximum line count for plain subtitle text (clamped to at least 1).
    pub fn subtitle_max_lines(mut self, lines: usize) -> Self {
        self.subtitle.max_lines = Some(lines.max(1));
        self
    }

    /// Places a leading navigation control (such as a back or menu button) at the start of the bar.
    pub fn navigation(mut self, element: impl IntoElement) -> Self {
        self.navigation = Some(element.into_any_element());
        self
    }

    /// Places trailing action controls (such as an [`AppBarRow`]) at the end of the bar.
    pub fn actions(mut self, element: impl IntoElement) -> Self {
        self.actions = Some(element.into_any_element());
        self
    }

    /// Supplies the search control that replaces the heading.
    pub fn search(mut self, element: impl IntoElement) -> Self {
        self.search = Some(element.into_any_element());
        self
    }

    /// Places a brand logo element alongside the title.
    pub fn logo(mut self, element: impl IntoElement) -> Self {
        self.logo = Some(element.into_any_element());
        self
    }

    /// Adds presentation content below the expanded heading in TwoRows.
    pub fn second_row(mut self, element: impl IntoElement) -> Self {
        self.second_row = Some(element.into_any_element());
        self
    }

    /// Overrides container, heading, navigation, and action colors.
    pub fn colors(mut self, colors: AppBarColors) -> Self {
        self.colors = colors;
        self
    }

    /// Sets explicit logical padding applied to each app bar row.
    pub fn content_padding(mut self, padding: AppBarPadding) -> Self {
        self.padding = Some(padding);
        self
    }

    /// Overrides the collapsed height of the top row in logical pixels (default 64 px).
    pub fn collapsed_height(mut self, height: Pixels) -> Self {
        self.collapsed_height = length(height).filter(|height| *height > 0.);
        self
    }

    /// Overrides the fully expanded height of a two-row bar in logical pixels.
    pub fn expanded_height(mut self, height: Pixels) -> Self {
        self.expanded_height = length(height).filter(|height| *height > 0.);
        self
    }

    /// Links a GPUI [`ScrollHandle`] to drive scroll-under color and collapse behavior.
    pub fn track_scroll(mut self, handle: &ScrollHandle) -> Self {
        self.scroll = Some(handle.clone());
        self
    }

    /// Binds a caller-owned [`AppBarScrollState`] entity for reading or controlling scroll collapse.
    pub fn scroll_state(mut self, state: &Entity<AppBarScrollState>) -> Self {
        self.scroll_state = Some(state.clone());
        self
    }

    /// Sets how scrolling affects the app bar's height (default [`AppBarScrollBehavior::Pinned`]).
    pub fn scroll_behavior(mut self, behavior: AppBarScrollBehavior) -> Self {
        self.scroll_behavior = Some(behavior);
        self
    }

    /// Enables or disables scroll-driven collapse updates (default `true`).
    pub fn scroll_enabled(mut self, enabled: bool) -> Self {
        self.scroll_enabled = enabled;
        self
    }

    /// Overrides motion when the caller asks the linked scroll state to settle.
    pub fn scroll_motion(mut self, motion: MotionSpec) -> Self {
        self.scroll_motion = Some(motion);
        self
    }

    /// Multiplies the heading typography scale by a positive finite factor (default `1.0`).
    pub fn font_scale(mut self, scale: f32) -> Self {
        self.font_scale = if scale.is_finite() && scale > 0. {
            scale
        } else {
            1.
        };
        self
    }

    fn scroll_position(&self, limit: f32, window: &mut Window, cx: &mut App) -> (f32, f32) {
        if self.scroll.is_none() && self.scroll_state.is_none() {
            return (0., 0.);
        }
        let state = self.scroll_state.clone().unwrap_or_else(|| {
            window.use_keyed_state((self.id.clone(), "app-bar-scroll"), cx, |_, _| {
                AppBarScrollState::new()
            })
        });
        let content_offset = self
            .scroll
            .as_ref()
            .map(|handle| length(-handle.offset().y).unwrap_or(0.));
        let position = state.update(cx, |state, _| {
            state.prepare(
                content_offset,
                limit,
                self.scroll_behavior,
                self.scroll_enabled,
            )
        });
        let motion = if position.settling && !cx.reduce_motion() {
            self.scroll_motion.unwrap_or_else(|| {
                current_material_theme(window, cx).motion.spec(
                    MotionKind::Spatial,
                    MotionSpeed::Default,
                    false,
                )
            })
        } else {
            MotionSpec::Instant
        };
        let fraction = animate(
            (self.id.clone(), "app-bar-height"),
            position.target,
            motion,
            window,
            cx,
        )
        .clamp(0., 1.);
        if state.update(cx, |state, _| state.display(position, fraction))
            && self.scroll_state.is_some()
        {
            let state = state.downgrade();
            window.defer(cx, move |_, cx| {
                let _ = state.update(cx, |_, cx| cx.notify());
            });
        }
        (fraction, position.overlap)
    }
}

impl RenderOnce for AppBar {
    fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let collapsed = self.collapsed_height.unwrap_or(64.);
        let two_rows = self.variant.two_rows();
        let (expanded_title_role, expanded_subtitle_role) = self.variant.expanded_roles();
        let text_scale = current_material_theme(window, cx).typography.text_scale();
        let default_expansion = if two_rows {
            (self.variant.expansion(self.subtitle.has_content())
                + self.title.additional_height(expanded_title_role)
                + self.subtitle.additional_height(expanded_subtitle_role))
                * (self.font_scale * text_scale).max(1.)
        } else {
            0.
        };
        let limit = self
            .expanded_height
            .map_or(default_expansion, |height| (height - collapsed).max(0.));
        let (fraction, overlap) = self.scroll_position(limit, window, cx);
        let remaining = limit * (1. - fraction);
        let theme = current_material_theme(window, cx);
        let direction = theme.layout.direction;
        let rtl = direction == Direction::Rtl;
        let centered = self.variant == AppBarVariant::Centered;
        let has_search = self.search.is_some();
        let expanded_row = two_rows && remaining > 0. && !has_search;
        let expanded_heading = expanded_row && remaining > limit / 2.;
        let default_alignment = if centered {
            AppBarAlignment::Center
        } else {
            AppBarAlignment::Start
        };
        let role = |role| color(theme.colors.color(role));
        let surface = self
            .colors
            .container
            .unwrap_or_else(|| role(ColorRole::Surface));
        let scrolled = self
            .colors
            .scrolled_container
            .unwrap_or_else(|| role(ColorRole::SurfaceContainer));
        let background = match overlap {
            0. => surface,
            1. => scrolled,
            _ => crate::motion::mix(surface, scrolled, overlap),
        };
        let title_color = self
            .colors
            .title
            .unwrap_or_else(|| role(ColorRole::OnSurface));
        let subtitle_color = self
            .colors
            .subtitle
            .unwrap_or_else(|| role(ColorRole::OnSurfaceVariant));
        let mut navigation = div()
            .flex()
            .items_center()
            .min_w_0()
            .gap(px(4.))
            .when(rtl, Styled::flex_row_reverse);
        if let Some(navigation_color) = self.colors.navigation {
            navigation = navigation.text_color(navigation_color);
        }
        let search_logo = has_search.then(|| self.logo.take()).flatten();
        navigation = navigation.children(self.navigation).children(search_logo);
        let mut actions = div()
            .flex()
            .justify_end()
            .min_w_0()
            .when(rtl, Styled::flex_row_reverse)
            .children(self.actions);
        if let Some(actions_color) = self.colors.actions {
            actions = actions.text_color(actions_color);
        }
        let label = self.title.text.clone().unwrap_or_default();
        let title_alignment = self
            .title
            .alignment
            .unwrap_or(default_alignment)
            .resolve(direction);
        let heading =
            if has_search {
                None
            } else if !two_rows && self.logo.is_some() {
                Some(
                    aligned_content(title_alignment)
                        .text_color(title_color)
                        .children(self.logo.take()),
                )
            } else {
                let heading_style = HeadingStyle {
                    direction,
                    alignment: default_alignment,
                    font_scale: self.font_scale,
                    color: title_color,
                };
                let (title_role, subtitle_role) = if expanded_heading {
                    (expanded_title_role, expanded_subtitle_role)
                } else {
                    (TypeRole::TitleLarge, TypeRole::LabelMedium)
                };
                Some(
                    div()
                        .flex()
                        .flex_col()
                        .min_w_0()
                        .children(expanded_heading.then(|| self.logo.take()).flatten().map(
                            |logo| {
                                aligned_content(title_alignment)
                                    .text_color(title_color)
                                    .child(logo)
                            },
                        ))
                        .children(self.title.render(
                            expanded_heading,
                            title_role,
                            heading_style,
                            window,
                            cx,
                        ))
                        .children(self.subtitle.render(
                            expanded_heading,
                            subtitle_role,
                            HeadingStyle {
                                color: subtitle_color,
                                ..heading_style
                            },
                            window,
                            cx,
                        )),
                )
            };
        let (top_heading, lower_heading) = if expanded_heading {
            (None, heading)
        } else {
            (heading, None)
        };
        let center_slots = centered && !has_search;
        let row = div()
            .flex()
            .items_center()
            .min_h(px(if two_rows || has_search {
                collapsed
            } else {
                collapsed + remaining
            }))
            .gap(px(4.))
            .when(rtl, Styled::flex_row_reverse)
            .child(navigation.when(center_slots, |lane| lane.flex_1()))
            .child(
                div()
                    .min_w_0()
                    .when_else(center_slots, |lane| lane.w_1_2(), |lane| lane.flex_1())
                    .children(self.search)
                    .children(top_heading),
            )
            .child(actions.when(center_slots, |lane| lane.flex_1()));
        let primary = self
            .padding
            .unwrap_or(AppBarPadding {
                start: px(4.),
                end: px(4.),
                ..Default::default()
            })
            .apply(row, direction);
        let lower = expanded_row.then(|| {
            let body = div()
                .h(px(remaining))
                .overflow_hidden()
                .flex()
                .flex_col()
                .justify_end()
                .children(lower_heading)
                .children(
                    self.second_row
                        .filter(|_| self.variant == AppBarVariant::TwoRows && expanded_heading),
                );
            self.padding
                .unwrap_or(AppBarPadding {
                    start: px(16.),
                    end: px(16.),
                    bottom: px(4.),
                    top: px(0.),
                })
                .apply(body, direction)
        });
        div()
            .id(self.id)
            .test_support()
            .role(Role::Toolbar)
            .aria_label(label)
            .w_full()
            .flex_none()
            .flex()
            .flex_col()
            .bg(background)
            .child(primary)
            .children(lower)
    }
}