cranpose-ui 0.1.84

UI primitives for Cranpose
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
//! Pinch-to-zoom / pan state and the `Modifier::zoomable` gesture modifier.
//!
//! # Overview
//! [`ZoomState`] is a pure transform model (scale + offset) mirroring the
//! [`ScrollState`](crate::ScrollState) pattern: reactive `MutableState`
//! internals so composables and lazy `graphics_layer` closures observe
//! changes, plus non-reactive accessors for gesture handlers.
//!
//! The app renders the transform with the existing graphics-layer pipeline:
//!
//! ```text
//! let zoom = ZoomState::new();
//! Image(
//!     Modifier::empty()
//!         .fill_max_size()
//!         .zoomable(zoom.clone())
//!         .graphics_layer(move || zoom.layer()),
//!     ...
//! );
//! ```
//!
//! # Gestures
//! - **Two-finger pinch** (Android/touch): scale about the finger centroid,
//!   plus centroid pan. Activates immediately when the second finger lands.
//! - **One-finger pan**: activates after the drag threshold, and only while
//!   the content is zoomed in (`scale > 1`) so an unzoomed zoomable never
//!   steals drags from an enclosing scrollable.
//! - **Double tap**: resets a transformed state back to identity.
//! - **Ctrl+wheel / trackpad pinch** (desktop, web): discrete
//!   [`PointerEventKind::Zoom`] steps about the cursor.
//!
//! # Pan gating
//! ALL pan — one-finger drags and the two-finger pinch centroid — is inert
//! while `scale <= 1`: [`ZoomState::apply_transform`] clamps the offset back
//! to zero whenever the resulting scale is at (or below) identity, so a pinch
//! that zooms back out never strands the content at a stray offset.
//!
//! # Coordinate space
//! Gesture math runs in window (global) coordinates, which stay stable while
//! the element's own graphics layer is being transformed. The focal-point
//! anchoring is therefore exact for zoomable surfaces positioned at the
//! window origin (the fullscreen viewer case) and approximate otherwise.

use crate::modifier::{Modifier, PointerEventKind};
use cranpose_core::{ownedMutableStateOf, OwnedMutableState};
use cranpose_foundation::nodes::input::gestures::{TransformGesture, TransformGestureEvent};
use cranpose_foundation::DRAG_THRESHOLD;
use cranpose_ui_graphics::{GraphicsLayer, Point, TransformOrigin};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use web_time::Instant;

/// Scale factors closer to 1.0 than this are treated as "not zoomed".
const SCALE_EPSILON: f32 = 1e-3;

/// Maximum time between the taps of a double-tap, in milliseconds
/// (matches Android's `ViewConfiguration` DOUBLE_TAP_TIMEOUT).
const DOUBLE_TAP_TIMEOUT_MS: i64 = 300;

/// Maximum distance between the taps of a double-tap, in dp
/// (matches Android's `ViewConfiguration` doubleTapSlop).
const DOUBLE_TAP_SLOP: f32 = 100.0;

fn distance(a: Point, b: Point) -> f32 {
    let dx = b.x - a.x;
    let dy = b.y - a.y;
    (dx * dx + dy * dy).sqrt()
}

/// Shared zoom/pan transform state for `Modifier::zoomable`.
///
/// Cloning shares the same underlying state (like `ScrollState`).
#[derive(Clone)]
pub struct ZoomState {
    inner: Rc<ZoomStateInner>,
}

struct ZoomStateInner {
    /// Uniform content scale factor. Reactive so composables and lazy
    /// graphics-layer closures re-evaluate when it changes.
    scale: OwnedMutableState<f32>,
    /// Content translation in dp, applied after scaling about the top-left
    /// origin: a content point `c` is displayed at `c * scale + offset`.
    offset_x: OwnedMutableState<f32>,
    offset_y: OwnedMutableState<f32>,
    min_scale: Cell<f32>,
    max_scale: Cell<f32>,
}

impl Default for ZoomState {
    fn default() -> Self {
        Self::new()
    }
}

impl ZoomState {
    /// Creates a state at scale 1.0 with a 1.0..=8.0 zoom range.
    pub fn new() -> Self {
        Self::with_scale_range(1.0, 8.0)
    }

