repose-core 0.21.5

Repose's core runtime, view model, signals, composition locals, and animation clock.
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
use crate::Vec2;
use crate::color::{Brush, Color};
use crate::geometry::Rect;
use crate::input::{Modifiers, PointerKind};
use crate::runtime::{Frame, HitRegion};
use crate::shortcuts::DragAction;
use crate::text::{FontStyle, FontWeight, TextAlign, TextDecoration};
use crate::view::{Scene, SceneNode};
use std::cell::RefCell;
use std::{any::Any, path::PathBuf, rc::Rc, sync::Arc};
use web_time::Instant;

/// Opaque payload moved during internal drag & drop.
/// Use [`downcast_drag_payload`] on the receiver side to recover a typed value.
pub type DragPayload = Rc<dyn Any>;

/// Wrap a typed value into a [`DragPayload`] for a drag source.
///
/// ```ignore
/// Modifier::new().on_drag_start(|_start| Some(drag_payload(MyItem { id: 1 })))
/// ```
pub fn drag_payload<T: 'static>(value: T) -> DragPayload {
    Rc::new(value)
}

/// Try to downcast a drag payload to a typed reference. Used on the drop side.
///
/// ```ignore
/// if let Some(item) = downcast_drag_payload::<MyItem>(&ev.payload) {
///     // handle item
/// }
/// ```
pub fn downcast_drag_payload<T: 'static>(payload: &DragPayload) -> Option<&T> {
    payload.as_ref().downcast_ref::<T>()
}

/// Block-style convenience for [`Modifier::on_drag_start`] with a typed payload.
///
/// ```ignore
/// use repose_core::{Modifier, drag_and_drop_source};
/// struct MyItem { id: i32 }
/// let m = drag_and_drop_source(Modifier::new(), |_start| Some(MyItem { id: 1 }));
/// ```
///
/// is equivalent to:
///
/// ```ignore
/// Modifier::new().on_drag_start(|_start| Some(drag_payload(MyItem { id: 1 })))
/// ```
pub fn drag_and_drop_source<T, F>(mut modifier: crate::Modifier, on_start: F) -> crate::Modifier
where
    T: 'static,
    F: Fn(DragStart) -> Option<T> + 'static,
{
    modifier = modifier.on_drag_start(move |start| on_start(start).map(drag_payload::<T>));
    modifier
}

/// Block-style convenience for [`Modifier::on_drop`] with a typed payload. The
/// drop is accepted when the closure returns `true`; the typed payload is
/// downcast before the closure is invoked.
///
/// ```ignore
/// use repose_core::{Modifier, drag_and_drop_target};
/// struct MyItem { id: i32 }
/// let m = drag_and_drop_target(Modifier::new(), |_ev, item: &MyItem| {
///     println!("got id {}", item.id);
///     true
/// });
/// ```
pub fn drag_and_drop_target<T, F>(mut modifier: crate::Modifier, on_drop: F) -> crate::Modifier
where
    T: 'static,
    F: Fn(&DropEvent, &T) -> bool + 'static,
{
    modifier = modifier.on_drop(move |ev| match downcast_drag_payload::<T>(&ev.payload) {
        Some(v) => on_drop(&ev, v),
        None => false,
    });
    modifier
}

#[derive(Clone, Debug)]
pub struct DragStart {
    pub source_id: u64,
    pub position: Vec2,
    pub modifiers: Modifiers,
}

#[derive(Clone, Debug)]
pub struct DragOver {
    pub source_id: u64,
    pub target_id: u64,
    pub position: Vec2,
    pub modifiers: Modifiers,
    pub payload: DragPayload,
}

#[derive(Clone, Debug)]
pub struct DropEvent {
    pub source_id: u64,
    pub target_id: u64,
    pub position: Vec2,
    pub modifiers: Modifiers,
    pub payload: DragPayload,
}

/// Sent to the drag source when the drag ends (drop or cancel).
#[derive(Clone, Copy, Debug)]
pub struct DragEnd {
    pub accepted: bool,
}

/// A single dropped file descriptor.
/// - On desktop: `path` is `Some(PathBuf)`.
/// - On web: `path` is usually `None` (browser doesn't expose local paths).
#[derive(Clone, Debug)]
pub struct DroppedFile {
    pub name: String,
    pub path: Option<PathBuf>,
}

/// Payload type for file drag/drop coming from the OS/browser.
#[derive(Clone, Debug)]
pub struct DroppedFiles {
    pub files: Vec<DroppedFile>,
}

