Skip to main content

cranpose_liquid/
motion.rs

1//! Liquid motion: the spring presets every component shares, and the press
2//! interaction (scale + specular boost) that makes glass feel physical.
3
4use cranpose_animation::{spring, tween, Animatable, AnimationType, Easing};
5use cranpose_core::{with_current_composer, RuntimeHandle, State};
6use cranpose_foundation::VelocityTracker1D;
7use cranpose_macros::composable;
8use cranpose_ui::Modifier;
9use cranpose_ui::MutableInteractionSource;
10use cranpose_ui_graphics::GraphicsLayer;
11use std::cell::{Cell, RefCell};
12use std::rc::Rc;
13
14use crate::dynamics::{LiquidDynamics, LiquidPose};
15
16const FLUID_RELAX_MS: u64 = 420;
17const VISUAL_HANDOFF_TOLERANCE_IN_ITEMS: f32 = 0.12;
18
19pub(crate) fn liquid_visual_index(
20    selected: usize,
21    lens_position: f32,
22    item_width: f32,
23    count: usize,
24    lens_owns_selection: bool,
25) -> usize {
26    if count == 0 {
27        return 0;
28    }
29    let selected = selected.min(count - 1);
30    if !lens_owns_selection || !lens_position.is_finite() || item_width <= f32::EPSILON {
31        return selected;
32    }
33    (lens_position / item_width)
34        .floor()
35        .clamp(0.0, count.saturating_sub(1) as f32) as usize
36}
37
38pub(crate) fn liquid_axis_owns_visual_selection(
39    direct: bool,
40    lens_position: f32,
41    state_position: f32,
42    item_width: f32,
43) -> bool {
44    direct
45        || (lens_position - state_position).abs()
46            > item_width.max(f32::EPSILON) * VISUAL_HANDOFF_TOLERANCE_IN_ITEMS
47}
48
49/// Named springs used across the Liquid components (value-space, velocity
50/// preserving).
51pub struct LiquidMotion;
52
53impl LiquidMotion {
54    /// Snappy interactions: presses, toggles, selection moves.
55    pub fn snappy() -> AnimationType {
56        spring(0.85, 900.0)
57    }
58
59    /// The droplet feel: visible overshoot for morphing shapes.
60    pub fn bouncy() -> AnimationType {
61        spring(0.55, 500.0)
62    }
63
64    /// Gentle settle for large surfaces (sheets, menus).
65    pub fn smooth() -> AnimationType {
66        spring(1.0, 400.0)
67    }
68
69    /// The leading edge of a stretching selection blob (runs ahead).
70    pub fn blob_leading() -> AnimationType {
71        spring(0.8, 900.0)
72    }
73
74    /// The trailing edge of a stretching selection blob (drags behind, giving
75    /// the droplet elongation while in motion).
76    pub fn blob_trailing() -> AnimationType {
77        spring(0.9, 380.0)
78    }
79
80    /// A released lens flying to its committed slot: the reference
81    /// bottom-bar transfer arrives in ~170 ms (on-white-click sheet,
82    /// f_0040 departure to f_0050 arrival at 60 fps) with no visible
83    /// overshoot; the optical settle continues after the geometry lands.
84    pub fn glide() -> AnimationType {
85        spring(1.0, 500.0)
86    }
87}
88
89/// One travelling coordinate with strict direct-manipulation semantics.
90/// Pointer samples are visible immediately; the animation channel is used
91/// only after release or for controlled-state changes while idle.
92pub(crate) struct LiquidDragAxis {
93    animation: RefCell<Animatable<f32>>,
94    pointer: Cell<Option<f32>>,
95    velocity: RefCell<VelocityTracker1D>,
96    runtime: RuntimeHandle,
97    last_sample_ms: Cell<Option<i64>>,
98    dynamics: LiquidDynamics,
99    fluid_clock: RefCell<Animatable<f32>>,
100}
101
102impl LiquidDragAxis {
103    fn new(initial: f32, runtime: RuntimeHandle) -> Self {
104        Self {
105            animation: RefCell::new(Animatable::new(initial, runtime.clone())),
106            pointer: Cell::new(None),
107            velocity: RefCell::new(VelocityTracker1D::new()),
108            dynamics: LiquidDynamics::new(runtime.clone()),
109            fluid_clock: RefCell::new(Animatable::new(1.0, runtime.clone())),
110            runtime,
111            last_sample_ms: Cell::new(None),
112        }
113    }
114
115    fn arm_fluid_frames(&self) {
116        let mut clock = self.fluid_clock.borrow_mut();
117        clock.snapTo(0.0);
118        clock.animateTo(1.0, tween(FLUID_RELAX_MS, Easing::LinearEasing));
119    }
120
121    fn sample_time_ms(&self, event_time_ms: Option<i64>) -> i64 {
122        let candidate = event_time_ms
123            .or_else(|| {
124                self.runtime
125                    .last_frame_time_nanos()
126                    .map(|nanos| (nanos / 1_000_000) as i64)
127            })
128            .unwrap_or_else(|| self.last_sample_ms.get().unwrap_or(0) + 16);
129        let monotonic = self
130            .last_sample_ms
131            .get()
132            .map_or(candidate, |last| candidate.max(last + 1));
133        self.last_sample_ms.set(Some(monotonic));
134        monotonic
135    }
136
137    pub(crate) fn begin(&self, position: f32, event_time_ms: Option<i64>) {
138        let time_ms = self.sample_time_ms(event_time_ms);
139        let mut velocity = self.velocity.borrow_mut();
140        velocity.reset();
141        velocity.add_data_point(time_ms, position);
142        self.pointer.set(Some(position));
143        self.animation.borrow_mut().snapTo(position);
144        self.dynamics.anchor_pointer((position, 0.0));
145        self.arm_fluid_frames();
146    }
147
148    pub(crate) fn move_to(&self, position: f32, event_time_ms: Option<i64>) {
149        if self.pointer.get().is_none() {
150            return;
151        }
152        let previous_time_ms = self.last_sample_ms.get();
153        let time_ms = self.sample_time_ms(event_time_ms);
154        self.velocity.borrow_mut().add_data_point(time_ms, position);
155        self.pointer.set(Some(position));
156        self.animation.borrow_mut().snapTo(position);
157        if let Some(previous_time_ms) = previous_time_ms {
158            let dt = (time_ms - previous_time_ms).max(1) as f32 / 1000.0;
159            self.dynamics.advance_pointer((position, 0.0), dt);
160        }
161        self.arm_fluid_frames();
162    }
163
164    pub(crate) fn release_to(
165        &self,
166        target: f32,
167        event_time_ms: Option<i64>,
168        animation: AnimationType,
169    ) {
170        let Some(position) = self.pointer.take() else {
171            self.settle_to(target, animation);
172            return;
173        };
174        let time_ms = self.sample_time_ms(event_time_ms);
175        self.velocity.borrow_mut().add_data_point(time_ms, position);
176        let release_velocity = self.velocity.borrow().calculate_velocity_with_max(8_000.0);
177        self.dynamics.release_pointer();
178        self.animation
179            .borrow_mut()
180            .animate_to_with_velocity(target, release_velocity, animation);
181    }
182
183    /// End direct manipulation at its final sample without creating a
184    /// translational spring flight. Continuous controls stop at the finger,
185    /// while the fluid integrator retains and relaxes the sampled velocity.
186    pub(crate) fn finish_at(&self, position: f32, event_time_ms: Option<i64>) {
187        let Some(_) = self.pointer.get() else {
188            self.animation.borrow_mut().snapTo(position);
189            return;
190        };
191        let previous_time_ms = self.last_sample_ms.get();
192        let time_ms = self.sample_time_ms(event_time_ms);
193        self.velocity.borrow_mut().add_data_point(time_ms, position);
194        if let Some(previous_time_ms) = previous_time_ms {
195            let dt = (time_ms - previous_time_ms).max(1) as f32 / 1000.0;
196            self.dynamics.advance_pointer((position, 0.0), dt);
197        }
198        self.pointer.set(None);
199        self.animation.borrow_mut().snapTo(position);
200        self.dynamics.release_pointer();
201        self.arm_fluid_frames();
202    }
203
204    pub(crate) fn settle_to(&self, target: f32, animation: AnimationType) {
205        if self.pointer.get().is_some() {
206            return;
207        }
208        let mut value = self.animation.borrow_mut();
209        if (value.target() - target).abs() > f32::EPSILON {
210            value.animateTo(target, animation);
211        }
212    }
213
214    pub(crate) fn value(&self) -> f32 {
215        let _ = self.fluid_clock.borrow().state().value();
216        self.pointer
217            .get()
218            .unwrap_or_else(|| self.animation.borrow().state().value())
219    }
220
221    pub(crate) fn liquid_pose(&self) -> LiquidPose {
222        self.dynamics.update_pointer((self.value(), 0.0))
223    }
224
225    pub(crate) fn is_dragging(&self) -> bool {
226        self.pointer.get().is_some()
227    }
228}
229
230#[composable]
231pub(crate) fn remember_liquid_drag_axis(initial: f32) -> Rc<LiquidDragAxis> {
232    with_current_composer(|composer| {
233        let runtime = composer.runtime_handle();
234        composer
235            .remember(move || Rc::new(LiquidDragAxis::new(initial, runtime)))
236            .with(Rc::clone)
237    })
238}
239
240/// Press feedback for glass controls, per the Liquid Glass law: touched glass
241/// GROWS (spring scale toward `pressed_scale` — never smaller) and turns MORE
242/// TRANSPARENT (the returned content alpha dips while pressed, the reference
243/// "…" dots fading as the button lifts). Returns the pressed state so callers
244/// can also boost the specular highlight.
245///
246/// Apply the returned modifier *outside* the glass effect so the whole lens
247/// scales together; apply the content alpha to the label/icon layer.
248#[composable]
249pub fn liquid_press_scale(
250    modifier: Modifier,
251    interaction_source: MutableInteractionSource,
252    pressed_scale: f32,
253) -> (Modifier, State<bool>, State<f32>) {
254    let pressed = interaction_source.collectIsPressedAsState();
255    let scale = cranpose_animation::animateFloatAsState(
256        if pressed.get() {
257            pressed_scale.max(1.0)
258        } else {
259            1.0
260        },
261        LiquidMotion::snappy(),
262        "liquid-press-scale",
263    );
264    let content_alpha = cranpose_animation::animateFloatAsState(
265        // The reference down-state ghosts glyphs hard (the menu button's
266        // dots drop to ~30% while held).
267        if pressed.get() { 0.35 } else { 1.0 },
268        LiquidMotion::smooth(),
269        "liquid-press-content",
270    );
271    let modifier = modifier.graphics_layer(move || {
272        let scale = scale.get();
273        GraphicsLayer {
274            scale_x: scale,
275            scale_y: scale,
276            ..Default::default()
277        }
278    });
279    (modifier, pressed, content_alpha)
280}
281
282#[cfg(test)]
283mod tests {
284    use super::*;
285
286    fn axis(initial: f32) -> (cranpose_core::Runtime, LiquidDragAxis) {
287        let runtime =
288            cranpose_core::Runtime::new(std::sync::Arc::new(cranpose_core::DefaultScheduler));
289        let axis = LiquidDragAxis::new(initial, runtime.handle());
290        (runtime, axis)
291    }
292
293    #[test]
294    fn pointer_samples_are_the_visual_coordinate_without_a_chase() {
295        let (_runtime, axis) = axis(10.0);
296        axis.begin(20.0, Some(0));
297        assert_eq!(axis.value(), 20.0);
298        axis.move_to(180.0, Some(16));
299        assert_eq!(axis.value(), 180.0);
300    }
301
302    #[test]
303    fn direct_manipulation_owns_visual_selection_until_the_lens_reaches_state() {
304        assert_eq!(liquid_visual_index(2, 0.0, 78.0, 4, false), 2);
305        assert_eq!(liquid_visual_index(0, 2.0 * 78.0, 78.0, 4, true), 2);
306        assert_eq!(liquid_visual_index(0, 2.71 * 78.0, 78.0, 4, true), 2);
307        assert_eq!(liquid_visual_index(0, 3.0 * 78.0, 78.0, 4, true), 3);
308        assert_eq!(liquid_visual_index(0, 99.0 * 78.0, 78.0, 4, true), 3);
309        assert_eq!(liquid_visual_index(9, f32::NAN, 78.0, 4, true), 3);
310        assert_eq!(liquid_visual_index(0, 78.0, 0.0, 4, true), 0);
311
312        assert!(liquid_axis_owns_visual_selection(true, 0.0, 0.0, 78.0));
313        assert!(liquid_axis_owns_visual_selection(false, 78.0, 0.0, 78.0));
314        assert!(!liquid_axis_owns_visual_selection(
315            false,
316            78.0 * 0.05,
317            0.0,
318            78.0,
319        ));
320    }
321
322    #[test]
323    fn pointer_sample_excites_the_incompressible_pose_before_render() {
324        let (_runtime, axis) = axis(0.0);
325        axis.begin(0.0, Some(0));
326        axis.move_to(14.0, Some(16));
327        let pose = axis.liquid_pose();
328        let deformation = (pose.stretch - 1.0).abs();
329        assert!(
330            (0.08..=0.12).contains(&deformation),
331            "the direct-input frame must deform visibly without treating one sample as extreme acceleration: {pose:?}"
332        );
333        assert!((pose.stretch * pose.ortho - 1.0).abs() < 1e-4);
334        assert_eq!(axis.value(), 14.0);
335    }
336
337    #[test]
338    fn render_without_a_new_pointer_sample_preserves_velocity_continuity() {
339        let (_runtime, axis) = axis(0.0);
340        axis.runtime.drain_frame_callbacks(1_000_000);
341        axis.begin(0.0, Some(0));
342        axis.move_to(14.0, Some(16));
343        let sampled = axis.liquid_pose();
344
345        axis.runtime.drain_frame_callbacks(17_000_000);
346        let next_frame = axis.liquid_pose();
347
348        assert!(
349            (next_frame.stretch - sampled.stretch).abs() < 0.08,
350            "a render frame without input must not synthesize a brake impulse: {sampled:?} -> {next_frame:?}"
351        );
352        assert!((next_frame.stretch * next_frame.ortho - 1.0).abs() < 1e-4);
353    }
354
355    #[test]
356    fn controlled_retargets_wait_until_direct_manipulation_ends() {
357        let (_runtime, axis) = axis(10.0);
358        axis.begin(40.0, Some(0));
359        axis.settle_to(90.0, LiquidMotion::snappy());
360        assert_eq!(axis.value(), 40.0);
361        axis.release_to(90.0, Some(16), LiquidMotion::snappy());
362        assert!(!axis.is_dragging());
363        assert_eq!(axis.animation.borrow().target(), 90.0);
364    }
365
366    #[test]
367    fn continuous_release_stops_translation_without_erasing_fluid_velocity() {
368        let (_runtime, axis) = axis(0.0);
369        axis.runtime.drain_frame_callbacks(1_000_000);
370        axis.begin(0.0, Some(0));
371        axis.move_to(80.0, Some(16));
372        let moving = axis.liquid_pose();
373
374        axis.finish_at(80.0, Some(17));
375        assert!(!axis.is_dragging());
376        assert_eq!(axis.value(), 80.0);
377        assert!(moving.speed > 0.0);
378
379        let mut relaxed = moving;
380        for frame in 2..=12 {
381            axis.runtime.drain_frame_callbacks(frame * 17_000_000);
382            assert_eq!(axis.value(), 80.0, "frame {frame} backtracked");
383            relaxed = axis.liquid_pose();
384        }
385        assert!(
386            relaxed.speed < moving.speed,
387            "shape velocity must relax even though translation stops"
388        );
389    }
390
391    #[test]
392    fn released_flight_is_critically_damped() {
393        // Stiffness 500 ~= 90% travel at ~175 ms: the reference bottom-bar
394        // transfer arrives in ~170 ms with no visible overshoot.
395        let AnimationType::Spring(spec) = LiquidMotion::glide() else {
396            panic!("released flight must use a spring");
397        };
398        assert_eq!(spec.damping_ratio, 1.0);
399        assert_eq!(spec.stiffness, 500.0);
400    }
401}