cranpose-ui 0.1.96

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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
//! SwipeToDismiss composable
//!
//! Mirrors Jetpack Compose's `SwipeToDismissBox` (Material) in spirit: wraps
//! content that can be dragged horizontally; releasing past a threshold
//! animates the content off-screen and fires `on_dismiss`, otherwise the
//! content springs back into place.
//!
//! # Gesture disambiguation
//!
//! The drag capture mirrors the axis-locking rules of the scroll modifier so
//! a `SwipeToDismiss` row inside a vertical `LazyColumn` coexists with the
//! list scroll (children receive pointer events before ancestors):
//!
//! - the swipe captures the gesture only once the *horizontal* travel exceeds
//!   the drag slop while dominating the vertical travel; from then on events
//!   are consumed so the parent scroll abandons the gesture;
//! - a decisively *vertical* start locks the swipe out for the rest of the
//!   gesture, leaving every event unconsumed for the parent to scroll;
//! - taps (no travel beyond the slop) consume nothing, so clickable rows
//!   keep working.

#![allow(non_snake_case)]

use crate::composable;
use crate::modifier::{GraphicsLayer, Modifier, PointerEvent, PointerEventKind};
use crate::subcompose_layout::{Constraints, SubcomposeLayoutScope, SubcomposeMeasureScope};
use crate::widgets::box_widget::{Box, BoxSpec};
use crate::widgets::layout::{BoxWithConstraints, SubcomposeLayout};
use crate::widgets::scopes::BoxWithConstraintsScope;
use cranpose_animation::{spring, Animatable, AnimationType, Spring};
use cranpose_core::internal::FrameCallbackRegistration;
use cranpose_core::{
    with_current_composer, NodeId, Owned, OwnedMutableState, RuntimeHandle, SlotId,
};
use cranpose_foundation::DRAG_THRESHOLD;
use cranpose_ui_layout::Placement;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::sync::atomic::{AtomicU64, Ordering};

/// Offset (logical px) within which a dismiss animation counts as settled.
const DISMISS_SETTLE_EPSILON: f32 = 0.5;

/// Height-scale (fraction of the natural height) at or below which the
/// post-dismiss collapse is considered complete.
const COLLAPSE_SETTLE_EPSILON: f32 = 0.01;

/// Spring used both for the dismissal fling and the spring-back.
fn swipe_spring() -> AnimationType {
    spring(Spring::DampingRatioNoBouncy, Spring::StiffnessMediumLow)
}

/// Which edge the dismiss background is revealed on, i.e. the side the row is
/// being swiped away from. Passed to the [`SwipeToDismissSpec::with_background`]
/// closure so its label/icon can follow the swipe direction instead of being
/// pinned to one side.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SwipeDismissSide {
    /// The row is moving right (offset > 0); the background shows on the leading
    /// (start / left-in-LTR) edge.
    Start,
    /// The row is moving left (offset < 0); the background shows on the trailing
    /// (end / right-in-LTR) edge.
    End,
}

/// Directions accepted by a swipe-dismiss container.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SwipeDismissDirection {
    #[default]
    Both,
    StartToEnd,
    EndToStart,
}

/// Boxed background closure, invoked each frame with the current
/// [`SwipeDismissSide`] so the reveal can follow the swipe direction.
type BackgroundFn = Rc<RefCell<dyn FnMut(SwipeDismissSide)>>;

/// Configuration for [`SwipeToDismiss`].
#[derive(Clone)]
pub struct SwipeToDismissSpec {
    /// Fraction of the content width the offset must exceed on release for
    /// the row to dismiss (default `0.5`). Clamped to `(0, 1]`.
    pub threshold_fraction: f32,
    /// Optional content drawn behind the swiped row (e.g. a delete bin),
    /// revealed as the row slides away. Receives the [`SwipeDismissSide`] the
    /// row is being swiped toward so the reveal can follow the swipe direction.
    background: Option<BackgroundFn>,
    /// Identity of the wrapped content (e.g. the row's database id). When a
    /// composition slot is reused for a DIFFERENT item — unkeyed lazy-list
    /// rows all shift up after a removal — the remembered swipe state must
    /// not leak onto the new item: without a key, the next row inherits the
    /// dismissed row's displacement, revealed background and collapsed
    /// height ("items go shuffled, red boxes stick").
    ///
    /// Inside a keyed lazy list this is filled in from the item's own key, so
    /// a row states its identity once, where the list already states it. Set it
    /// explicitly only for a row that is not a lazy item, or whose identity is
    /// not the one the list is keyed by.
    pub key: Option<u64>,
    /// Caller-owned swipe state, from [`rememberSwipeDismissState`].
    ///
    /// Supply one to read the swipe as it happens — a label that fades in with
    /// it, a count of what is about to go, an undo bar after it lands — or to
    /// return a row to rest from elsewhere on the screen. Left unset, the row
    /// owns its own state.
    pub state: Option<SwipeDismissState>,
    pub direction: SwipeDismissDirection,
    pub edge_width: Option<f32>,
    pub collapse_after_dismiss: bool,
    pub enabled: bool,
}