    /// Creates a state at scale 1.0 clamping zoom to `min_scale..=max_scale`.
    pub fn with_scale_range(min_scale: f32, max_scale: f32) -> Self {
        assert!(
            min_scale > 0.0 && max_scale >= min_scale,
            "invalid zoom range {min_scale}..{max_scale}"
        );
        Self {
            inner: Rc::new(ZoomStateInner {
                scale: ownedMutableStateOf(1.0f32.clamp(min_scale, max_scale)),
                offset_x: ownedMutableStateOf(0.0f32),
                offset_y: ownedMutableStateOf(0.0f32),
                min_scale: Cell::new(min_scale),
                max_scale: Cell::new(max_scale),
            }),
        }
    }

    /// Stable identity of this state (shared across clones).
    pub fn id(&self) -> u64 {
        Rc::as_ptr(&self.inner) as usize as u64
    }

    /// Current scale (reactive — subscribes the caller to changes).
    pub fn scale(&self) -> f32 {
        self.inner.scale.with(|s| *s)
    }

    /// Current scale without snapshot subscription.
    pub fn scale_non_reactive(&self) -> f32 {
        self.inner.scale.get_non_reactive()
    }

    /// Current pan offset in dp (reactive).
    pub fn offset(&self) -> Point {
        Point {
            x: self.inner.offset_x.with(|v| *v),
            y: self.inner.offset_y.with(|v| *v),
        }
    }

    /// Current pan offset without snapshot subscription.
    pub fn offset_non_reactive(&self) -> Point {
        Point {
            x: self.inner.offset_x.get_non_reactive(),
            y: self.inner.offset_y.get_non_reactive(),
        }
    }

    pub fn min_scale(&self) -> f32 {
        self.inner.min_scale.get()
    }

    pub fn max_scale(&self) -> f32 {
        self.inner.max_scale.get()
    }

    /// Whether the content is currently transformed away from identity.
    pub fn is_transformed(&self) -> bool {
        let offset = self.offset_non_reactive();
        (self.scale_non_reactive() - 1.0).abs() > SCALE_EPSILON
            || offset.x != 0.0
            || offset.y != 0.0
    }

    /// Whether the content is currently zoomed in beyond identity.
    ///
    /// Pan gestures only apply while this is `true`: an image at (or below)
    /// its natural size has nothing to pan, and drags over it belong to
    /// enclosing scrollables.
    pub fn is_zoomed_in(&self) -> bool {
        self.scale_non_reactive() > 1.0 + SCALE_EPSILON
    }

    /// Sets the scale directly (clamped to the configured range).
    pub fn set_scale(&self, scale: f32) {
        let clamped = scale.clamp(self.min_scale(), self.max_scale());
        self.inner.scale.set(clamped);
    }

    /// Sets the pan offset directly.
    pub fn set_offset(&self, offset: Point) {
        self.inner.offset_x.set(offset.x);
        self.inner.offset_y.set(offset.y);
    }

    /// Resets to identity (scale clamped into range, zero offset).
    pub fn reset(&self) {
        self.set_scale(1.0);
        self.set_offset(Point { x: 0.0, y: 0.0 });
    }

    /// Applies one gesture step: zoom by `zoom` about `centroid`, then pan.
    ///
    /// `centroid` and `pan` are in the element's display frame; for finger
    /// gestures the anchor must be the centroid of the pointers BEFORE the
    /// step (as reported by `TransformGestureEvent::Transform`). With the
    /// top-left-origin layer produced by [`ZoomState::layer`], a content
    /// point `c` renders at `p = c * scale + offset`; this update applies
    /// `p' = zoom * (p - centroid) + centroid + pan`, which keeps the
    /// content glued to the fingers.
    ///
    /// Pan is inert while not zoomed in: whenever the resulting scale is at
    /// (or below) identity the offset is clamped back to zero, so a pinch
    /// that zooms out to `scale <= 1` — or a pure centroid pan at identity —
    /// never leaves the content stranded at a stray offset.
    pub fn apply_transform(&self, centroid: Point, pan: Point, zoom: f32) {
        let old_scale = self.scale_non_reactive();
        let new_scale = (old_scale * zoom).clamp(self.min_scale(), self.max_scale());
        let effective_zoom = new_scale / old_scale;
        let old_offset = self.offset_non_reactive();

        let new_offset = if new_scale <= 1.0 + SCALE_EPSILON {
            // Not zoomed in: pan (finger delta AND focal-point correction)
            // must not displace the content.
            Point { x: 0.0, y: 0.0 }
        } else {
            Point {
                x: centroid.x - (centroid.x - old_offset.x) * effective_zoom + pan.x,
                y: centroid.y - (centroid.y - old_offset.y) * effective_zoom + pan.y,
            }
        };

        if new_scale != old_scale {
            self.inner.scale.set(new_scale);
        }
        if new_offset != old_offset {
            self.set_offset(new_offset);
        }
    }

