Skip to main content

uzor_framework/widgets/
mobile.rs

1//! Drives the mobile shell widgets of [`uzor::ui::mobile`] from this frame's input: a
2//! finger (the touch recogniser's pans, [`VisualView::gestures`]) and the mouse (a press
3//! held on a hit target and moved) both become one [`Drag`] stream, which moves a
4//! [`SheetState`], [`DrawerState`] or [`SwipeState`]. Releases carry a velocity, so a
5//! flick snaps to the next stop with either input.
6//!
7//! The keyboard and the safe area come from the view too: [`composer_rect`] puts the
8//! composer over the soft keyboard (or the home indicator), [`reveal_field`] says how far
9//! to scroll a focused field out from under it.
10
11use uzor::types::Rect;
12use uzor::ui::mobile::{DrawerState, SheetState, SwipeState, DRAWER_W};
13
14use crate::handle::VisualView;
15use crate::types::gesture::{Axis, Edge, Gesture, GestureConfig, VelocityTracker};
16use uzor::WidgetId;
17use crate::types::spec::Spec;
18use crate::types::window::Point;
19
20/// One step of a drag.
21#[derive(Clone, Copy, Debug, PartialEq)]
22pub enum Drag {
23    /// The drag began (past the slop).
24    Start {
25        /// Where the press went down.
26        origin: (f64, f64),
27        /// Where it is now.
28        pos: (f64, f64),
29    },
30    /// It moved.
31    Move {
32        /// Where it is.
33        pos: (f64, f64),
34        /// Motion since the last step.
35        delta: (f64, f64),
36    },
37    /// It ended.
38    End {
39        /// Where it lifted.
40        pos: (f64, f64),
41        /// Release velocity, px/s.
42        velocity: (f64, f64),
43    },
44}
45
46/// What may start a drag.
47#[derive(Clone, Copy, Debug, PartialEq)]
48pub enum Grip {
49    /// A press on this hit target (mouse) or a pan that started inside `rect` (touch).
50    Target(Rect),
51    /// A pan from this window edge (touch), or a mouse press within `width` px of it.
52    Edge(Edge, f64),
53}
54
55#[derive(Clone, Copy, Debug, PartialEq)]
56enum Src {
57    Touch,
58    Mouse,
59}
60
61/// Turns touch pans and mouse drags on one target into [`Drag`] steps. Keep one per
62/// draggable thing (sheet handle, drawer edge, a row) across frames.
63#[derive(Clone, Debug, Default)]
64pub struct DragTracker {
65    active: Option<Src>,
66    /// Mouse: where the press began, whether it left the slop, last position.
67    press: Option<(f64, f64)>,
68    last: (f64, f64),
69    vel: VelocityTracker,
70    moved: bool,
71    swallow: bool,
72}
73
74impl DragTracker {
75    /// Whether a drag is in progress.
76    pub fn active(&self) -> bool {
77        self.active.is_some() && self.moved
78    }
79
80    /// True once after a mouse drag ended on the target: the release click that
81    /// follows is the drag's, not a tap (ignore that click).
82    pub fn take_swallow(&mut self) -> bool {
83        std::mem::take(&mut self.swallow)
84    }
85
86    /// The drag steps of this frame. `id` is the hit target's id (for the mouse press),
87    /// `axis` limits touch pans to that direction (`None`: any), `now` is the frame
88    /// time in seconds.
89    pub fn update<S: Spec>(&mut self, view: &VisualView<S>, id: &WidgetId, grip: Grip, axis: Option<Axis>, now: f64) -> Vec<Drag> {
90        let cfg = GestureConfig::default();
91        let mut out = Vec::new();
92        // Touch: the recogniser's pans.
93        for g in view.gestures() {
94            match *g {
95                Gesture::PanStart { origin, pos, axis: a, edge } if self.active.is_none() => {
96                    let ok_axis = axis.is_none_or(|x| x == a);
97                    let ok = match grip {
98                        Grip::Target(r) => contains(r, origin),
99                        Grip::Edge(e, _) => edge == Some(e),
100                    };
101                    if ok && ok_axis {
102                        self.active = Some(Src::Touch);
103                        self.moved = true;
104                        self.last = (pos.x, pos.y);
105                        out.push(Drag::Start { origin: (origin.x, origin.y), pos: (pos.x, pos.y) });
106                        // The slop already travelled counts.
107                        out.push(Drag::Move { pos: (pos.x, pos.y), delta: (pos.x - origin.x, pos.y - origin.y) });
108                    }
109                }
110                Gesture::Pan { pos, delta, .. } if self.active == Some(Src::Touch) => {
111                    self.last = (pos.x, pos.y);
112                    out.push(Drag::Move { pos: (pos.x, pos.y), delta });
113                }
114                Gesture::PanEnd { pos, velocity, .. } if self.active == Some(Src::Touch) => {
115                    self.active = None;
116                    self.moved = false;
117                    out.push(Drag::End { pos: (pos.x, pos.y), velocity });
118                }
119                _ => {}
120            }
121        }
122        if self.active == Some(Src::Touch) || view.coarse_pointer() {
123            return out;
124        }
125        // Mouse: a held press that moves.
126        let p = view.raw_pointer();
127        let held = view.is_pressed(id) || (self.active == Some(Src::Mouse) && view.button_down());
128        let edge_press = |pt: (f64, f64)| match grip {
129            Grip::Edge(Edge::Left, w) => pt.0 <= w,
130            _ => false,
131        };
132        match (held, p) {
133            (true, Some(pt)) => {
134                if self.press.is_none() {
135                    self.press = Some(view.press_origin().unwrap_or(pt));
136                    self.last = self.press.unwrap_or(pt);
137                    self.vel.reset();
138                    self.moved = false;
139                    self.active = Some(Src::Mouse);
140                }
141                let o = self.press.unwrap_or(pt);
142                self.vel.add(now, Point::new(pt.0, pt.1), &cfg);
143                if !self.moved {
144                    let (dx, dy) = (pt.0 - o.0, pt.1 - o.1);
145                    let along = match axis {
146                        Some(Axis::Horizontal) => dx.abs() > cfg.slop && dx.abs() > dy.abs(),
147                        Some(Axis::Vertical) => dy.abs() > cfg.slop && dy.abs() > dx.abs(),
148                        None => dx.hypot(dy) > cfg.slop,
149                    };
150                    if along {
151                        self.moved = true;
152                        out.push(Drag::Start { origin: o, pos: pt });
153                        out.push(Drag::Move { pos: pt, delta: (dx, dy) });
154                        self.last = pt;
155                    }
156                } else if pt != self.last {
157                    out.push(Drag::Move { pos: pt, delta: (pt.0 - self.last.0, pt.1 - self.last.1) });
158                    self.last = pt;
159                }
160            }
161            (true, None) => {}
162            (false, _) => {
163                if self.active == Some(Src::Mouse) {
164                    if self.moved {
165                        let v = self.vel.velocity(now, &cfg);
166                        out.push(Drag::End { pos: self.last, velocity: v });
167                        self.swallow = true;
168                    }
169                    self.active = None;
170                    self.moved = false;
171                    self.press = None;
172                }
173                let _ = edge_press;
174            }
175        }
176        out
177    }
178}
179
180fn contains(r: Rect, p: Point) -> bool {
181    p.x >= r.x && p.x < r.x + r.width && p.y >= r.y && p.y < r.y + r.height
182}
183
184/// Feed `steps` to a bottom sheet in a viewport `vh` tall; true while it needs frames.
185pub fn drive_sheet(st: &mut SheetState, steps: &[Drag], vh: f64, dt: f64) -> bool {
186    for s in steps {
187        match *s {
188            Drag::Start { .. } => {}
189            Drag::Move { delta, .. } => st.drag_by(delta.1, vh),
190            Drag::End { velocity, .. } => {
191                st.release(velocity.1, vh);
192            }
193        }
194    }
195    st.dragging() | st.step(dt, vh)
196}
197
198/// Feed `steps` to an edge drawer; true while it needs frames.
199pub fn drive_drawer(st: &mut DrawerState, steps: &[Drag], dt: f64) -> bool {
200    for s in steps {
201        match *s {
202            Drag::Start { .. } => {}
203            Drag::Move { delta, .. } => st.drag_by(delta.0, DRAWER_W),
204            Drag::End { velocity, .. } => {
205                st.release(velocity.0);
206            }
207        }
208    }
209    st.dragging() | st.step(dt, DRAWER_W)
210}
211
212/// Feed `steps` to a swipe row with `left_w` / `right_w` px of actions; true while it
213/// needs frames.
214pub fn drive_swipe(st: &mut SwipeState, steps: &[Drag], left_w: f64, right_w: f64, dt: f64) -> bool {
215    for s in steps {
216        match *s {
217            Drag::Start { .. } => {}
218            Drag::Move { delta, .. } => st.drag_by(delta.0, left_w, right_w),
219            Drag::End { velocity, .. } => {
220                st.release(velocity.0, left_w, right_w);
221            }
222        }
223    }
224    st.dragging() | st.step(dt)
225}
226
227/// The composer's rect in `viewport`: `height` tall, its bottom on the soft keyboard
228/// when it is up, else on the bottom safe area (home indicator).
229pub fn composer_rect<S: Spec>(view: &VisualView<S>, viewport: Rect, height: f64) -> Rect {
230    let bottom = uzor::ui::mobile::composer_bottom(viewport.y, viewport.height, view.keyboard(), view.safe_area().bottom);
231    Rect::new(viewport.x, bottom - height, viewport.width, height)
232}
233
234/// How far to scroll (px, positive = content up) so the focused field at `field`
235/// clears the soft keyboard by 8 px in `viewport` (0 when visible or no keyboard).
236pub fn reveal_field<S: Spec>(view: &VisualView<S>, viewport: Rect, field: Rect) -> f64 {
237    if view.keyboard() <= 0.0 {
238        return 0.0;
239    }
240    uzor::ui::mobile::reveal_above(field.y, field.y + field.height, viewport.y, viewport.height, view.keyboard(), 8.0)
241}
242
243#[cfg(test)]
244mod tests {
245    use super::*;
246    use crate::types::spec::{PanelHome, Spec};
247    use uzor::layout::docking::DockPanel;
248
249    #[derive(Clone, Debug)]
250    struct P;
251    impl DockPanel for P {
252        fn title(&self) -> &str {
253            "m"
254        }
255        fn type_id(&self) -> &'static str {
256            "m"
257        }
258    }
259    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
260    enum Never {}
261    struct T;
262    impl Spec for T {
263        type Panel = P;
264        type Overlay = Never;
265        type Action = Never;
266        fn decode_panel(_home: PanelHome, _type_id: &str) -> Option<P> {
267            Some(P)
268        }
269    }
270
271    fn pan(origin: (f64, f64), path: &[(f64, f64)], v: (f64, f64)) -> Vec<Gesture> {
272        let mut g = vec![Gesture::PanStart { origin: Point::new(origin.0, origin.1), pos: Point::new(path[0].0, path[0].1), axis: Axis::Vertical, edge: None }];
273        let mut last = path[0];
274        for p in &path[1..] {
275            g.push(Gesture::Pan { pos: Point::new(p.0, p.1), delta: (p.0 - last.0, p.1 - last.1), total: (p.0 - origin.0, p.1 - origin.1), edge: None });
276            last = *p;
277        }
278        g.push(Gesture::PanEnd { pos: Point::new(last.0, last.1), velocity: v, edge: None });
279        g
280    }
281
282    #[test]
283    fn a_touch_pan_on_the_handle_moves_and_flicks_the_sheet() {
284        let mut view = VisualView::<T>::default();
285        view.coarse_pointer = true;
286        view.gestures = pan((195.0, 430.0), &[(195.0, 420.0), (195.0, 300.0)], (0.0, -1500.0));
287        let mut tr = DragTracker::default();
288        let steps = tr.update(&view, &WidgetId::from("card:grab"), Grip::Target(Rect::new(0.0, 420.0, 390.0, 24.0)), Some(Axis::Vertical), 1.0);
289        assert!(matches!(steps.first(), Some(Drag::Start { .. })) && matches!(steps.last(), Some(Drag::End { .. })));
290        let mut st = SheetState::default();
291        st.open(uzor::ui::mobile::Detent::Half);
292        drive_sheet(&mut st, &steps, 844.0, 1.0 / 60.0);
293        assert_eq!(st.detent, uzor::ui::mobile::Detent::Full, "flicked up to full");
294        // A pan that starts elsewhere is not the sheet's.
295        let mut tr2 = DragTracker::default();
296        view.gestures = pan((195.0, 700.0), &[(195.0, 690.0)], (0.0, 0.0));
297        assert!(tr2.update(&view, &WidgetId::from("card:grab"), Grip::Target(Rect::new(0.0, 420.0, 390.0, 24.0)), None, 1.0).is_empty());
298    }
299
300    #[test]
301    fn an_edge_pan_opens_the_drawer() {
302        let mut view = VisualView::<T>::default();
303        view.coarse_pointer = true;
304        view.gestures = vec![
305            Gesture::PanStart { origin: Point::new(4.0, 300.0), pos: Point::new(14.0, 300.0), axis: Axis::Horizontal, edge: Some(Edge::Left) },
306            Gesture::Pan { pos: Point::new(200.0, 300.0), delta: (186.0, 0.0), total: (196.0, 0.0), edge: Some(Edge::Left) },
307            Gesture::PanEnd { pos: Point::new(200.0, 300.0), velocity: (100.0, 0.0), edge: Some(Edge::Left) },
308        ];
309        let mut tr = DragTracker::default();
310        let steps = tr.update(&view, &WidgetId::from("edge"), Grip::Edge(Edge::Left, 20.0), Some(Axis::Horizontal), 1.0);
311        let mut d = DrawerState::default();
312        drive_drawer(&mut d, &steps, 1.0 / 60.0);
313        assert!(d.open, "past half: open");
314    }
315
316    #[test]
317    fn a_mouse_drag_swipes_a_row_and_swallows_its_click() {
318        let id = WidgetId::from("chat:1");
319        let mut view = VisualView::<T>::default();
320        view.pressed = Some(id.clone());
321        view.button_down = true;
322        view.press_origin = Some((300.0, 100.0));
323        let mut tr = DragTracker::default();
324        let mut st = SwipeState::default();
325        let mut t = 0.0;
326        for x in [300.0, 296.0, 260.0, 200.0, 150.0] {
327            view.pointer = Some((x, 101.0));
328            t += 1.0 / 60.0;
329            let s = tr.update(&view, &id, Grip::Target(Rect::new(0.0, 66.0, 390.0, 68.0)), Some(Axis::Horizontal), t);
330            drive_swipe(&mut st, &s, 0.0, 234.0, 1.0 / 60.0);
331        }
332        assert!(st.offset < -100.0);
333        view.pressed = None;
334        view.button_down = false;
335        let s = tr.update(&view, &id, Grip::Target(Rect::new(0.0, 66.0, 390.0, 68.0)), Some(Axis::Horizontal), t + 0.016);
336        assert!(matches!(s.as_slice(), [Drag::End { .. }]));
337        drive_swipe(&mut st, &s, 0.0, 234.0, 1.0 / 60.0);
338        assert!(st.is_open());
339        assert!(tr.take_swallow() && !tr.take_swallow());
340    }
341
342    #[test]
343    fn a_still_mouse_press_is_a_click_not_a_drag() {
344        let id = WidgetId::from("row");
345        let mut view = VisualView::<T>::default();
346        view.pressed = Some(id.clone());
347        view.button_down = true;
348        view.press_origin = Some((100.0, 100.0));
349        view.pointer = Some((103.0, 101.0));
350        let mut tr = DragTracker::default();
351        assert!(tr.update(&view, &id, Grip::Target(Rect::new(0.0, 0.0, 390.0, 200.0)), None, 0.0).is_empty());
352        view.pressed = None;
353        view.button_down = false;
354        assert!(tr.update(&view, &id, Grip::Target(Rect::new(0.0, 0.0, 390.0, 200.0)), None, 0.1).is_empty());
355        assert!(!tr.take_swallow());
356    }
357
358    #[test]
359    fn the_composer_rides_the_keyboard() {
360        let mut view = VisualView::<T>::default();
361        view.safe_area = crate::types::window::Insets::new(47.0, 0.0, 34.0, 0.0);
362        let vp = Rect::new(0.0, 0.0, 390.0, 844.0);
363        assert_eq!(composer_rect(&view, vp, 56.0).y, 844.0 - 34.0 - 56.0);
364        view.keyboard = 336.0;
365        assert_eq!(composer_rect(&view, vp, 56.0).y, 844.0 - 336.0 - 56.0);
366        assert_eq!(reveal_field(&view, vp, Rect::new(0.0, 600.0, 390.0, 44.0)), 144.0);
367    }
368}