Skip to main content

gpui_material_foundation/
feedback.rs

1use std::time::Duration;
2
3use gpui::{Hsla, Pixels, Point, Window, px};
4use gpui_material_theme::StateLayer;
5use web_time::Instant;
6
7use crate::Shape;
8
9const RIPPLE_EXPANSION: Duration = Duration::from_millis(225);
10const RIPPLE_FADE_IN: Duration = Duration::from_millis(75);
11const RIPPLE_FADE_OUT: Duration = Duration::from_millis(150);
12const FOCUS_RING_WIDTH: Pixels = px(3.);
13
14/// A snapshot of interaction state from the caller's GPUI/Base behavior.
15#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
16#[non_exhaustive]
17pub struct InteractionState {
18    /// Whether the control is currently disabled.
19    pub disabled: bool,
20    /// Whether a pointer is hovering over the control.
21    pub hovered: bool,
22    /// Whether the control holds visible keyboard focus.
23    pub focus_visible: bool,
24    /// Whether the control is actively pressed.
25    pub pressed: bool,
26    /// Whether the control is actively being dragged.
27    pub dragged: bool,
28}
29
30impl InteractionState {
31    /// Resolves the non-press state layer when a ripple supplies press feedback.
32    /// Reduced motion uses the static pressed layer instead of an animated ripple.
33    pub fn layer_with_ripple(self, reduced_motion: bool) -> Option<StateLayer> {
34        Self {
35            pressed: self.pressed && reduced_motion,
36            ..self
37        }
38        .layer()
39    }
40
41    /// Resolves the highest-priority Material [`StateLayer`] for this interaction snapshot,
42    /// or `None` when disabled or idle.
43    pub fn layer(self) -> Option<StateLayer> {
44        if self.disabled {
45            None
46        } else if self.dragged {
47            Some(StateLayer::Dragged)
48        } else if self.pressed {
49            Some(StateLayer::Pressed)
50        } else if self.focus_visible {
51            Some(StateLayer::Focus)
52        } else if self.hovered {
53            Some(StateLayer::Hover)
54        } else {
55            None
56        }
57    }
58}
59
60/// One pointer or keyboard ripple. A held ripple is released when the
61/// interaction ends; a one-shot ripple releases itself.
62#[derive(Clone)]
63pub struct Ripple {
64    origin: Point<Pixels>,
65    started: Instant,
66    released: Option<Instant>,
67}
68
69impl Ripple {
70    /// Starts a one-shot ripple at the activation point or the shape's center.
71    pub fn start(shape: &Shape, pointer: Option<Point<Pixels>>, now: Instant) -> Option<Self> {
72        let mut ripple = Self::press(shape, pointer, now)?;
73        ripple.release(now);
74        Some(ripple)
75    }
76
77    /// Starts a ripple that holds its settled opacity until released.
78    pub fn press(shape: &Shape, pointer: Option<Point<Pixels>>, now: Instant) -> Option<Self> {
79        let bounds = shape.bounds();
80        let origin = pointer.unwrap_or_else(|| bounds.center());
81        shape.contains(origin).then_some(Self {
82            origin: origin - bounds.origin,
83            started: now,
84            released: None,
85        })
86    }
87
88    /// Begins the exit from the current ripple opacity after a release or cancellation.
89    pub fn release(&mut self, now: Instant) {
90        self.release_if_held(now);
91    }
92
93    pub(crate) fn release_if_held(&mut self, now: Instant) -> bool {
94        if self.released.is_some() {
95            return false;
96        }
97        self.released = Some(now);
98        true
99    }
100
101    pub(crate) fn is_finished(&self, now: Instant) -> bool {
102        let (progress, alpha) = self.sample(now);
103        alpha <= 0. && progress >= 1.
104    }
105
106    /// Draws above the state layer and requests another frame while its radius or opacity changes.
107    pub fn paint(
108        &self,
109        shape: &Shape,
110        color: Hsla,
111        now: Instant,
112        reduced_motion: bool,
113        window: &mut Window,
114    ) {
115        if reduced_motion {
116            return;
117        }
118        let (progress, alpha) = self.sample(now);
119        if alpha <= 0. && progress >= 1. {
120            return;
121        }
122        let bounds = shape.bounds();
123        if !crate::is_bounds_visible(bounds, window) {
124            return;
125        }
126        let center = bounds.center() - bounds.origin;
127        let origin = bounds.origin + self.origin + (center - self.origin) * progress;
128        let width = f32::from(bounds.size.width);
129        let height = f32::from(bounds.size.height);
130        let start_radius = width.max(height) * 0.3;
131        let end_radius = width.hypot(height) * 0.5 + 10.;
132        let expansion = gpui_base::motion::Easing::CubicBezier {
133            x1: 0.4,
134            y1: 0.,
135            x2: 0.2,
136            y2: 1.,
137        }
138        .sample(progress);
139        shape.paint_ripple(
140            origin,
141            px(start_radius + (end_radius - start_radius) * expansion),
142            color.opacity(StateLayer::Pressed.opacity() * alpha),
143            window,
144        );
145        if progress < 1. || self.released.is_some() {
146            window.request_animation_frame();
147        }
148    }
149
150    // Compose RippleAnimation waits for radius/center expansion before fading out.
151    // A quick release reaches full opacity immediately so short taps remain visible.
152    fn sample(&self, now: Instant) -> (f32, f32) {
153        let elapsed = now.saturating_duration_since(self.started);
154        let fade_start = self
155            .released
156            .map(|time| time.max(self.started + RIPPLE_EXPANSION));
157        let fade = fade_start.map_or(0., |time| {
158            now.saturating_duration_since(time).as_secs_f32() / RIPPLE_FADE_OUT.as_secs_f32()
159        });
160        let progress = (elapsed.as_secs_f32() / RIPPLE_EXPANSION.as_secs_f32()).min(1.);
161        let fade_in = if self.released.is_some_and(|released| now >= released) {
162            1.
163        } else {
164            (elapsed.as_secs_f32() / RIPPLE_FADE_IN.as_secs_f32()).min(1.)
165        };
166        (progress, fade_in * (1. - fade).clamp(0., 1.))
167    }
168}
169
170/// Material feedback colors and state policy for a prepared shape.
171pub struct InteractionFeedback {
172    state: InteractionState,
173    foreground: Hsla,
174    focus: Hsla,
175}
176
177impl InteractionFeedback {
178    /// Creates an [`InteractionFeedback`] painter from the current interaction state,
179    /// state-layer/ripple ink color (`foreground`), and keyboard focus ring color (`focus`).
180    pub fn new(state: InteractionState, foreground: Hsla, focus: Hsla) -> Self {
181        Self {
182            state,
183            foreground,
184            focus,
185        }
186    }
187
188    /// Draws the state layer, optional ripple, and keyboard focus ring.
189    pub fn paint(
190        &self,
191        shape: &Shape,
192        ripple: Option<&Ripple>,
193        now: Instant,
194        reduced_motion: bool,
195        window: &mut Window,
196    ) {
197        self.paint_with_opacity(
198            shape,
199            ripple,
200            self.state
201                .layer_with_ripple(reduced_motion || ripple.is_none())
202                .map_or(0., |layer| layer.opacity()),
203            now,
204            reduced_motion,
205            window,
206        );
207    }
208
209    /// Paints a state layer sampled by the caller's stable motion channel.
210    pub fn paint_with_opacity(
211        &self,
212        shape: &Shape,
213        ripple: Option<&Ripple>,
214        opacity: f32,
215        now: Instant,
216        reduced_motion: bool,
217        window: &mut Window,
218    ) {
219        if !self.state.disabled && opacity > 0. {
220            shape.paint(self.foreground.opacity(opacity), window);
221        }
222        if !self.state.disabled {
223            if let Some(ripple) = ripple {
224                ripple.paint(shape, self.foreground, now, reduced_motion, window);
225            }
226            if self.state.focus_visible {
227                shape.paint_ring(FOCUS_RING_WIDTH, self.focus, window);
228            }
229        }
230    }
231}
232
233#[cfg(test)]
234mod tests {
235    use super::*;
236
237    #[test]
238    fn ripple_owns_press_while_hover_focus_and_reduced_motion_remain_visible() {
239        let mut state = InteractionState {
240            pressed: true,
241            ..Default::default()
242        };
243        assert_eq!(state.layer_with_ripple(false), None);
244        assert_eq!(state.layer_with_ripple(true), Some(StateLayer::Pressed));
245        state.hovered = true;
246        assert_eq!(state.layer_with_ripple(false), Some(StateLayer::Hover));
247        state.focus_visible = true;
248        assert_eq!(state.layer_with_ripple(false), Some(StateLayer::Focus));
249        state.dragged = true;
250        assert_eq!(state.layer_with_ripple(false), Some(StateLayer::Dragged));
251        state.disabled = true;
252        assert_eq!(state.layer_with_ripple(false), None);
253        assert_eq!(state.layer_with_ripple(true), None);
254    }
255
256    #[test]
257    fn quick_tap_finishes_expansion_before_fading_and_held_ripple_settles() {
258        let now = Instant::now();
259        let mut ripple = Ripple {
260            origin: gpui::point(px(0.), px(0.)),
261            started: now,
262            released: None,
263        };
264        assert_eq!(ripple.sample(now), (0., 0.));
265        assert_eq!(ripple.sample(now + Duration::from_secs(1)), (1., 1.));
266        ripple.release(now + Duration::from_millis(10));
267        assert_eq!(ripple.sample(now + Duration::from_millis(10)).1, 1.);
268        assert_eq!(ripple.sample(now + RIPPLE_EXPANSION), (1., 1.));
269        assert_eq!(
270            ripple.sample(now + RIPPLE_EXPANSION + RIPPLE_FADE_OUT / 2),
271            (1., 0.5)
272        );
273        assert_eq!(
274            ripple.sample(now + RIPPLE_EXPANSION + RIPPLE_FADE_OUT),
275            (1., 0.)
276        );
277        ripple.release(now + Duration::from_secs(2));
278        assert_eq!(ripple.sample(now + Duration::from_secs(2)), (1., 0.));
279        assert!(ripple.is_finished(now + Duration::from_secs(2)));
280        let mut feedback = crate::control_feedback::FeedbackState::default();
281        feedback.ripple = Some(ripple);
282        feedback.prune_finished_ripple(now);
283        assert!(feedback.ripple.is_some());
284        feedback.prune_finished_ripple(now + Duration::from_secs(2));
285        assert!(feedback.ripple.is_none());
286    }
287
288    #[test]
289    fn disabled_suppresses_the_layer_and_drag_precedes_press() {
290        let mut state = InteractionState {
291            disabled: false,
292            hovered: true,
293            focus_visible: true,
294            pressed: true,
295            dragged: true,
296        };
297        assert_eq!(state.layer(), Some(StateLayer::Dragged));
298        state.dragged = false;
299        assert_eq!(state.layer(), Some(StateLayer::Pressed));
300        state.pressed = false;
301        assert_eq!(state.layer(), Some(StateLayer::Focus));
302        state.disabled = true;
303        assert_eq!(state.layer(), None);
304    }
305}