impl SwipeToDismissSpec {
    pub fn new() -> Self {
        Self {
            threshold_fraction: 0.5,
            background: None,
            key: None,
            state: None,
            direction: SwipeDismissDirection::Both,
            edge_width: None,
            collapse_after_dismiss: true,
            enabled: true,
        }
    }

    /// Declares the identity of the wrapped content. When the key changes,
    /// the swipe state resets to rest — the new item starts untouched.
    ///
    /// A row inside a keyed lazy list already has an identity and does not
    /// need this.
    pub fn with_key(mut self, key: u64) -> Self {
        self.key = Some(key);
        self
    }

    /// Uses caller-owned swipe state, so the swipe can be read and reset from
    /// outside the row.
    pub fn with_state(mut self, state: SwipeDismissState) -> Self {
        self.state = Some(state);
        self
    }

    /// Sets the dismiss threshold as a fraction of the content width.
    pub fn with_threshold_fraction(mut self, fraction: f32) -> Self {
        self.threshold_fraction = fraction;
        self
    }

    /// Sets the background content revealed behind the swiped row. The closure
    /// receives the [`SwipeDismissSide`] the row is currently being swiped
    /// toward, so it can align its label/icon to the revealed edge.
    pub fn with_background(mut self, background: impl FnMut(SwipeDismissSide) + 'static) -> Self {
        self.background = Some(Rc::new(RefCell::new(background)));
        self
    }

    pub fn with_direction(mut self, direction: SwipeDismissDirection) -> Self {
        self.direction = direction;
        self
    }

    pub fn from_edge(mut self, width: f32) -> Self {
        self.edge_width = Some(width.max(0.0));
        self
    }

    pub fn with_collapse_after_dismiss(mut self, collapse: bool) -> Self {
        self.collapse_after_dismiss = collapse;
        self
    }

    pub fn with_enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }
}

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

/// Phase of the swipe gesture state machine.
#[derive(Clone, Copy, Debug, PartialEq)]
enum SwipePhase {
    /// No active pointer sequence.
    Idle,
    /// Pointer down, axis not decided yet.
    Tracking {
        down_x: f32,
        down_y: f32,
        start_offset: f32,
    },
    /// Horizontal axis won: the swipe owns the gesture and consumes events.
    Dragging { down_x: f32, start_offset: f32 },
    /// Vertical axis won decisively: never capture for this gesture.
    LockedOut,
}

/// Axis decision for the initial slop check. Mirrors the scroll modifier:
/// the main axis captures when it exceeds the slop *and* dominates; the
/// cross axis locks out when it exceeds the slop and strictly dominates.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum SwipeAxisDecision {
    Undecided,
    Horizontal,
    Vertical,
}

/// Decides the gesture axis from the total travel since pointer down.
pub(crate) fn decide_axis(total_dx: f32, total_dy: f32, slop: f32) -> SwipeAxisDecision {
    let horizontal = total_dx.abs();
    let vertical = total_dy.abs();
    if horizontal > slop && horizontal >= vertical {
        SwipeAxisDecision::Horizontal
    } else if vertical > slop && vertical > horizontal {
        SwipeAxisDecision::Vertical
    } else {
        SwipeAxisDecision::Undecided
    }
}

/// Where the released row should animate to: `Some(±width)` when the offset
/// crossed the dismiss threshold, `None` to spring back to rest.
pub(crate) fn dismissal_target(offset: f32, width: f32, threshold_fraction: f32) -> Option<f32> {
    if !width.is_finite() || width <= 0.0 {
        return None;
    }
    let threshold = width * threshold_fraction.clamp(f32::EPSILON, 1.0);
    (offset.abs() >= threshold).then(|| width * offset.signum())
}

/// Clamps the dragged offset so the content cannot travel further than one
/// full width in either direction.
pub(crate) fn clamp_offset(offset: f32, width: f32) -> f32 {
    if width.is_finite() && width > 0.0 {
        offset.clamp(-width, width)
    } else {
        offset
    }
}

