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