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