static NEXT_SWIPE_ID: AtomicU64 = AtomicU64::new(0);

/// State shared between the composable (which reads the animated offset) and
/// the pointer-input handler (which drives it). Main-thread only.
struct SwipeToDismissController {
    /// Stable key for the pointer-input modifier.
    id: u64,
    runtime: RuntimeHandle,
    /// Animated horizontal offset of the content in logical px.
    offset: RefCell<Animatable<f32>>,
    /// Reactive flag mirroring `|offset| > 0`, read inside the subcompose so
    /// the row's background is *composed* only while the row is displaced.
    /// Conditional composition (adding/removing the background node) re-applies
    /// when the slot recomposes, unlike a layout-offset value change which is
    /// placement-cached — so this bool, not the raw offset, gates the reveal.
    /// A plain bool also recomposes only on rest/displaced transitions rather
    /// than on every drag frame. Without gating, the always-composed background
    /// flashes through content that fades in with alpha < 1 during an entrance.
    revealed: OwnedMutableState<bool>,
    /// Height scale of the row (fraction of its natural height). `1.0` at rest;
    /// after a successful dismiss it animates to `0.0` so the row collapses and
    /// leaves no gap — and no red background strip — even if the host removes
    /// the item a few frames later.
    collapse: RefCell<Animatable<f32>>,
    phase: Cell<SwipePhase>,
    /// Content width in logical px, refreshed from the incoming constraints.
    width_px: Cell<f32>,
    threshold_fraction: Cell<f32>,
    /// Refreshed every recomposition so the latest captured environment runs.
    on_dismiss: RefCell<Option<Rc<dyn Fn()>>>,
    /// `on_dismiss` fired for the current dismissal (fires at most once).
    /// Observable: a caller watching [`SwipeDismissState`] reacts to a row
    /// leaving without being handed a callback.
    dismissed: OwnedMutableState<bool>,
    /// The row's layout node, so the collapse watcher can force a re-measure
    /// each frame as the height shrinks. Set on every recomposition.
    node_id: Cell<Option<NodeId>>,
    /// Frame callback watching the dismiss animation for completion.
    settle_watcher: RefCell<Option<FrameCallbackRegistration>>,
    /// Frame callback driving the post-dismiss height collapse.
    collapse_watcher: RefCell<Option<FrameCallbackRegistration>>,
    /// Identity of the content this controller's state belongs to (from
    /// [`SwipeToDismissSpec::with_key`]); state resets when it changes.
    identity: Cell<Option<u64>>,
    active_pointer: Cell<Option<u64>>,
    direction: Cell<SwipeDismissDirection>,
    edge_width: Cell<Option<f32>>,
    collapse_after_dismiss: Cell<bool>,
    enabled: Cell<bool>,
}

impl SwipeToDismissController {
    fn new(runtime: RuntimeHandle) -> Rc<Self> {
        Rc::new(Self {
            id: NEXT_SWIPE_ID.fetch_add(1, Ordering::Relaxed),
            offset: RefCell::new(Animatable::new(0.0, runtime.clone())),
            revealed: OwnedMutableState::with_runtime(false, runtime.clone()),
            collapse: RefCell::new(Animatable::new(1.0, runtime.clone())),
            dismissed: OwnedMutableState::with_runtime(false, runtime.clone()),
            runtime,
            phase: Cell::new(SwipePhase::Idle),
            width_px: Cell::new(f32::NAN),
            threshold_fraction: Cell::new(0.5),
            on_dismiss: RefCell::new(None),
            node_id: Cell::new(None),
            settle_watcher: RefCell::new(None),
            collapse_watcher: RefCell::new(None),
            identity: Cell::new(None),
            active_pointer: Cell::new(None),
            direction: Cell::new(SwipeDismissDirection::Both),
            edge_width: Cell::new(None),
            collapse_after_dismiss: Cell::new(true),
            enabled: Cell::new(true),
        })
    }

    /// Instantly return to the untouched state. Used when the composition
    /// slot is reused for a different item (the spec key changed): the new
    /// item must not inherit the old item's displacement, reveal, collapse
    /// or a pending dismissal.
    fn reset_to_rest(&self) {
        self.settle_watcher.borrow_mut().take();
        self.collapse_watcher.borrow_mut().take();
        self.offset.borrow_mut().snapTo(0.0);
        self.collapse.borrow_mut().snapTo(1.0);
        self.phase.set(SwipePhase::Idle);
        self.active_pointer.set(None);
        self.set_dismissed(false);
        self.set_revealed(false);
    }