/// Tracks an active drag session (internal widget-to-widget DnD).
#[derive(Clone, Debug)]
pub struct DragSession {
    pub source_id: u64,
    pub payload: DragPayload,
    pub start_px: (f32, f32),
    pub over_id: Option<u64>,
}

#[derive(Clone)]
struct MouseDownState {
    position: Vec2,
    capture_id: u64,
}

#[derive(Clone)]
struct TouchDownState {
    time: Instant,
    position: Vec2,
    capture_id: u64,
    long_press_pending: bool,
}

const LONG_PRESS_MS: u128 = 400;

thread_local! {
    static DND_FRAME: RefCell<Option<Frame>> = const { RefCell::new(None) };
    static DND_SCALE: RefCell<f32> = const { RefCell::new(1.0) };
    static DND_SESSION: RefCell<Option<DragSession>> = const { RefCell::new(None) };
    static DND_MOUSE_DOWN: RefCell<Option<MouseDownState>> = const { RefCell::new(None) };
    static DND_TOUCH_DOWN: RefCell<Option<TouchDownState>> = const { RefCell::new(None) };
}

/// Set the current frame for DnD hit-testing. Called by platform after each render.
pub fn set_dnd_frame(frame: Option<Frame>) {
    DND_FRAME.with(|f| *f.borrow_mut() = frame);
}

/// Set the display scale for DnD slop calculation.
pub fn set_dnd_scale(scale: f32) {
    DND_SCALE.with(|s| *s.borrow_mut() = scale);
}

/// Check if a drag session is currently active.
pub fn is_dragging() -> bool {
    DND_SESSION.with(|s| s.borrow().is_some())
}

fn touch_slop_px(scale: f32) -> f32 {
    6.0 * scale
}

fn hit_index_by_id(frame: &Frame, id: u64) -> Option<usize> {
    frame.hit_regions.iter().position(|h| h.id == id)
}

fn is_dnd_target(hit: &HitRegion) -> bool {
    hit.on_drop.is_some()
        || hit.on_drag_enter.is_some()
        || hit.on_drag_over.is_some()
        || hit.on_drag_leave.is_some()
}

pub fn dnd_target_id_at(frame: &Frame, pos: Vec2) -> Option<u64> {
    frame
        .hit_regions
        .iter()
        .rev()
        .filter(|h| h.rect.contains(pos))
        .find(|h| is_dnd_target(h))
        .map(|h| h.id)
}

fn dnd_update_over(frame: &Frame, session: &mut DragSession, modifiers: Modifiers, pos: Vec2) {
    let new_over = dnd_target_id_at(frame, pos);

    if new_over != session.over_id {
        if let Some(prev) = session.over_id {
            if let Some(i) = hit_index_by_id(frame, prev) {
                if let Some(cb) = &frame.hit_regions[i].on_drag_leave {
                    cb(DragOver {
                        source_id: session.source_id,
                        target_id: prev,
                        position: pos,
                        modifiers,
                        payload: session.payload.clone(),
                    });
                }
            }
        }

        if let Some(now) = new_over {
            if let Some(i) = hit_index_by_id(frame, now) {
                if let Some(cb) = &frame.hit_regions[i].on_drag_enter {
                    cb(DragOver {
                        source_id: session.source_id,
                        target_id: now,
                        position: pos,
                        modifiers,
                        payload: session.payload.clone(),
                    });
                }
            }
        }

        session.over_id = new_over;
    }

    if let Some(over) = session.over_id {
        if let Some(i) = hit_index_by_id(frame, over) {
            if let Some(cb) = &frame.hit_regions[i].on_drag_over {
                cb(DragOver {
                    source_id: session.source_id,
                    target_id: over,
                    position: pos,
                    modifiers,
                    payload: session.payload.clone(),
                });
            }
        }
    }
}

/// Finish a drag-and-drop session.
fn dnd_finish(
    frame: &Frame,
    session: DragSession,
    modifiers: Modifiers,
    pos: Vec2,
    accept_if_possible: bool,
) -> bool {
    let mut accepted = false;
    if accept_if_possible {
        let drop_target = dnd_target_id_at(frame, pos);
        if let Some(tid) = drop_target {
            if let Some(i) = hit_index_by_id(frame, tid) {
                if let Some(cb) = &frame.hit_regions[i].on_drop {
                    accepted = cb(DropEvent {
                        source_id: session.source_id,
                        target_id: tid,
                        position: pos,
                        modifiers,
                        payload: session.payload.clone(),
                    });
                }
            }
        }
    }

    if let Some(i) = hit_index_by_id(frame, session.source_id) {
        if let Some(cb) = &frame.hit_regions[i].on_drag_end {
            cb(DragEnd { accepted });
        }
    }

    accepted
}

