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