    fn current_offset(&self) -> f32 {
        self.offset.borrow().state().value()
    }

    /// The edge the background is revealed on, from the current displacement:
    /// a rightward offset reveals the start edge, a leftward offset the end.
    fn revealed_side(&self) -> SwipeDismissSide {
        if self.current_offset() >= 0.0 {
            SwipeDismissSide::Start
        } else {
            SwipeDismissSide::End
        }
    }

    /// Current row height scale (`1.0` at rest, `0.0` fully collapsed).
    fn collapse_fraction(&self) -> f32 {
        self.collapse.borrow().state().value()
    }

    /// Reactive read of the revealed flag; subscribes the reading scope (the
    /// subcompose slot) so it recomposes when the background reveal toggles.
    fn revealed(&self) -> bool {
        self.revealed.value()
    }

    /// Updates the revealed flag (only writes on change, to avoid needless
    /// recompositions each drag frame while already displaced).
    fn set_revealed(&self, revealed: bool) {
        if self.revealed.get_non_reactive() != revealed {
            self.revealed.set_value(revealed);
        }
    }

    /// Updates the dismissed flag, writing only on change.
    fn set_dismissed(&self, dismissed: bool) {
        if self.dismissed.get_non_reactive() != dismissed {
            self.dismissed.set_value(dismissed);
        }
    }

    fn snap_to(&self, offset: f32) {
        self.offset.borrow_mut().snapTo(offset);
        // A live drag frame: the background is revealed exactly while the row
        // is displaced. Rest (offset 0) hides it, even mid-entrance.
        self.set_revealed(offset != 0.0);
    }

    fn animate_to(&self, target: f32) {
        self.offset.borrow_mut().animateTo(target, swipe_spring());
        // A dismissal fling keeps the row displaced, so reveal immediately.
        // A spring-back keeps the reveal on until the settle watcher observes
        // the row return to rest (so the background does not vanish out from
        // under the still-sliding content).
        if target != 0.0 {
            self.set_revealed(true);
        }
    }
}

/// A row's swipe, as the application can see it.
///
/// A dismissable row is not only a callback: an application shows a delete
/// label that fades in with the swipe, a counter of what is about to go, or an
/// undo bar once a row has left. All of that needs the swipe itself, not just
/// its ending, so the same state the widget drives is readable from outside it.
///
/// Cloning shares one row's state. Hold it with [`rememberSwipeDismissState`]
/// and hand it to [`SwipeToDismissSpec::with_state`].
#[derive(Clone)]
pub struct SwipeDismissState {
    controller: Rc<SwipeToDismissController>,
}

impl PartialEq for SwipeDismissState {
    /// Identity, not value: a composable taking one skips while it is the same
    /// row, however far that row has been swiped.
    fn eq(&self, other: &Self) -> bool {
        Rc::ptr_eq(&self.controller, &other.controller)
    }
}

impl SwipeDismissState {
    fn new(runtime: RuntimeHandle) -> Self {
        Self {
            controller: SwipeToDismissController::new(runtime),
        }
    }

    /// How far the row is displaced, in logical pixels: positive towards the
    /// start edge, negative towards the end. Reactive.
    pub fn offset(&self) -> f32 {
        self.controller.current_offset()
    }

    /// How far through a dismissal the row is, in `0..=1`, against the same
    /// threshold a release is judged by. `1.0` means letting go now dismisses.
    ///
    /// Zero before the row has been measured — a fraction of an unknown width
    /// would be a guess.
    pub fn progress(&self) -> f32 {
        let width = self.controller.width_px.get();
        if !width.is_finite() || width <= 0.0 {
            return 0.0;
        }
        let threshold = width * self.controller.threshold_fraction.get();
        if threshold <= 0.0 {
            return 0.0;
        }
        (self.offset().abs() / threshold).clamp(0.0, 1.0)
    }

    /// The edge the background is revealed on, or `None` while the row is at
    /// rest and no edge is showing.
    pub fn side(&self) -> Option<SwipeDismissSide> {
        (self.offset() != 0.0).then(|| self.controller.revealed_side())
    }

    /// Whether the row is away from rest — dragged, springing back, or leaving.
    /// Reactive.
    pub fn is_displaced(&self) -> bool {
        self.controller.revealed()
    }

    /// Whether this row has been dismissed. Reactive.
    pub fn is_dismissed(&self) -> bool {
        self.controller.dismissed.value()
    }

