1use std::rc::Rc;
2
3use gpui::prelude::FluentBuilder;
4use gpui::{
5 AnyElement, App, AvailableSpace, ElementId, Empty, Entity, FocusHandle, IntoElement,
6 ParentElement, Pixels, Point, RenderOnce, SharedString, Styled, Window, anchored, canvas,
7 deferred, div, point, px, size,
8};
9use gpui_material_foundation::{
10 InteractionSource, ThemeScope, animate, current_material_theme, logical_anchor,
11};
12use gpui_material_theme::{
13 ColorRole, CornerRole, CornerShape, Direction, Elevation, MotionKind, MotionSpec, MotionSpeed,
14 TypeRole, TypographyEmphasis,
15};
16
17use crate::action::{
18 Action, ActionControl, ActionLayout, ActionStyle, Activate, DisabledStyle, icon_slot,
19};
20use crate::button_style::{ButtonColors, ButtonElevations, ButtonStyle};
21use crate::motion::OverlayMotion;
22
23#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
25pub enum FabSize {
26 #[default]
27 Small,
28 Medium,
29 Large,
30}
31
32impl FabSize {
33 fn metrics(self) -> (f32, f32, CornerRole, f32, f32, TypeRole) {
34 match self {
36 Self::Small => (56., 24., CornerRole::Large, 16., 8., TypeRole::TitleMedium),
37 Self::Medium => (
38 80.,
39 28.,
40 CornerRole::LargeIncreased,
41 26.,
42 12.,
43 TypeRole::TitleLarge,
44 ),
45 Self::Large => (
46 96.,
47 32.,
48 CornerRole::ExtraLarge,
49 28.,
50 16.,
51 TypeRole::HeadlineSmall,
52 ),
53 }
54 }
55}
56
57#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
58pub enum FabColor {
59 #[default]
60 Primary,
61 Secondary,
62 Tertiary,
63 PrimaryStrong,
64 SecondaryStrong,
65 TertiaryStrong,
66}
67
68#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
70pub enum FabAlignment {
71 TopStart,
72 TopCenter,
73 TopEnd,
74 CenterStart,
75 #[default]
76 Center,
77 CenterEnd,
78 BottomStart,
79 BottomCenter,
80 BottomEnd,
81}
82
83impl FabAlignment {
84 fn pivot(self, direction: Direction) -> Point<f32> {
85 use FabAlignment::*;
86 let x = match self {
87 TopStart | CenterStart | BottomStart => 0.,
88 TopCenter | Center | BottomCenter => 0.5,
89 TopEnd | CenterEnd | BottomEnd => 1.,
90 };
91 let y = match self {
92 TopStart | TopCenter | TopEnd => 0.,
93 CenterStart | Center | CenterEnd => 0.5,
94 BottomStart | BottomCenter | BottomEnd => 1.,
95 };
96 point(
97 if direction == Direction::Rtl {
98 1. - x
99 } else {
100 x
101 },
102 y,
103 )
104 }
105}
106
107#[derive(Clone, Copy, Debug, PartialEq)]
109pub struct FabVisibilityAnimation {
110 pub alignment: FabAlignment,
111 pub target_scale: f32,
114 pub scale_motion: Option<MotionSpec>,
116 pub alpha_motion: Option<MotionSpec>,
118}
119
120impl Default for FabVisibilityAnimation {
121 fn default() -> Self {
122 Self {
123 alignment: FabAlignment::Center,
124 target_scale: 0.2,
125 scale_motion: None,
126 alpha_motion: None,
127 }
128 }
129}
130
131impl FabVisibilityAnimation {
132 #[doc(hidden)]
134 pub fn frame(
135 self,
136 id: &ElementId,
137 visible: bool,
138 extent: f32,
139 window: &mut Window,
140 cx: &mut App,
141 ) -> (f32, f32, Point<f32>) {
142 let sample = self.sample(id, visible, extent, window, cx);
143 let direction = current_material_theme(window, cx).layout.direction;
144 (sample.scale, sample.alpha, self.alignment.pivot(direction))
145 }
146
147 fn sample(
148 self,
149 id: &ElementId,
150 visible: bool,
151 extent: f32,
152 window: &mut Window,
153 cx: &mut App,
154 ) -> OverlayMotion {
155 let scheme = current_material_theme(window, cx).motion;
156 let reduced = cx.reduce_motion();
157 let mut progress = |channel, kind, spec: Option<MotionSpec>| {
158 let spec = if reduced {
159 MotionSpec::Instant
160 } else {
161 spec.unwrap_or_else(|| scheme.spec(kind, MotionSpeed::Fast, false))
162 };
163 animate((id.clone(), channel), f32::from(visible), spec, window, cx)
164 };
165 let spatial = progress(
166 "fab-visibility-scale",
167 MotionKind::Spatial,
168 self.scale_motion,
169 );
170 let alpha = progress(
171 "fab-visibility-alpha",
172 MotionKind::Effects,
173 self.alpha_motion,
174 );
175 let target = if self.target_scale >= 0. && (self.target_scale * extent).is_finite() {
176 self.target_scale
177 } else {
178 Self::default().target_scale
179 };
180 let scale = ((1. - spatial) * target + spatial).max(0.);
181 OverlayMotion {
182 scale: if (scale * extent).is_finite() {
183 scale
184 } else {
185 1.
186 },
187 alpha: alpha.clamp(0., 1.),
188 }
189 }
190}
191
192struct FabContent {
193 id: ElementId,
194 name: SharedString,
195 size: FabSize,
196 color: FabColor,
197 disabled: bool,
198 focus: Option<FocusHandle>,
199 on_activate: Option<Activate>,
200}
201
202impl FabContent {
203 fn new(id: impl Into<ElementId>, name: impl Into<SharedString>) -> Self {
204 Self {
205 id: id.into(),
206 name: name.into(),
207 size: FabSize::default(),
208 color: FabColor::default(),
209 disabled: false,
210 focus: None,
211 on_activate: None,
212 }
213 }
214
215 fn style(&self) -> ActionStyle {
216 let (height, _, corner, _, _, _) = self.size.metrics();
217 let (background, foreground) = match self.color {
218 FabColor::Primary => (ColorRole::PrimaryContainer, ColorRole::OnPrimaryContainer),
219 FabColor::Secondary => (
220 ColorRole::SecondaryContainer,
221 ColorRole::OnSecondaryContainer,
222 ),
223 FabColor::Tertiary => (ColorRole::TertiaryContainer, ColorRole::OnTertiaryContainer),
224 FabColor::PrimaryStrong => (ColorRole::Primary, ColorRole::OnPrimary),
225 FabColor::SecondaryStrong => (ColorRole::Secondary, ColorRole::OnSecondary),
226 FabColor::TertiaryStrong => (ColorRole::Tertiary, ColorRole::OnTertiary),
227 };
228 ActionStyle {
229 background: Some(background),
230 background_color: None,
231 foreground,
232 disabled: DisabledStyle {
235 foreground: ColorRole::OnSurface,
236 background: Some((ColorRole::OnSurface, 0.12)),
237 outline: (ColorRole::OnSurface, 0.12),
238 },
239 height,
240 min_width: height,
241 corner,
242 pressed_corner: corner,
243 selected_corner: None,
244 corner_motion: (
245 gpui_material_theme::MotionKind::Spatial,
246 gpui_material_theme::MotionSpeed::Fast,
247 ),
248 outline: 0.,
249 outline_role: ColorRole::OutlineVariant,
250 elevation: Elevation::Level3,
251 hover_elevation: Elevation::Level4,
252 }
253 }
254
255 fn action(self, content: impl IntoElement) -> ActionControl {
256 ActionControl {
257 style: self.style(),
258 id: self.id,
259 label: self.name,
260 focus: self.focus,
261 disabled: self.disabled,
262 action: Action::Invoke(self.on_activate),
263 content: content.into_any_element(),
264 }
265 }
266}
267
268#[derive(Default)]
269struct FabAppearance {
270 style: ButtonStyle,
271 interaction_source: Option<Entity<InteractionSource>>,
272 visible: Option<bool>,
273 animation: FabVisibilityAnimation,
274}
275
276impl FabAppearance {
277 fn motion(
278 &self,
279 id: &ElementId,
280 extent: f32,
281 window: &mut Window,
282 cx: &mut App,
283 ) -> OverlayMotion {
284 self.visible.map_or(
285 OverlayMotion {
286 scale: 1.,
287 alpha: 1.,
288 },
289 |visible| self.animation.sample(id, visible, extent, window, cx),
290 )
291 }
292
293 fn interactive(
294 &self,
295 action: &ActionControl,
296 motion: OverlayMotion,
297 window: &mut Window,
298 cx: &mut App,
299 ) -> bool {
300 let interactive = self.visible != Some(false) && motion.alpha > 0. && motion.scale > 0.;
301 if !interactive {
302 action.clear_interaction(window, cx);
303 }
304 interactive
305 }
306
307 fn control(
308 &self,
309 action: ActionControl,
310 scale: f32,
311 interactive: bool,
312 window: &mut Window,
313 cx: &mut App,
314 ) -> AnyElement {
315 action.render_layout(
316 scale,
317 ActionLayout {
318 tab_stop: interactive,
319 decorative: !interactive,
320 appearance: self.style,
321 ..Default::default()
322 },
323 self.interaction_source.as_ref().filter(|_| interactive),
324 window,
325 cx,
326 )
327 }
328}
329
330macro_rules! fab_builders {
331 () => {
332 pub fn size(mut self, size: FabSize) -> Self {
333 self.content.size = size;
334 self
335 }
336
337 pub fn color(mut self, color: FabColor) -> Self {
338 self.content.color = color;
339 self
340 }
341
342 pub fn disabled(mut self, disabled: bool) -> Self {
345 self.content.disabled = disabled;
346 self
347 }
348
349 pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
350 self.content.focus = Some(focus.clone());
351 self
352 }
353
354 pub fn on_activate(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
355 self.content.on_activate = Some(Rc::new(handler));
356 self
357 }
358
359 pub fn shape(mut self, shape: CornerShape) -> Self {
361 self.appearance.style.shapes.resting = Some(shape);
362 self.appearance.style.shapes.pressed = Some(shape);
363 self
364 }
365
366 pub fn colors(mut self, colors: ButtonColors) -> Self {
368 self.appearance.style.colors = colors;
369 self
370 }
371
372 pub fn elevations(mut self, elevations: ButtonElevations) -> Self {
374 self.appearance.style.elevations = elevations;
375 self
376 }
377
378 pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
380 self.appearance.interaction_source = Some(source.clone());
381 self
382 }
383
384 pub fn visible(mut self, visible: bool) -> Self {
386 self.appearance.visible = Some(visible);
387 self
388 }
389
390 pub fn visibility_animation(mut self, animation: FabVisibilityAnimation) -> Self {
392 self.appearance.animation = animation;
393 self
394 }
395 };
396}
397
398#[derive(IntoElement)]
401pub struct Fab {
402 content: FabContent,
403 icon: AnyElement,
404 appearance: FabAppearance,
405}
406
407impl Fab {
408 pub fn new(
409 id: impl Into<ElementId>,
410 name: impl Into<SharedString>,
411 icon: impl IntoElement,
412 ) -> Self {
413 Self {
414 content: FabContent::new(id, name),
415 icon: icon.into_any_element(),
416 appearance: FabAppearance::default(),
417 }
418 }
419
420 fab_builders!();
421}
422
423impl RenderOnce for Fab {
424 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
425 let style = self.content.style();
426 let (_, icon_size, _, _, _, _) = self.content.size.metrics();
427 let icon_size = if self.content.size == FabSize::Large {
428 36.
429 } else {
430 icon_size
431 };
432 let theme = current_material_theme(window, cx);
433 let direction = theme.layout.direction;
434 let extent = theme.layout.density.interactive_size(style.height);
435 let motion = self.appearance.motion(&self.content.id, extent, window, cx);
436 let action = self
437 .content
438 .action(icon_slot(self.icon, icon_size * motion.scale));
439 if self.appearance.visible.is_none() {
440 return self.appearance.control(action, 1., true, window, cx);
441 }
442 let interactive = self.appearance.interactive(&action, motion, window, cx);
443 if motion.alpha == 0. {
444 return Empty.into_any_element();
445 }
446 let extent = px(extent);
447 let mut footprint = div().relative().size(extent).min_w(extent).min_h(extent);
448 if motion.scale > 0. {
449 let pivot = self.appearance.animation.alignment.pivot(direction);
450 let distance = extent * (1. - motion.scale);
451 let control = self
452 .appearance
453 .control(action, motion.scale, interactive, window, cx);
454 footprint = footprint.child(
455 div()
456 .absolute()
457 .left(distance * pivot.x)
458 .top(distance * pivot.y)
459 .opacity(motion.alpha)
460 .child(control),
461 );
462 }
463 footprint.into_any_element()
464 }
465}
466
467#[derive(IntoElement)]
470pub struct ExtendedFab {
471 content: FabContent,
472 icon: Option<AnyElement>,
473 custom_content: Option<AnyElement>,
474 expanded: bool,
475 appearance: FabAppearance,
476}
477
478impl ExtendedFab {
479 pub fn new(
481 id: impl Into<ElementId>,
482 label: impl Into<SharedString>,
483 icon: impl IntoElement,
484 ) -> Self {
485 Self {
486 icon: Some(icon.into_any_element()),
487 ..Self::text(id, label)
488 }
489 }
490
491 pub fn text(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
493 Self {
494 content: FabContent::new(id, label),
495 icon: None,
496 custom_content: None,
497 expanded: true,
498 appearance: FabAppearance::default(),
499 }
500 }
501
502 fab_builders!();
503
504 pub fn content(mut self, content: impl IntoElement) -> Self {
507 self.custom_content = Some(content.into_any_element());
508 self
509 }
510
511 pub fn expanded(mut self, expanded: bool) -> Self {
514 self.expanded = expanded;
515 self
516 }
517}
518
519impl RenderOnce for ExtendedFab {
520 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
521 let (height, icon, _, padding, gap, role) = self.content.size.metrics();
522 let theme = current_material_theme(window, cx);
523 let direction = theme.layout.direction;
524 let extent = theme.layout.density.interactive_size(height);
525 let visual_height = theme.layout.density.visual_size(height);
526 let scheme = theme.motion;
527 let motion = self.appearance.motion(
528 &self.content.id,
529 extent.max(f32::from(window.viewport_size().width)),
530 window,
531 cx,
532 );
533 let action = self.content.action(Empty);
534 let interactive = self.appearance.interactive(&action, motion, window, cx);
535 if motion.alpha == 0. {
536 return Empty.into_any_element();
537 }
538 let (progress, opacity) = if self.icon.is_some() {
539 let reduced = cx.reduce_motion();
540 let mut sample = |channel, kind| {
541 animate(
542 (action.id.clone(), channel),
543 f32::from(self.expanded),
544 scheme.spec(kind, MotionSpeed::Fast, reduced),
545 window,
546 cx,
547 )
548 .clamp(0., 1.)
549 };
550 (
551 sample("expansion", MotionKind::Spatial),
552 sample("label-opacity", MotionKind::Effects),
553 )
554 } else {
555 (1., 1.)
556 };
557 let (icon_size, padding, gap) = if self.icon.is_some() {
558 let collapsed_padding = (height - icon) / 2.;
559 (
560 icon,
561 collapsed_padding + (padding - collapsed_padding) * progress,
562 gap * progress,
563 )
564 } else {
565 (0., padding, 0.)
566 };
567 let ink = self
568 .appearance
569 .style
570 .colors
571 .content(action.disabled, false)
572 .unwrap_or_else(|| action.style.foreground(action.disabled, window, cx));
573 let typography = role.style(TypographyEmphasis::Baseline);
574 let mut custom_content = self.custom_content;
575 let mut pre_shaped = None;
576 let label_width = if progress == 0. {
577 px(0.)
578 } else if let Some(content) = &mut custom_content {
579 window
580 .with_text_style(
581 Some(gpui::TextStyleRefinement {
582 color: Some(ink),
583 font_size: Some(px(typography.size).into()),
584 line_height: Some(px(typography.line_height).into()),
585 ..Default::default()
586 }),
587 |window| {
588 content.layout_as_root(
589 size(AvailableSpace::MaxContent, AvailableSpace::MaxContent),
590 window,
591 cx,
592 )
593 },
594 )
595 .width
596 } else {
597 let (clean, shaped) = crate::text::shape_single_line(
598 action.label.clone(),
599 typography,
600 1.,
601 ink,
602 window,
603 cx,
604 );
605 let width = shaped.line().width.ceil();
606 pre_shaped = Some((clean, shaped));
607 width
608 };
609 let fixed_width = px(icon_size + gap + padding * 2.);
610 let width = (fixed_width + label_width * progress).max(px(extent));
611 let control = canvas(
614 move |bounds, window, cx| {
615 if motion.scale == 0. {
616 return None;
617 }
618 let scale = if f32::from(bounds.size.width * motion.scale).is_finite() {
619 motion.scale
620 } else {
621 1.
622 };
623 let motion = OverlayMotion { scale, ..motion };
624 let pivot = self.appearance.animation.alignment.pivot(direction);
625 let assigned_width = bounds.size.width * scale;
626 let mut row = div()
627 .flex()
628 .items_center()
629 .w(assigned_width)
630 .px(px(padding * scale))
631 .gap(px(gap * scale))
632 .when(direction == Direction::Rtl, Styled::flex_row_reverse);
633 if let Some(icon) = self.icon {
634 row = row.child(icon_slot(icon, icon_size * scale));
635 }
636 let mut action = action;
637 let available = (bounds.size.width - fixed_width).max(px(0.));
638 let label_width = (label_width * progress).min(available) * scale;
639 if label_width > px(0.) {
640 if let Some(content) = custom_content {
641 row = row.child(custom_label(
642 content,
643 label_width,
644 px(visual_height * scale),
645 opacity,
646 ));
647 } else if scale == 1.
648 && let Some(shaped) = pre_shaped
649 {
650 row = row.child(crate::text::single_line_with_shaped(
651 shaped,
652 typography,
653 1.,
654 ink,
655 (Some(label_width / progress), progress, opacity),
656 window,
657 cx,
658 ));
659 } else {
660 row = row.child(crate::text::single_line(
661 action.label.clone(),
662 typography,
663 scale,
664 ink,
665 (Some(label_width / progress), progress, opacity),
666 window,
667 cx,
668 ));
669 }
670 }
671 action.content = row.into_any_element();
672 let action = self
673 .appearance
674 .control(action, scale, interactive, window, cx);
675 let mut target = div()
676 .w(assigned_width)
677 .opacity(motion.alpha)
678 .child(action)
679 .into_any_element();
680 target.prepaint_as_root(
681 motion.origin(bounds, pivot),
682 bounds
683 .size
684 .map(|side| AvailableSpace::Definite(side * scale)),
685 window,
686 cx,
687 );
688 Some(target)
689 },
690 |_, target, window, cx| {
691 if let Some(mut target) = target {
692 target.paint(window, cx);
693 }
694 },
695 );
696 div()
697 .w(width)
698 .h(px(extent))
699 .min_w(px(extent))
700 .min_h(px(extent))
701 .max_w_full()
702 .child(control.size_full())
703 .into_any_element()
704 }
705}
706
707fn custom_label(mut content: AnyElement, width: Pixels, height: Pixels, opacity: f32) -> gpui::Div {
708 div()
709 .w(width)
710 .h(height)
711 .min_w_0()
712 .overflow_hidden()
713 .opacity(opacity)
714 .child(
715 canvas(
716 move |bounds, window, cx| {
717 let actual = content.layout_as_root(
718 bounds.size.map(AvailableSpace::Definite),
719 window,
720 cx,
721 );
722 let origin = point(
723 bounds.origin.x,
724 bounds.origin.y + ((bounds.size.height - actual.height) / 2.).max(px(0.)),
725 );
726 content.prepaint_at(origin, window, cx);
727 content
728 },
729 |_, mut content, window, cx| content.paint(window, cx),
730 )
731 .size_full(),
732 )
733}
734
735#[derive(IntoElement)]
738pub struct FloatingAction {
739 action: AnyElement,
740 margin: gpui::Pixels,
741}
742
743impl FloatingAction {
744 pub fn new(action: impl IntoElement) -> Self {
745 Self {
746 action: action.into_any_element(),
747 margin: px(16.),
748 }
749 }
750
751 pub fn margin(mut self, margin: gpui::Pixels) -> Self {
752 self.margin = margin.max(px(0.));
753 self
754 }
755}
756
757impl RenderOnce for FloatingAction {
758 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
759 let viewport = window.viewport_size();
760 let direction = current_material_theme(window, cx).layout.direction;
761 let margin = self.margin.min(viewport.width.min(viewport.height) / 4.);
762 let x = if direction == Direction::Rtl {
763 margin
764 } else {
765 viewport.width - margin
766 };
767 deferred(
768 anchored()
769 .anchor(logical_anchor(gpui::Anchor::BottomRight, direction))
770 .position(gpui::point(x, viewport.height - margin))
771 .snap_to_window_with_margin(margin)
772 .child(ThemeScope::inherit(
773 div()
774 .max_w((viewport.width - margin * 2.).max(px(0.)))
775 .child(self.action),
776 window,
777 cx,
778 )),
779 )
780 }
781}