    /// Builds the [`GraphicsLayer`] rendering this transform.
    ///
    /// Reads the state reactively, so it is meant for the lazy
    /// `Modifier::graphics_layer(move || state.layer())` form.
    pub fn layer(&self) -> GraphicsLayer {
        let scale = self.scale();
        let offset = self.offset();
        GraphicsLayer {
            scale_x: scale,
            scale_y: scale,
            translation_x: offset.x,
            translation_y: offset.y,
            transform_origin: TransformOrigin::new(0.0, 0.0),
            ..Default::default()
        }
    }
}

/// Per-modifier gesture bookkeeping for `zoomable`.
struct ZoomGestureState {
    tracker: TransformGesture,
    /// Whether the gesture crossed into actively transforming (consuming).
    active: bool,
    /// Accumulated single-finger travel for the drag threshold.
    travel: f32,
    /// Down position of a potential tap (single finger, in window coords).
    tap_down: Option<Point>,
    /// Time and position of the previous completed tap, for double-tap
    /// detection.
    last_tap: Option<(i64, Point)>,
    /// Timestamp epoch for platforms whose events carry no input timestamps.
    fallback_epoch: Instant,
}

impl Default for ZoomGestureState {
    fn default() -> Self {
        Self {
            tracker: TransformGesture::default(),
            active: false,
            travel: 0.0,
            tap_down: None,
            last_tap: None,
            fallback_epoch: Instant::now(),
        }
    }
}

impl ZoomGestureState {
    /// The event's own timestamp when the platform provides one (Android),
    /// falling back to delivery time (desktop mouse, web).
    fn timestamp_ms(&self, time_ms: Option<i64>) -> i64 {
        time_ms.unwrap_or_else(|| self.fallback_epoch.elapsed().as_millis() as i64)
    }

    /// Abandons any tap tracking (drag, pinch, cancel, foreign consumption).
    fn abandon_tap(&mut self) {
        self.tap_down = None;
        self.last_tap = None;
    }
}