    /// Returns the row to rest without dismissing it — an undo, or a screen
    /// closing a menu the swipe opened.
    pub fn reset(&self) {
        self.controller.reset_to_rest();
    }
}

/// Remembers the swipe state for one row.
///
/// Inside a keyed lazy list the state is keyed by the item, so a row removed
/// from the middle does not leave its displacement on the row that moves up
/// into its slot.
#[allow(non_snake_case)]
pub fn rememberSwipeDismissState() -> SwipeDismissState {
    let state = with_current_composer(|composer| {
        let runtime = composer.runtime_handle();
        let owned: Owned<SwipeDismissState> = composer.remember(|| SwipeDismissState::new(runtime));
        owned.with(SwipeDismissState::clone)
    });
    let identity = crate::lazy_item::lazy_item_key();
    if state.controller.identity.get() != identity {
        state.controller.reset_to_rest();
        state.controller.identity.set(identity);
    }
    state
}

/// Appends the swipe pointer-input handler to `base`. Split out of the
/// composable so headless tests can drive the exact production modifier
/// through a manually built modifier chain.
fn swipe_gesture_modifier(base: Modifier, controller: Rc<SwipeToDismissController>) -> Modifier {
    let key = controller.id;
    base.pointer_input(key, move |scope| {
        let controller = Rc::clone(&controller);
        async move {
            scope
                .await_pointer_event_scope(|await_scope| async move {
                    loop {
                        let event = await_scope.await_pointer_event().await;
                        handle_swipe_event(&controller, &event);
                    }
                })
                .await;
        }
    })
}

/// Handles one pointer event for the swipe gesture. Returns nothing; event
/// consumption communicates ownership to sibling/ancestor handlers.
fn handle_swipe_event(controller: &Rc<SwipeToDismissController>, event: &PointerEvent) {
    if event.kind != PointerEventKind::Down
        && event.kind != PointerEventKind::Cancel
        && controller.active_pointer.get() != Some(event.id)
    {
        return;
    }

    match event.kind {
        PointerEventKind::Down => {
            if event.is_consumed()
                || !controller.enabled.get()
                || controller.active_pointer.get().is_some()
            {
                return;
            }
            let width = controller.width_px.get();
            let inside_edge = match (controller.edge_width.get(), controller.direction.get()) {
                (None, _) => true,
                (Some(edge), SwipeDismissDirection::StartToEnd) => event.global_position.x <= edge,
                (Some(edge), SwipeDismissDirection::EndToStart) => {
                    width.is_finite() && event.global_position.x >= width - edge
                }
                (Some(edge), SwipeDismissDirection::Both) => {
                    event.global_position.x <= edge
                        || (width.is_finite() && event.global_position.x >= width - edge)
                }
            };
            if !inside_edge {
                return;
            }
            controller.active_pointer.set(Some(event.id));
            // Catch an in-flight spring: pressing pins the content where it
            // currently is, like Compose's swipeable.
            let current = controller.current_offset();
            controller.snap_to(current);
            controller.phase.set(SwipePhase::Tracking {
                down_x: event.global_position.x,
                down_y: event.global_position.y,
                start_offset: current,
            });
            // Down is never consumed: taps must keep reaching clickables.
        }
        PointerEventKind::Move => {
            if event.is_consumed() {
                // Another handler owns this sequence (parent scroll started,
                // or a sibling captured); abandon and rest.
                if matches!(controller.phase.get(), SwipePhase::Dragging { .. }) {
                    animate_spring_back(controller);
                }
                controller.phase.set(SwipePhase::Idle);
                return;
            }
            match controller.phase.get() {
                SwipePhase::Tracking {
                    down_x,
                    down_y,
                    start_offset,
                } => {
                    let total_dx = event.global_position.x - down_x;
                    let total_dy = event.global_position.y - down_y;
                    match decide_axis(total_dx, total_dy, DRAG_THRESHOLD) {
                        SwipeAxisDecision::Horizontal => {
                            controller.phase.set(SwipePhase::Dragging {
                                down_x,
                                start_offset,
                            });
                            let width = controller.width_px.get();
                            controller.snap_to(constrain_direction(
                                clamp_offset(start_offset + total_dx, width),
                                controller.direction.get(),
                            ));
                            event.consume();
                        }
                        SwipeAxisDecision::Vertical => {
                            controller.phase.set(SwipePhase::LockedOut);
                        }
                        SwipeAxisDecision::Undecided => {}
                    }
                }
                SwipePhase::Dragging {
                    down_x,
                    start_offset,
                } => {
                    let total_dx = event.global_position.x - down_x;
                    let width = controller.width_px.get();
                    controller.snap_to(constrain_direction(
                        clamp_offset(start_offset + total_dx, width),
                        controller.direction.get(),
                    ));
                    event.consume();
                }
                SwipePhase::Idle | SwipePhase::LockedOut => {}
            }
        }
        PointerEventKind::Up => {
            let phase = controller.phase.get();
            controller.phase.set(SwipePhase::Idle);
            if let SwipePhase::Dragging { .. } = phase {
                settle_release(controller);
                event.consume();
            }
            controller.active_pointer.set(None);
        }
        PointerEventKind::Cancel => {
            if matches!(controller.phase.get(), SwipePhase::Dragging { .. }) {
                animate_spring_back(controller);
            }
            controller.phase.set(SwipePhase::Idle);
            controller.active_pointer.set(None);
        }
        PointerEventKind::Scroll
        | PointerEventKind::Zoom
        | PointerEventKind::RotaryScrollPre
        | PointerEventKind::RotaryScroll
        | PointerEventKind::Enter
        | PointerEventKind::Exit => {}
    }
}