fn initiate_drag(
    frame: &Frame,
    capture_id: u64,
    start_pos: Vec2,
    current_pos: Vec2,
    modifiers: Modifiers,
) -> bool {
    let Some(i) = hit_index_by_id(frame, capture_id) else {
        return false;
    };
    let Some(cb) = &frame.hit_regions[i].on_drag_start else {
        return false;
    };

    let payload = cb(DragStart {
        source_id: capture_id,
        position: current_pos,
        modifiers,
    });
    let Some(payload) = payload else {
        return false;
    };

    DND_SESSION.with(|s| {
        *s.borrow_mut() = Some(DragSession {
            source_id: capture_id,
            payload,
            start_px: (start_pos.x, start_pos.y),
            over_id: None,
        });
    });
    true
}

/// Handle a DragAction from the platform. Returns true if the action was consumed.
pub fn handle_drag_action(action: &DragAction) -> bool {
    let scale = DND_SCALE.with(|s| *s.borrow());
    let slop = touch_slop_px(scale);

    match *action {
        DragAction::Press {
            position,
            capture_id,
            kind,
            ..
        } => {
            match kind {
                PointerKind::Mouse => {
                    DND_MOUSE_DOWN.with(|m| {
                        *m.borrow_mut() = Some(MouseDownState {
                            position,
                            capture_id,
                        });
                    });
                }
                _ => {
                    // Touch (or pen/unknown): start long-press timer
                    DND_TOUCH_DOWN.with(|t| {
                        *t.borrow_mut() = Some(TouchDownState {
                            time: web_time::Instant::now(),
                            position,
                            capture_id,
                            long_press_pending: true,
                        });
                    });
                }
            }
            false
        }

        DragAction::Move {
            position,
            modifiers,
        } => {
            // If already dragging, update
            if DND_SESSION.with(|s| s.borrow().is_some()) {
                if let Some(frame) = DND_FRAME.with(|f| f.borrow().clone()) {
                    DND_SESSION.with(|s| {
                        if let Some(ref mut session) = *s.borrow_mut() {
                            dnd_update_over(&frame, session, modifiers, position);
                        }
                    });
                }
                return true;
            }

            // Mouse: try drag initiation (drag past slop)
            if let Some(down) = DND_MOUSE_DOWN.with(|m| m.borrow().clone()) {
                let dx = position.x - down.position.x;
                let dy = position.y - down.position.y;
                let dist = (dx * dx + dy * dy).sqrt();
                if dist >= slop {
                    if let Some(frame) = DND_FRAME.with(|f| f.borrow().clone()) {
                        if initiate_drag(
                            &frame,
                            down.capture_id,
                            down.position,
                            position,
                            modifiers,
                        ) {
                            // Update over immediately
                            DND_SESSION.with(|s| {
                                if let Some(ref mut session) = *s.borrow_mut() {
                                    dnd_update_over(&frame, session, modifiers, position);
                                }
                            });
                            DND_MOUSE_DOWN.with(|m| *m.borrow_mut() = None);
                            return true;
                        }
                    }
                    // Widget doesn't support drag - try mouse down again next time
                    // (actually, clear it so we don't retry on every move)
                    DND_MOUSE_DOWN.with(|m| *m.borrow_mut() = None);
                }
                return true; // consumed: mouse is pressed, don't fall through to scroll
            }

            // Touch: try long-press initiation
            if let Some(touch) = DND_TOUCH_DOWN.with(|t| t.borrow().clone()) {
                if touch.long_press_pending {
                    let elapsed_ms = (Instant::now() - touch.time).as_millis() as u128;
                    let dx = position.x - touch.position.x;
                    let dy = position.y - touch.position.y;
                    let dist = (dx * dx + dy * dy).sqrt();

                    if elapsed_ms >= LONG_PRESS_MS && dist <= slop {
                        if let Some(frame) = DND_FRAME.with(|f| f.borrow().clone()) {
                            if initiate_drag(
                                &frame,
                                touch.capture_id,
                                touch.position,
                                position,
                                modifiers,
                            ) {
                                DND_SESSION.with(|s| {
                                    if let Some(ref mut session) = *s.borrow_mut() {
                                        dnd_update_over(&frame, session, modifiers, position);
                                    }
                                });
                                DND_TOUCH_DOWN.with(|t| *t.borrow_mut() = None);
                                return true;
                            }
                            // Widget doesn't support drag - cancel long press
                            DND_TOUCH_DOWN.with(|t| {
                                if let Some(ref mut td) = *t.borrow_mut() {
                                    td.long_press_pending = false;
                                }
                            });
                        }
                    }
                    if dist > slop {
                        DND_TOUCH_DOWN.with(|t| {
                            if let Some(ref mut td) = *t.borrow_mut() {
                                td.long_press_pending = false;
                            }
                        });
                    }
                }
                // Only consume if still waiting for long-press (within slop, timer not yet expired).
                // If long-press was cancelled (moved past slop), let scroll handle the event.
                let still_pending = DND_TOUCH_DOWN.with(|t| {
                    t.borrow().as_ref().map(|td| td.long_press_pending).unwrap_or(false)
                });
                if still_pending {
                    return true;
                }
            }

            false
        }

        DragAction::Release {
            position,
            modifiers,
        } => {
            let mut consumed = false;

            if let Some(session) = DND_SESSION.with(|s| s.borrow_mut().take()) {
                if let Some(frame) = DND_FRAME.with(|f| f.borrow().clone()) {
                    dnd_finish(&frame, session, modifiers, position, true);
                }
                consumed = true;
            }

            DND_MOUSE_DOWN.with(|m| *m.borrow_mut() = None);
            DND_TOUCH_DOWN.with(|t| *t.borrow_mut() = None);

            consumed
        }

        DragAction::Cancel => {
            let mut consumed = false;
            if let Some(session) = DND_SESSION.with(|s| s.borrow_mut().take()) {
                if let Some(frame) = DND_FRAME.with(|f| f.borrow().clone()) {
                    dnd_finish(
                        &frame,
                        session,
                        Modifiers::default(),
                        Vec2::default(),
                        false,
                    );
                }
                consumed = true;
            }
            DND_MOUSE_DOWN.with(|m| *m.borrow_mut() = None);
            DND_TOUCH_DOWN.with(|t| *t.borrow_mut() = None);
            consumed
        }
    }
}