impl Modifier {
    /// Makes the element respond to transform gestures, updating `state`.
    ///
    /// Recognizes two-finger pinch/pan (touch), one-finger pan while the
    /// content is zoomed in (`scale > 1`), a double-tap that resets a
    /// transformed state to identity, and [`PointerEventKind::Zoom`] steps
    /// (desktop ctrl+wheel, browser pinch). Pan — including the pinch
    /// centroid — is inert while `scale <= 1`. Rendering is the app's
    /// choice — typically `.graphics_layer(move || state.layer())` on the
    /// same or a child element.
    pub fn zoomable(self, state: ZoomState) -> Self {
        let gesture_state = Rc::new(RefCell::new(ZoomGestureState::default()));
        let key = state.id();

        self.pointer_input(key, move |scope| {
            let state = state.clone();
            let gesture_state = gesture_state.clone();

            async move {
                scope
                    .await_pointer_event_scope(|await_scope| async move {
                        loop {
                            let event = await_scope.await_pointer_event().await;

                            match event.kind {
                                PointerEventKind::Zoom => {
                                    if !event.is_consumed() && event.zoom_delta != 1.0 {
                                        state.apply_transform(
                                            event.global_position,
                                            Point { x: 0.0, y: 0.0 },
                                            event.zoom_delta,
                                        );
                                        event.consume();
                                    }
                                }
                                PointerEventKind::Cancel => {
                                    // Platforms cancel whole gestures, not
                                    // individual pointers.
                                    let mut gs = gesture_state.borrow_mut();
                                    gs.tracker.reset();
                                    gs.active = false;
                                    gs.travel = 0.0;
                                    gs.abandon_tap();
                                }
                                PointerEventKind::Down
                                | PointerEventKind::Move
                                | PointerEventKind::Up => {
                                    let mut gs = gesture_state.borrow_mut();

                                    if event.is_consumed() {
                                        // Another handler owns this pointer
                                        // sequence; abandon the gesture.
                                        gs.tracker.reset();
                                        gs.active = false;
                                        gs.travel = 0.0;
                                        gs.abandon_tap();
                                        continue;
                                    }

                                    // Track in window coordinates: they stay
                                    // stable while our own layer transform
                                    // changes mid-gesture.
                                    let tracked =
                                        event.copy_with_local_position(event.global_position);
                                    let step = gs.tracker.handle_event(&tracked);

                                    if event.kind == PointerEventKind::Down {
                                        if gs.tracker.pointer_count() >= 2 {
                                            // Pinch begins: transform gestures
                                            // own the sequence immediately.
                                            gs.active = true;
                                            // A multi-finger gesture is never
                                            // a tap.
                                            gs.tap_down = None;
                                        } else {
                                            gs.travel = 0.0;
                                            gs.tap_down = Some(event.global_position);
                                        }
                                        // Secondary fingers are meaningless to
                                        // single-pointer handlers; keep them.
                                        if event.id != 0 {
                                            event.consume();
                                        }
                                        continue;
                                    }

                                    if event.kind == PointerEventKind::Up && event.id == 0 {
                                        // Double-tap resets a transformed
                                        // state back to identity.
                                        let now_ms = gs.timestamp_ms(event.time_ms);
                                        let up_position = event.global_position;
                                        let is_tap = !gs.active
                                            && gs.tap_down.is_some_and(|down| {
                                                distance(down, up_position) <= DRAG_THRESHOLD
                                            });
                                        gs.tap_down = None;
                                        if is_tap {
                                            let is_double_tap = gs.last_tap.is_some_and(
                                                |(tap_ms, tap_position)| {
                                                    now_ms.saturating_sub(tap_ms)
                                                        <= DOUBLE_TAP_TIMEOUT_MS
                                                        && distance(tap_position, up_position)
                                                            <= DOUBLE_TAP_SLOP
                                                },
                                            );
                                            if is_double_tap {
                                                gs.last_tap = None;
                                                if state.is_transformed() {
                                                    state.reset();
                                                    event.consume();
                                                }
                                            } else {
                                                gs.last_tap = Some((now_ms, up_position));
                                            }
                                        } else {
                                            gs.last_tap = None;
                                        }
                                    }

                                    match step {
                                        TransformGestureEvent::Transform {
                                            pan,
                                            zoom,
                                            centroid,
                                            pointer_count,
                                        } => {
                                            if pointer_count >= 2 {
                                                gs.active = true;
                                            } else if !gs.active && state.is_zoomed_in() {
                                                // One-finger pan only grabs the
                                                // gesture while zoomed in
                                                // (scale > 1), so unzoomed
                                                // zoomables never steal scrolls.
                                                gs.travel += (pan.x * pan.x + pan.y * pan.y).sqrt();
                                                if gs.travel > DRAG_THRESHOLD {
                                                    gs.active = true;
                                                }
                                            }

                                            if gs.active {
                                                state.apply_transform(centroid, pan, zoom);
                                                event.consume();
                                            }
                                        }
                                        TransformGestureEvent::Ended => {
                                            let was_active = gs.active;
                                            gs.active = false;
                                            gs.travel = 0.0;
                                            if was_active {
                                                event.consume();
                                            }
                                        }
                                        TransformGestureEvent::None => {
                                            if event.id != 0
                                                || (gs.active
                                                    && matches!(
                                                        event.kind,
                                                        PointerEventKind::Up
                                                            | PointerEventKind::Cancel
                                                    ))
                                            {
                                                event.consume();
                                            }
                                        }
                                    }
                                }
                                PointerEventKind::Scroll
                                | PointerEventKind::RotaryScrollPre
                                | PointerEventKind::RotaryScroll
                                | PointerEventKind::Enter
                                | PointerEventKind::Exit => {}
                            }
                        }
                    })
                    .await;
            }
        })
    }
}

#[cfg(test)]
#[path = "tests/zoom_tests.rs"]
mod tests;