fn constrain_direction(offset: f32, direction: SwipeDismissDirection) -> f32 {
    match direction {
        SwipeDismissDirection::Both => offset,
        SwipeDismissDirection::StartToEnd => offset.max(0.0),
        SwipeDismissDirection::EndToStart => offset.min(0.0),
    }
}

/// Applies the release decision: animate off-screen and watch for completion
/// (firing `on_dismiss`), or spring back to rest.
fn settle_release(controller: &Rc<SwipeToDismissController>) {
    let offset = controller.current_offset();
    let width = controller.width_px.get();
    match dismissal_target(offset, width, controller.threshold_fraction.get()) {
        Some(target) => animate_dismiss(controller, target),
        None => animate_spring_back(controller),
    }
}

/// Flings the row off-screen and watches for `on_dismiss` to fire once settled.
fn animate_dismiss(controller: &Rc<SwipeToDismissController>, target: f32) {
    controller.animate_to(target);
    watch_settle(controller, true);
}

/// Springs the row back to rest and watches so the reveal is hidden again once
/// the content actually returns to offset 0.
fn animate_spring_back(controller: &Rc<SwipeToDismissController>) {
    controller.animate_to(0.0);
    watch_settle(controller, false);
}

/// Watches the settle animation frame-by-frame. Once the offset reaches its
/// target it syncs the reveal flag to the resting displacement and, for a
/// dismissal, fires `on_dismiss` exactly once. Runs in frame callbacks
/// (outside composition), so the callback may freely mutate state.
fn watch_settle(controller: &Rc<SwipeToDismissController>, dismissing: bool) {
    let weak = Rc::downgrade(controller);
    let registration =
        controller
            .runtime
            .frame_clock()
            .with_frame_nanos(move |_frame_time_nanos| {
                let Some(controller) = weak.upgrade() else {
                    return;
                };
                controller.settle_watcher.borrow_mut().take();
                if dismissing && controller.dismissed.get_non_reactive() {
                    return;
                }
                // A new gesture retargeted the animation; a fresh snap already
                // owns the reveal flag, so stop watching.
                if matches!(controller.phase.get(), SwipePhase::Dragging { .. }) {
                    return;
                }
                let target = controller.offset.borrow().target();
                let value = controller.current_offset();
                if (value - target).abs() <= DISMISS_SETTLE_EPSILON {
                    // The row has settled. Stop drawing the background in every
                    // case: a spring-back rests at 0 (nothing revealed), and a
                    // dismissal must *not* leave the red strip behind while it
                    // waits for the host to drop the item.
                    controller.set_revealed(false);
                    if dismissing && !controller.dismissed.get_non_reactive() {
                        controller.set_dismissed(true);
                        // Collapse the row to zero height so no empty gap (or
                        // background strip) lingers if the host removes the item
                        // a frame or two later, then notify the host.
                        if controller.collapse_after_dismiss.get() {
                            start_collapse(&controller);
                        }
                        let on_dismiss = controller.on_dismiss.borrow().clone();
                        if let Some(on_dismiss) = on_dismiss {
                            on_dismiss();
                        }
                    }
                } else {
                    watch_settle(&controller, dismissing);
                }
            });
    *controller.settle_watcher.borrow_mut() = Some(registration);
}

