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, text_style, window_material_theme};
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 window_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 default_expansion = if two_rows {
433 (self.variant.expansion(self.subtitle.has_content())
434 + self.title.additional_height(expanded_title_role)
435 + self.subtitle.additional_height(expanded_subtitle_role))
436 * self.font_scale.max(1.)
437 } else {
438 0.
439 };
440 let limit = self
441 .expanded_height
442 .map_or(default_expansion, |height| (height - collapsed).max(0.));
443 let (fraction, overlap) = self.scroll_position(limit, window, cx);
444 let remaining = limit * (1. - fraction);
445 let theme = window_material_theme(window, cx);
446 let direction = theme.layout.direction;
447 let rtl = direction == Direction::Rtl;
448 let centered = self.variant == AppBarVariant::Centered;
449 let has_search = self.search.is_some();
450 let expanded_row = two_rows && remaining > 0. && !has_search;
451 let expanded_heading = expanded_row && remaining > limit / 2.;
452 let default_alignment = if centered {
453 AppBarAlignment::Center
454 } else {
455 AppBarAlignment::Start
456 };
457 let role = |role| color(theme.colors.color(role));
458 let surface = self
459 .colors
460 .container
461 .unwrap_or_else(|| role(ColorRole::Surface));
462 let scrolled = self
463 .colors
464 .scrolled_container
465 .unwrap_or_else(|| role(ColorRole::SurfaceContainer));
466 let background = match overlap {
467 0. => surface,
468 1. => scrolled,
469 _ => crate::motion::mix(surface, scrolled, overlap),
470 };
471 let title_color = self
472 .colors
473 .title
474 .unwrap_or_else(|| role(ColorRole::OnSurface));
475 let subtitle_color = self
476 .colors
477 .subtitle
478 .unwrap_or_else(|| role(ColorRole::OnSurfaceVariant));
479 let mut navigation = div()
480 .flex()
481 .items_center()
482 .min_w_0()
483 .gap(px(4.))
484 .when(rtl, Styled::flex_row_reverse);
485 if let Some(navigation_color) = self.colors.navigation {
486 navigation = navigation.text_color(navigation_color);
487 }
488 let search_logo = has_search.then(|| self.logo.take()).flatten();
489 navigation = navigation.children(self.navigation).children(search_logo);
490 let mut actions = div()
491 .flex()
492 .justify_end()
493 .min_w_0()
494 .when(rtl, Styled::flex_row_reverse)
495 .children(self.actions);
496 if let Some(actions_color) = self.colors.actions {
497 actions = actions.text_color(actions_color);
498 }
499 let label = self.title.text.clone().unwrap_or_default();
500 let title_alignment = self
501 .title
502 .alignment
503 .unwrap_or(default_alignment)
504 .resolve(direction);
505 let heading =
506 if has_search {
507 None
508 } else if !two_rows && self.logo.is_some() {
509 Some(
510 aligned_content(title_alignment)
511 .text_color(title_color)
512 .children(self.logo.take()),
513 )
514 } else {
515 let heading_style = HeadingStyle {
516 direction,
517 alignment: default_alignment,
518 font_scale: self.font_scale,
519 color: title_color,
520 };
521 let (title_role, subtitle_role) = if expanded_heading {
522 (expanded_title_role, expanded_subtitle_role)
523 } else {
524 (TypeRole::TitleLarge, TypeRole::LabelMedium)
525 };
526 Some(
527 div()
528 .flex()
529 .flex_col()
530 .min_w_0()
531 .children(expanded_heading.then(|| self.logo.take()).flatten().map(
532 |logo| {
533 aligned_content(title_alignment)
534 .text_color(title_color)
535 .child(logo)
536 },
537 ))
538 .children(self.title.render(
539 expanded_heading,
540 title_role,
541 heading_style,
542 window,
543 cx,
544 ))
545 .children(self.subtitle.render(
546 expanded_heading,
547 subtitle_role,
548 HeadingStyle {
549 color: subtitle_color,
550 ..heading_style
551 },
552 window,
553 cx,
554 )),
555 )
556 };
557 let (top_heading, lower_heading) = if expanded_heading {
558 (None, heading)
559 } else {
560 (heading, None)
561 };
562 let center_slots = centered && !has_search;
563 let row = div()
564 .flex()
565 .items_center()
566 .min_h(px(if two_rows || has_search {
567 collapsed
568 } else {
569 collapsed + remaining
570 }))
571 .gap(px(4.))
572 .when(rtl, Styled::flex_row_reverse)
573 .child(navigation.when(center_slots, |lane| lane.flex_1()))
574 .child(
575 div()
576 .min_w_0()
577 .when_else(center_slots, |lane| lane.w_1_2(), |lane| lane.flex_1())
578 .children(self.search)
579 .children(top_heading),
580 )
581 .child(actions.when(center_slots, |lane| lane.flex_1()));
582 let primary = self
583 .padding
584 .unwrap_or(AppBarPadding {
585 start: px(4.),
586 end: px(4.),
587 ..Default::default()
588 })
589 .apply(row, direction);
590 let lower = expanded_row.then(|| {
591 let body = div()
592 .h(px(remaining))
593 .overflow_hidden()
594 .flex()
595 .flex_col()
596 .justify_end()
597 .children(lower_heading)
598 .children(
599 self.second_row
600 .filter(|_| self.variant == AppBarVariant::TwoRows && expanded_heading),
601 );
602 self.padding
603 .unwrap_or(AppBarPadding {
604 start: px(16.),
605 end: px(16.),
606 bottom: px(4.),
607 top: px(0.),
608 })
609 .apply(body, direction)
610 });
611 div()
612 .id(self.id)
613 .test_support()
614 .role(Role::Toolbar)
615 .aria_label(label)
616 .w_full()
617 .flex_none()
618 .flex()
619 .flex_col()
620 .bg(background)
621 .child(primary)
622 .children(lower)
623 }
624}