1use gpui::{
2 AnyElement, App, Div, ElementId, Entity, Hsla, InteractiveElement, IntoElement, ParentElement,
3 Pixels, RenderOnce, Role, ScrollHandle, SharedString, StatefulInteractiveElement, Styled,
4 TextAlign, Window, div, prelude::FluentBuilder, px,
5};
6use gpui_base::TestSupportExt;
7use gpui_material_foundation::{animate, color, current_material_theme, text_style};
8use gpui_material_theme::{
9 ColorRole, Direction, MotionKind, MotionSpec, MotionSpeed, TypeRole, TypographyEmphasis,
10};
11
12mod actions;
13mod scroll;
14
15pub use actions::{AppBarColumn, AppBarItem, AppBarMenuState, AppBarRow};
16use scroll::length;
17pub use scroll::{AppBarScrollBehavior, AppBarScrollState};
18
19#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
21pub enum AppBarVariant {
22 #[default]
24 Small,
25 Centered,
27 MediumFlexible,
29 LargeFlexible,
31 TwoRows,
33}
34
35impl AppBarVariant {
36 fn two_rows(self) -> bool {
37 matches!(
38 self,
39 Self::MediumFlexible | Self::LargeFlexible | Self::TwoRows
40 )
41 }
42
43 fn expansion(self, subtitle: bool) -> f32 {
44 match (self, subtitle) {
45 (Self::MediumFlexible | Self::TwoRows, false) => 48.,
46 (Self::MediumFlexible | Self::TwoRows, true) => 72.,
47 (Self::LargeFlexible, false) => 56.,
48 (Self::LargeFlexible, true) => 88.,
49 _ => 0.,
50 }
51 }
52
53 fn expanded_roles(self) -> (TypeRole, TypeRole) {
54 if self == Self::LargeFlexible {
55 (TypeRole::DisplaySmall, TypeRole::TitleMedium)
56 } else {
57 (TypeRole::HeadlineMedium, TypeRole::LabelLarge)
58 }
59 }
60}
61
62#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
64pub enum AppBarAlignment {
65 #[default]
67 Start,
68 Center,
70 End,
72}
73
74impl AppBarAlignment {
75 fn resolve(self, direction: Direction) -> TextAlign {
76 match (self, direction) {
77 (Self::Center, _) => TextAlign::Center,
78 (Self::Start, Direction::Ltr) | (Self::End, Direction::Rtl) => TextAlign::Left,
79 _ => TextAlign::Right,
80 }
81 }
82}
83
84#[derive(Clone, Copy, Debug, Default, PartialEq)]
86pub struct AppBarColors {
87 pub container: Option<Hsla>,
89 pub scrolled_container: Option<Hsla>,
91 pub navigation: Option<Hsla>,
93 pub title: Option<Hsla>,
95 pub subtitle: Option<Hsla>,
97 pub actions: Option<Hsla>,
99}
100
101#[derive(Clone, Copy, Debug, Default, PartialEq)]
103pub struct AppBarPadding {
104 pub top: Pixels,
106 pub end: Pixels,
108 pub bottom: Pixels,
110 pub start: Pixels,
112}
113
114impl AppBarPadding {
115 fn apply(self, row: Div, direction: Direction) -> Div {
116 let (left, right) = if direction == Direction::Rtl {
117 (self.end, self.start)
118 } else {
119 (self.start, self.end)
120 };
121 let resolve = |value| px(length(value).unwrap_or(0.));
122 row.pl(resolve(left))
123 .pr(resolve(right))
124 .pt(resolve(self.top))
125 .pb(resolve(self.bottom))
126 }
127}
128
129type HeadingContent = Box<dyn FnOnce(bool) -> AnyElement>;
130
131#[derive(Default)]
132struct Heading {
133 text: Option<SharedString>,
134 content: Option<HeadingContent>,
135 alignment: Option<AppBarAlignment>,
136 max_lines: Option<usize>,
137}
138
139impl Heading {
140 fn has_content(&self) -> bool {
141 self.text.is_some() || self.content.is_some()
142 }
143
144 fn additional_height(&self, role: TypeRole) -> f32 {
145 if self.content.is_some() || self.text.is_none() {
146 return 0.;
147 }
148 self.max_lines.unwrap_or(1).saturating_sub(1) as f32
149 * role.style(TypographyEmphasis::Baseline).line_height
150 }
151
152 fn render(
153 self,
154 expanded: bool,
155 role: TypeRole,
156 style: HeadingStyle,
157 window: &Window,
158 cx: &App,
159 ) -> Option<Div> {
160 let alignment = self
161 .alignment
162 .unwrap_or(style.alignment)
163 .resolve(style.direction);
164 let label = text_style(
165 div().min_w_0().text_align(alignment),
166 role.style(TypographyEmphasis::Baseline),
167 style.font_scale,
168 window,
169 cx,
170 )
171 .text_color(style.color);
172 if let Some(build) = self.content {
173 return Some(aligned_content(alignment).child(label.child(build(expanded))));
174 }
175 let lines = self.max_lines.unwrap_or(1);
176 self.text.map(|text| {
177 label
178 .when_else(lines == 1, Styled::truncate, |label| {
179 label.line_clamp(lines)
180 })
181 .child(text)
182 })
183 }
184}
185
186fn aligned_content(alignment: TextAlign) -> Div {
187 div()
188 .flex()
189 .min_w_0()
190 .when(alignment == TextAlign::Center, Styled::justify_center)
191 .when(alignment == TextAlign::Right, Styled::justify_end)
192}
193
194#[derive(Clone, Copy)]
195struct HeadingStyle {
196 direction: Direction,
197 alignment: AppBarAlignment,
198 font_scale: f32,
199 color: Hsla,
200}
201
202#[derive(IntoElement)]
204pub struct AppBar {
205 id: ElementId,
206 title: Heading,
207 subtitle: Heading,
208 variant: AppBarVariant,
209 navigation: Option<AnyElement>,
210 actions: Option<AnyElement>,
211 search: Option<AnyElement>,
212 logo: Option<AnyElement>,
213 second_row: Option<AnyElement>,
214 colors: AppBarColors,
215 padding: Option<AppBarPadding>,
216 collapsed_height: Option<f32>,
217 expanded_height: Option<f32>,
218 scroll: Option<ScrollHandle>,
219 scroll_state: Option<Entity<AppBarScrollState>>,
220 scroll_behavior: Option<AppBarScrollBehavior>,
221 scroll_enabled: bool,
222 scroll_motion: Option<MotionSpec>,
223 font_scale: f32,
224}
225
226impl AppBar {
227 pub fn new(id: impl Into<ElementId>, title: impl Into<SharedString>) -> Self {
229 Self {
230 id: id.into(),
231 title: Heading {
232 text: Some(title.into()),
233 ..Heading::default()
234 },
235 subtitle: Heading::default(),
236 variant: AppBarVariant::Small,
237 navigation: None,
238 actions: None,
239 search: None,
240 logo: None,
241 second_row: None,
242 colors: AppBarColors::default(),
243 padding: None,
244 collapsed_height: None,
245 expanded_height: None,
246 scroll: None,
247 scroll_state: None,
248 scroll_behavior: None,
249 scroll_enabled: true,
250 scroll_motion: None,
251 font_scale: 1.,
252 }
253 }
254
255 pub fn variant(mut self, variant: AppBarVariant) -> Self {
257 self.variant = variant;
258 self
259 }
260
261 pub fn subtitle(mut self, subtitle: impl Into<SharedString>) -> Self {
263 self.subtitle.text = Some(subtitle.into());
264 self.subtitle.content = None;
265 self
266 }
267
268 pub fn title_content(self, content: impl IntoElement + 'static) -> Self {
270 self.title_for_rows(move |_| content)
271 }
272
273 pub fn subtitle_content(self, content: impl IntoElement + 'static) -> Self {
275 self.subtitle_for_rows(move |_| content)
276 }
277
278 pub fn title_for_rows<E: IntoElement>(
280 mut self,
281 build: impl FnOnce(bool) -> E + 'static,
282 ) -> Self {
283 self.title.content = Some(Box::new(move |expanded| build(expanded).into_any_element()));
284 self
285 }
286
287 pub fn subtitle_for_rows<E: IntoElement>(
289 mut self,
290 build: impl FnOnce(bool) -> E + 'static,
291 ) -> Self {
292 self.subtitle.content = Some(Box::new(move |expanded| build(expanded).into_any_element()));
293 self
294 }
295
296 pub fn title_alignment(mut self, alignment: AppBarAlignment) -> Self {
298 self.title.alignment = Some(alignment);
299 self
300 }
301
302 pub fn subtitle_alignment(mut self, alignment: AppBarAlignment) -> Self {
304 self.subtitle.alignment = Some(alignment);
305 self
306 }
307
308 pub fn title_max_lines(mut self, lines: usize) -> Self {
310 self.title.max_lines = Some(lines.max(1));
311 self
312 }
313
314 pub fn subtitle_max_lines(mut self, lines: usize) -> Self {
316 self.subtitle.max_lines = Some(lines.max(1));
317 self
318 }
319
320 pub fn navigation(mut self, element: impl IntoElement) -> Self {
322 self.navigation = Some(element.into_any_element());
323 self
324 }
325
326 pub fn actions(mut self, element: impl IntoElement) -> Self {
328 self.actions = Some(element.into_any_element());
329 self
330 }
331
332 pub fn search(mut self, element: impl IntoElement) -> Self {
334 self.search = Some(element.into_any_element());
335 self
336 }
337
338 pub fn logo(mut self, element: impl IntoElement) -> Self {
340 self.logo = Some(element.into_any_element());
341 self
342 }
343
344 pub fn second_row(mut self, element: impl IntoElement) -> Self {
346 self.second_row = Some(element.into_any_element());
347 self
348 }
349
350 pub fn colors(mut self, colors: AppBarColors) -> Self {
352 self.colors = colors;
353 self
354 }
355
356 pub fn content_padding(mut self, padding: AppBarPadding) -> Self {
358 self.padding = Some(padding);
359 self
360 }
361
362 pub fn collapsed_height(mut self, height: Pixels) -> Self {
364 self.collapsed_height = length(height).filter(|height| *height > 0.);
365 self
366 }
367
368 pub fn expanded_height(mut self, height: Pixels) -> Self {
370 self.expanded_height = length(height).filter(|height| *height > 0.);
371 self
372 }
373
374 pub fn track_scroll(mut self, handle: &ScrollHandle) -> Self {
376 self.scroll = Some(handle.clone());
377 self
378 }
379
380 pub fn scroll_state(mut self, state: &Entity<AppBarScrollState>) -> Self {
382 self.scroll_state = Some(state.clone());
383 self
384 }
385
386 pub fn scroll_behavior(mut self, behavior: AppBarScrollBehavior) -> Self {
388 self.scroll_behavior = Some(behavior);
389 self
390 }
391
392 pub fn scroll_enabled(mut self, enabled: bool) -> Self {
394 self.scroll_enabled = enabled;
395 self
396 }
397
398 pub fn scroll_motion(mut self, motion: MotionSpec) -> Self {
400 self.scroll_motion = Some(motion);
401 self
402 }
403
404 pub fn font_scale(mut self, scale: f32) -> Self {
406 self.font_scale = if scale.is_finite() && scale > 0. {
407 scale
408 } else {
409 1.
410 };
411 self
412 }
413
414 fn scroll_position(&self, limit: f32, window: &mut Window, cx: &mut App) -> (f32, f32) {
415 if self.scroll.is_none() && self.scroll_state.is_none() {
416 return (0., 0.);
417 }
418 let state = self.scroll_state.clone().unwrap_or_else(|| {
419 window.use_keyed_state((self.id.clone(), "app-bar-scroll"), cx, |_, _| {
420 AppBarScrollState::new()
421 })
422 });
423 let content_offset = self
424 .scroll
425 .as_ref()
426 .map(|handle| length(-handle.offset().y).unwrap_or(0.));
427 let position = state.update(cx, |state, _| {
428 state.prepare(
429 content_offset,
430 limit,
431 self.scroll_behavior,
432 self.scroll_enabled,
433 )
434 });
435 let motion = if position.settling && !cx.reduce_motion() {
436 self.scroll_motion.unwrap_or_else(|| {
437 current_material_theme(window, cx).motion.spec(
438 MotionKind::Spatial,
439 MotionSpeed::Default,
440 false,
441 )
442 })
443 } else {
444 MotionSpec::Instant
445 };
446 let fraction = animate(
447 (self.id.clone(), "app-bar-height"),
448 position.target,
449 motion,
450 window,
451 cx,
452 )
453 .clamp(0., 1.);
454 if state.update(cx, |state, _| state.display(position, fraction))
455 && self.scroll_state.is_some()
456 {
457 let state = state.downgrade();
458 window.defer(cx, move |_, cx| {
459 let _ = state.update(cx, |_, cx| cx.notify());
460 });
461 }
462 (fraction, position.overlap)
463 }
464}
465
466impl RenderOnce for AppBar {
467 fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
468 let collapsed = self.collapsed_height.unwrap_or(64.);
469 let two_rows = self.variant.two_rows();
470 let (expanded_title_role, expanded_subtitle_role) = self.variant.expanded_roles();
471 let text_scale = current_material_theme(window, cx).typography.text_scale();
472 let default_expansion = if two_rows {
473 (self.variant.expansion(self.subtitle.has_content())
474 + self.title.additional_height(expanded_title_role)
475 + self.subtitle.additional_height(expanded_subtitle_role))
476 * (self.font_scale * text_scale).max(1.)
477 } else {
478 0.
479 };
480 let limit = self
481 .expanded_height
482 .map_or(default_expansion, |height| (height - collapsed).max(0.));
483 let (fraction, overlap) = self.scroll_position(limit, window, cx);
484 let remaining = limit * (1. - fraction);
485 let theme = current_material_theme(window, cx);
486 let direction = theme.layout.direction;
487 let rtl = direction == Direction::Rtl;
488 let centered = self.variant == AppBarVariant::Centered;
489 let has_search = self.search.is_some();
490 let expanded_row = two_rows && remaining > 0. && !has_search;
491 let expanded_heading = expanded_row && remaining > limit / 2.;
492 let default_alignment = if centered {
493 AppBarAlignment::Center
494 } else {
495 AppBarAlignment::Start
496 };
497 let role = |role| color(theme.colors.color(role));
498 let surface = self
499 .colors
500 .container
501 .unwrap_or_else(|| role(ColorRole::Surface));
502 let scrolled = self
503 .colors
504 .scrolled_container
505 .unwrap_or_else(|| role(ColorRole::SurfaceContainer));
506 let background = match overlap {
507 0. => surface,
508 1. => scrolled,
509 _ => crate::motion::mix(surface, scrolled, overlap),
510 };
511 let title_color = self
512 .colors
513 .title
514 .unwrap_or_else(|| role(ColorRole::OnSurface));
515 let subtitle_color = self
516 .colors
517 .subtitle
518 .unwrap_or_else(|| role(ColorRole::OnSurfaceVariant));
519 let mut navigation = div()
520 .flex()
521 .items_center()
522 .min_w_0()
523 .gap(px(4.))
524 .when(rtl, Styled::flex_row_reverse);
525 if let Some(navigation_color) = self.colors.navigation {
526 navigation = navigation.text_color(navigation_color);
527 }
528 let search_logo = has_search.then(|| self.logo.take()).flatten();
529 navigation = navigation.children(self.navigation).children(search_logo);
530 let mut actions = div()
531 .flex()
532 .justify_end()
533 .min_w_0()
534 .when(rtl, Styled::flex_row_reverse)
535 .children(self.actions);
536 if let Some(actions_color) = self.colors.actions {
537 actions = actions.text_color(actions_color);
538 }
539 let label = self.title.text.clone().unwrap_or_default();
540 let title_alignment = self
541 .title
542 .alignment
543 .unwrap_or(default_alignment)
544 .resolve(direction);
545 let heading =
546 if has_search {
547 None
548 } else if !two_rows && self.logo.is_some() {
549 Some(
550 aligned_content(title_alignment)
551 .text_color(title_color)
552 .children(self.logo.take()),
553 )
554 } else {
555 let heading_style = HeadingStyle {
556 direction,
557 alignment: default_alignment,
558 font_scale: self.font_scale,
559 color: title_color,
560 };
561 let (title_role, subtitle_role) = if expanded_heading {
562 (expanded_title_role, expanded_subtitle_role)
563 } else {
564 (TypeRole::TitleLarge, TypeRole::LabelMedium)
565 };
566 Some(
567 div()
568 .flex()
569 .flex_col()
570 .min_w_0()
571 .children(expanded_heading.then(|| self.logo.take()).flatten().map(
572 |logo| {
573 aligned_content(title_alignment)
574 .text_color(title_color)
575 .child(logo)
576 },
577 ))
578 .children(self.title.render(
579 expanded_heading,
580 title_role,
581 heading_style,
582 window,
583 cx,
584 ))
585 .children(self.subtitle.render(
586 expanded_heading,
587 subtitle_role,
588 HeadingStyle {
589 color: subtitle_color,
590 ..heading_style
591 },
592 window,
593 cx,
594 )),
595 )
596 };
597 let (top_heading, lower_heading) = if expanded_heading {
598 (None, heading)
599 } else {
600 (heading, None)
601 };
602 let center_slots = centered && !has_search;
603 let row = div()
604 .flex()
605 .items_center()
606 .min_h(px(if two_rows || has_search {
607 collapsed
608 } else {
609 collapsed + remaining
610 }))
611 .gap(px(4.))
612 .when(rtl, Styled::flex_row_reverse)
613 .child(navigation.when(center_slots, |lane| lane.flex_1()))
614 .child(
615 div()
616 .min_w_0()
617 .when_else(center_slots, |lane| lane.w_1_2(), |lane| lane.flex_1())
618 .children(self.search)
619 .children(top_heading),
620 )
621 .child(actions.when(center_slots, |lane| lane.flex_1()));
622 let primary = self
623 .padding
624 .unwrap_or(AppBarPadding {
625 start: px(4.),
626 end: px(4.),
627 ..Default::default()
628 })
629 .apply(row, direction);
630 let lower = expanded_row.then(|| {
631 let body = div()
632 .h(px(remaining))
633 .overflow_hidden()
634 .flex()
635 .flex_col()
636 .justify_end()
637 .children(lower_heading)
638 .children(
639 self.second_row
640 .filter(|_| self.variant == AppBarVariant::TwoRows && expanded_heading),
641 );
642 self.padding
643 .unwrap_or(AppBarPadding {
644 start: px(16.),
645 end: px(16.),
646 bottom: px(4.),
647 top: px(0.),
648 })
649 .apply(body, direction)
650 });
651 div()
652 .id(self.id)
653 .test_support()
654 .role(Role::Toolbar)
655 .aria_label(label)
656 .w_full()
657 .flex_none()
658 .flex()
659 .flex_col()
660 .bg(background)
661 .child(primary)
662 .children(lower)
663 }
664}