/// Animates the row's height scale to `0.0` and watches the animation so the
/// list re-measures the shrinking row each frame. Runs after a dismiss settles.
fn start_collapse(controller: &Rc<SwipeToDismissController>) {
    controller
        .collapse
        .borrow_mut()
        .animateTo(0.0, swipe_spring());
    watch_collapse(controller);
}

/// Frame-by-frame watcher for the post-dismiss collapse: the row height is a
/// layout output, so a plain animated value would not reach the parent list on
/// its own — each frame this forces a scoped re-measure of the row and a redraw
/// until the height scale reaches zero.
fn watch_collapse(controller: &Rc<SwipeToDismissController>) {
    let weak = Rc::downgrade(controller);
    let registration =
        controller
            .runtime
            .frame_clock()
            .with_frame_nanos(move |_frame_time_nanos| {
                let Some(controller) = weak.upgrade() else {
                    return;
                };
                controller.collapse_watcher.borrow_mut().take();
                if let Some(node_id) = controller.node_id.get() {
                    // Re-measure the row as it collapses. A plain layout repass
                    // only bubbles *layout* (placement) dirtiness up the tree,
                    // which does not set the row node's own `needs_measure` flag —
                    // and that flag is exactly what an enclosing `LazyColumn`
                    // consults (`children_need_relayout`) before reusing a cached
                    // item slot. `schedule_measure_repass` bubbles *measure*
                    // dirtiness so the list actually re-measures the shrinking
                    // row; otherwise the pre-dismiss height and the still-composed
                    // red background linger until the whole list is rebuilt.
                    crate::schedule_measure_repass(node_id);
                }
                crate::request_render_invalidation();
                if controller.collapse_fraction() > COLLAPSE_SETTLE_EPSILON {
                    watch_collapse(&controller);
                }
            });
    *controller.collapse_watcher.borrow_mut() = Some(registration);
}

