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.release_if_held(now);
84    }
85
86    pub(crate) fn release_if_held(&mut self, now: Instant) -> bool {
87        if self.released.is_some() {
88            return false;
89        }
90        self.released = Some(now);
91        true
92    }
93
94    /// Draws above the state layer and requests another frame while its radius or opacity changes.
95    pub fn paint(
96        &self,
97        shape: &Shape,
98        color: Hsla,
99        now: Instant,
100        reduced_motion: bool,
101        window: &mut Window,
102    ) {
103        if reduced_motion {
104            return;
105        }
106        let (progress, alpha) = self.sample(now);
107        if alpha <= 0. && progress >= 1. {
108            return;
109        }
110        let bounds = shape.bounds();
111        if !crate::is_bounds_visible(bounds, window) {
112            return;
113        }
114        let center = bounds.center() - bounds.origin;
115        let origin = bounds.origin + self.origin + (center - self.origin) * progress;
116        let width = f32::from(bounds.size.width);
117        let height = f32::from(bounds.size.height);
118        let start_radius = width.max(height) * 0.3;
119        let end_radius = width.hypot(height) * 0.5 + 10.;
120        let expansion = gpui_base::motion::Easing::CubicBezier {
121            x1: 0.4,
122            y1: 0.,
123            x2: 0.2,
124            y2: 1.,
125        }
126        .sample(progress);
127        shape.paint_ripple(
128            origin,
129            px(start_radius + (end_radius - start_radius) * expansion),
130            color.opacity(StateLayer::Pressed.opacity() * alpha),
131            window,
132        );
133        if progress < 1. || self.released.is_some() {
134            window.request_animation_frame();
135        }
136    }
137
138    // Compose RippleAnimation waits for radius/center expansion before fading out.
139    // A quick release reaches full opacity immediately so short taps remain visible.
140    fn sample(&self, now: Instant) -> (f32, f32) {
141        let elapsed = now.saturating_duration_since(self.started);
142        let fade_start = self
143            .released
144            .map(|time| time.max(self.started + RIPPLE_EXPANSION));
145        let fade = fade_start.map_or(0., |time| {
146            now.saturating_duration_since(time).as_secs_f32() / RIPPLE_FADE_OUT.as_secs_f32()
147        });
148        let progress = (elapsed.as_secs_f32() / RIPPLE_EXPANSION.as_secs_f32()).min(1.);
149        let fade_in = if self.released.is_some_and(|released| now >= released) {
150            1.
151        } else {
152            (elapsed.as_secs_f32() / RIPPLE_FADE_IN.as_secs_f32()).min(1.)
153        };
154        (progress, fade_in * (1. - fade).clamp(0., 1.))
155    }
156}
157
158/// Material feedback colors and state policy for a prepared shape.
159pub struct InteractionFeedback {
160    state: InteractionState,
161    foreground: Hsla,
162    focus: Hsla,
163}
164
165impl InteractionFeedback {
166    pub fn new(state: InteractionState, foreground: Hsla, focus: Hsla) -> Self {
167        Self {
168            state,
169            foreground,
170            focus,
171        }
172    }
173
174    /// Draws the state layer, optional ripple, and keyboard focus ring.
175    pub fn paint(
176        &self,
177        shape: &Shape,
178        ripple: Option<&Ripple>,
179        now: Instant,
180        reduced_motion: bool,
181        window: &mut Window,
182    ) {
183        self.paint_with_opacity(
184            shape,
185            ripple,
186            self.state
187                .layer_with_ripple(reduced_motion || ripple.is_none())
188                .map_or(0., |layer| layer.opacity()),
189            now,
190            reduced_motion,
191            window,
192        );
193    }
194
195    /// Paints a state layer sampled by the caller's stable motion channel.
196    pub fn paint_with_opacity(
197        &self,
198        shape: &Shape,
199        ripple: Option<&Ripple>,
200        opacity: f32,
201        now: Instant,
202        reduced_motion: bool,
203        window: &mut Window,
204    ) {
205        if !self.state.disabled && opacity > 0. {
206            shape.paint(self.foreground.opacity(opacity), window);
207        }
208        if !self.state.disabled {
209            if let Some(ripple) = ripple {
210                ripple.paint(shape, self.foreground, now, reduced_motion, window);
211            }
212            if self.state.focus_visible {
213                shape.paint_ring(FOCUS_RING_WIDTH, self.focus, window);
214            }
215        }
216    }
217}
218
219#[cfg(test)]
220mod tests {
221    use super::*;
222
223    #[test]
224    fn ripple_owns_press_while_hover_focus_and_reduced_motion_remain_visible() {
225        let mut state = InteractionState {
226            pressed: true,
227            ..Default::default()
228        };
229        assert_eq!(state.layer_with_ripple(false), None);
230        assert_eq!(state.layer_with_ripple(true), Some(StateLayer::Pressed));
231        state.hovered = true;
232        assert_eq!(state.layer_with_ripple(false), Some(StateLayer::Hover));
233        state.focus_visible = true;
234        assert_eq!(state.layer_with_ripple(false), Some(StateLayer::Focus));
235        state.dragged = true;
236        assert_eq!(state.layer_with_ripple(false), Some(StateLayer::Dragged));
237        state.disabled = true;
238        assert_eq!(state.layer_with_ripple(false), None);
239        assert_eq!(state.layer_with_ripple(true), None);
240    }
241
242    #[test]
243    fn quick_tap_finishes_expansion_before_fading_and_held_ripple_settles() {
244        let now = Instant::now();
245        let mut ripple = Ripple {
246            origin: gpui::point(px(0.), px(0.)),
247            started: now,
248            released: None,
249        };
250        assert_eq!(ripple.sample(now), (0., 0.));
251        assert_eq!(ripple.sample(now + Duration::from_secs(1)), (1., 1.));
252        ripple.release(now + Duration::from_millis(10));
253        assert_eq!(ripple.sample(now + Duration::from_millis(10)).1, 1.);
254        assert_eq!(ripple.sample(now + RIPPLE_EXPANSION), (1., 1.));
255        assert_eq!(
256            ripple.sample(now + RIPPLE_EXPANSION + RIPPLE_FADE_OUT / 2),
257            (1., 0.5)
258        );
259        assert_eq!(
260            ripple.sample(now + RIPPLE_EXPANSION + RIPPLE_FADE_OUT),
261            (1., 0.)
262        );
263        ripple.release(now + Duration::from_secs(2));
264        assert_eq!(ripple.sample(now + Duration::from_secs(2)), (1., 0.));
265    }
266
267    #[test]
268    fn disabled_suppresses_the_layer_and_drag_precedes_press() {
269        let mut state = InteractionState {
270            disabled: false,
271            hovered: true,
272            focus_visible: true,
273            pressed: true,
274            dragged: true,
275        };
276        assert_eq!(state.layer(), Some(StateLayer::Dragged));
277        state.dragged = false;
278        assert_eq!(state.layer(), Some(StateLayer::Pressed));
279        state.pressed = false;
280        assert_eq!(state.layer(), Some(StateLayer::Focus));
281        state.disabled = true;
282        assert_eq!(state.layer(), None);
283    }
284}