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