/// Wraps `content` so it can be swiped away horizontally.
///
/// Dragging moves the content with the finger (clamped to one content width
/// in either direction). Releasing past `spec.threshold_fraction` of the
/// width animates the content off-screen with a spring and then fires
/// `on_dismiss` (exactly once); releasing earlier springs the content back.
/// An optional [`SwipeToDismissSpec::with_background`] content (delete bin,
/// archive icon, ...) is revealed behind the row while it is displaced.
///
/// Vertical drags are handed to ancestor scroll containers untouched, so
/// rows inside a `LazyColumn` still scroll the list (see the module docs for
/// the axis-locking rules).
#[composable(no_skip)]
pub fn SwipeToDismiss<D, F>(
    modifier: Modifier,
    spec: SwipeToDismissSpec,
    on_dismiss: D,
    content: F,
) -> cranpose_core::NodeId
where
    D: Fn() + 'static,
    F: FnMut() + 'static,
{
    let owned_controller: Rc<SwipeToDismissController> = with_current_composer(|composer| {
        let runtime = composer.runtime_handle();
        let owned: Owned<Rc<SwipeToDismissController>> =
            composer.remember(|| SwipeToDismissController::new(runtime));
        owned.with(Rc::clone)
    });
    let controller = match &spec.state {
        Some(state) => Rc::clone(&state.controller),
        None => owned_controller,
    };

    // Content identity: when this composition slot is reused for a different
    // item (unkeyed lazy rows shifting up after a removal), the remembered
    // controller must not leak the old item's swipe state onto the new one.
    // A row inside a keyed lazy list is identified by the list's own key, so
    // an application does not repeat it here.
    let identity = spec.key.or_else(crate::lazy_item::lazy_item_key);
    if controller.identity.get() != identity {
        controller.reset_to_rest();
        controller.identity.set(identity);
    }

    // Refresh the per-recomposition inputs so the pointer handler (which
    // lives across recompositions) observes the latest values.
    controller
        .threshold_fraction
        .set(spec.threshold_fraction.clamp(f32::EPSILON, 1.0));
    controller.direction.set(spec.direction);
    controller.edge_width.set(spec.edge_width);
    controller
        .collapse_after_dismiss
        .set(spec.collapse_after_dismiss);
    controller.enabled.set(spec.enabled);
    *controller.on_dismiss.borrow_mut() = Some(Rc::new(on_dismiss));

    let background = spec.background.clone();
    let content = Rc::new(RefCell::new(content));

    // The gesture area is the whole (un-offset) row: like a scroll
    // container, the handler sits on the ancestor node so descendants
    // (clickables) see events first, and the hit region stays put while the
    // content slides away.
    let gesture_modifier = swipe_gesture_modifier(modifier, Rc::clone(&controller));

    // Outer collapsing layout: it measures the row and reports the row's height
    // scaled by the collapse fraction, so a dismissed row shrinks to nothing —
    // even when the row has a fixed height. It carries no user modifier: the
    // user modifier, the gesture handler and any fixed size stay on the *row*
    // (below), so the hit region and layout still belong to the row while only
    // the reported height is scaled here.
    let controller_for_layout = Rc::clone(&controller);
    let node = SubcomposeLayout(Modifier::empty(), move |scope, constraints| {
        // Height scale for the post-dismiss collapse (1.0 until dismissed), read
        // before measuring so the reported height tracks the animation.
        let collapse = controller_for_layout.collapse_fraction().clamp(0.0, 1.0);

        let gesture_modifier = gesture_modifier.clone();
        let background = background.clone();
        let content = Rc::clone(&content);
        let controller_for_row = Rc::clone(&controller_for_layout);
        let measurables = scope.subcompose(SlotId::new(0), move || {
            // The row itself: a `BoxWithConstraints` (so it can read its own
            // width for the dismiss threshold) carrying the user modifier + the
            // swipe pointer handler, overlaying the optional background and the
            // finger-translated content.
            let background = background.clone();
            let content = Rc::clone(&content);
            let controller_for_row = Rc::clone(&controller_for_row);
            BoxWithConstraints(gesture_modifier.clone(), move |row_scope| {
                controller_for_row
                    .width_px
                    .set(row_scope.constraints().max_width);

                // Only compose the background while the row is displaced (and
                // never once dismissed — the reveal flag is cleared on settle).
                // Reading it inside the subcompose subscribes this slot, so it
                // recomposes when the row leaves/returns to rest. At rest the
                // background is not composed at all, so it cannot flash through
                // content that fades in with alpha < 1 during an entrance.
                if controller_for_row.revealed() {
                    if let Some(background) = &background {
                        let background = Rc::clone(background);
                        let side = controller_for_row.revealed_side();
                        Box(Modifier::empty(), BoxSpec::new(), move || {
                            (background.borrow_mut())(side);
                        });
                    }
                }

                // Translate the content with the finger via a graphics-layer
                // resolver. The resolver re-reads the live offset on every draw
                // pass, and an offset write schedules a draw repass for this
                // node, so the content follows the finger 1:1 in real time and
                // settles with the spring on release — without re-measuring the
                // subcompose each frame.
                let content = Rc::clone(&content);
                let controller_for_layer = Rc::clone(&controller_for_row);
                Box(
                    Modifier::empty().graphics_layer(move || GraphicsLayer {
                        translation_x: controller_for_layer.current_offset(),
                        ..GraphicsLayer::default()
                    }),
                    BoxSpec::new(),
                    move || {
                        (content.borrow_mut())();
                    },
                );
            });
        });

        let child_constraints = Constraints {
            min_width: constraints.min_width,
            max_width: constraints.max_width,
            min_height: 0.0,
            max_height: constraints.max_height,
        };
        let mut width = 0.0_f32;
        let mut natural_height = 0.0_f32;
        let mut placements = Vec::with_capacity(measurables.len());
        for measurable in measurables {
            let placeable = scope.measure(measurable, child_constraints);
            width = width.max(placeable.width());
            natural_height = natural_height.max(placeable.height());
            placeable.place(0.0, 0.0);
            placements.push(Placement::new(placeable.node_id(), 0.0, 0.0, 0));
        }
        width = width.clamp(constraints.min_width, constraints.max_width);
        // Collapse the row height after a dismiss so the slot shrinks to
        // nothing: the content is already translated off-screen and the
        // background hidden, so scaling the reported height just closes the gap.
        let height = (natural_height * collapse).clamp(0.0, constraints.max_height);
        scope.layout(width, height, placements)
    });
    controller.node_id.set(Some(node));
    node
}

/// Full-content navigation dismissal. The gesture starts at the leading edge,
/// moves only toward the end edge, and leaves sizing to the navigation owner.
#[composable]
pub fn SwipeToDismissBox<D, F>(modifier: Modifier, on_dismiss: D, content: F) -> NodeId
where
    D: Fn() + 'static,
    F: FnMut() + 'static,
{
    SwipeToDismiss(
        modifier,
        SwipeToDismissSpec::new()
            .with_threshold_fraction(0.35)
            .with_direction(SwipeDismissDirection::StartToEnd)
            .from_edge(32.0)
            .with_collapse_after_dismiss(false),
        on_dismiss,
        content,
    )
}

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