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