/// Draw drag overlay indicator on the scene.
/// `external_file_drag` enables orange styling for OS/browser file-drop overlays.
pub fn overlay_drag_indicator(
    scene: &mut Scene,
    mouse_pos_px: (f32, f32),
    external_file_drag: bool,
) {
    if !is_dragging() && !external_file_drag {
        return;
    }

    let pos = Vec2 {
        x: mouse_pos_px.0,
        y: mouse_pos_px.1,
    };

    let frame = DND_FRAME.with(|f| f.borrow().clone());
    let Some(ref f) = frame else {
        return;
    };

    let color = if external_file_drag {
        Color::from_hex("#FFAA00")
    } else {
        Color::from_hex("#44AAFF")
    };

    // Highlight best drop target under cursor
    if let Some(tid) = dnd_target_id_at(f, pos)
        && let Some(hit) = f.hit_regions.iter().find(|h| h.id == tid)
    {
        let r = crate::locals::dp_to_px(8.0);
        scene.nodes.push(SceneNode::Border {
            rect: hit.rect,
            color,
            width: crate::locals::dp_to_px(2.0),
            radius: [r; 4],
        });
    }

    // Cursor badge
    let badge = Rect {
        x: pos.x + crate::locals::dp_to_px(12.0),
        y: pos.y + crate::locals::dp_to_px(12.0),
        w: crate::locals::dp_to_px(110.0),
        h: crate::locals::dp_to_px(24.0),
    };

    let bg = if external_file_drag {
        Color::from_hex("#FFAA0077")
    } else {
        Color::from_hex("#44AAFF77")
    };

    let r = crate::locals::dp_to_px(8.0);
    scene.nodes.push(SceneNode::Rect {
        rect: badge,
        brush: Brush::Solid(bg),
        radius: [r; 4],
    });
    scene.nodes.push(SceneNode::Text {
        rect: Rect {
            x: badge.x + crate::locals::dp_to_px(8.0),
            y: badge.y + crate::locals::dp_to_px(6.0),
            w: 0.0,
            h: crate::locals::dp_to_px(14.0),
        },
        text: Arc::<str>::from(" "),
        color: Color::WHITE,
        size: crate::locals::dp_to_px(12.0),
        font_family: None,
        text_align: TextAlign::Unspecified,
        font_weight: FontWeight::NORMAL,
        font_style: FontStyle::Normal,
        text_decoration: TextDecoration::default(),
        letter_spacing: 0.0,
        line_height: 0.0,
        extra_style: Default::default(),
        url: None,
    });
}