1
//! Unified drag context for all drag operations.
2
//!
3
//! This module provides a single, coherent way to handle all drag operations:
4
//! - Text selection drag
5
//! - Scrollbar thumb drag
6
//! - Node drag-and-drop
7
//! - Window drag/resize
8
//! - File drop from OS
9
//!
10
//! The `DragContext` struct tracks the current drag state and provides
11
//! a unified interface for event processing.
12

            
13
use alloc::vec::Vec;
14

            
15
use azul_css::{AzString, StringVec, U8Vec};
16

            
17
use crate::{
18
    dom::{DomId, DomNodeId, NodeId, OptionDomNodeId},
19
    geom::LogicalPosition,
20
    selection::TextCursor,
21
    window::WindowPosition,
22
};
23

            
24
/// Type of the active drag operation.
25
///
26
/// This enum unifies all drag types into a single discriminated union,
27
/// making it easy to handle different drag behaviors in one place.
28
#[derive(Debug, Clone, PartialEq)]
29
#[repr(C, u8)]
30
pub enum ActiveDragType {
31
    /// Text selection drag - user is selecting text by dragging
32
    TextSelection(TextSelectionDrag),
33
    /// Scrollbar thumb drag - user is dragging a scrollbar thumb
34
    ScrollbarThumb(ScrollbarThumbDrag),
35
    /// Node drag-and-drop - user is dragging a DOM node
36
    Node(NodeDrag),
37
    /// Window drag - user is moving the window (titlebar drag)
38
    WindowMove(WindowMoveDrag),
39
    /// Window resize - user is resizing the window (edge/corner drag)
40
    WindowResize(WindowResizeDrag),
41
    /// File drop from OS - user is dragging file(s) from the OS
42
    FileDrop(FileDropDrag),
43
}
44

            
45
/// Text selection drag state.
46
///
47
/// Tracks the anchor point (where selection started) and current position.
48
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49
#[repr(C)]
50
pub struct TextSelectionDrag {
51
    /// DOM ID where the selection started
52
    pub dom_id: DomId,
53
    /// The IFC root node where selection started (e.g., <p> element)
54
    pub anchor_ifc_node: NodeId,
55
    /// The anchor cursor position (fixed during drag)
56
    pub anchor_cursor: Option<TextCursor>,
57
    /// Mouse position where drag started
58
    pub start_mouse_position: LogicalPosition,
59
    /// Current mouse position
60
    pub current_mouse_position: LogicalPosition,
61
}
62

            
63
/// Scrollbar thumb drag state.
64
///
65
/// Tracks which scrollbar is being dragged and the current offset.
66
#[derive(Debug, Clone, Copy, PartialEq)]
67
#[repr(C)]
68
pub struct ScrollbarThumbDrag {
69
    /// DOM ID that `scroll_container_node` belongs to. Used to scope
70
    /// `remap_node_ids` so a reconciliation of a *different* DOM can't remap
71
    /// this drag's node id against an unrelated DOM's old→new map.
72
    pub dom_id: DomId,
73
    /// The scroll container node being scrolled
74
    pub scroll_container_node: NodeId,
75
    /// Whether this is the vertical or horizontal scrollbar
76
    pub axis: ScrollbarAxis,
77
    /// Mouse Y position where drag started (for calculating delta)
78
    pub start_mouse_position: LogicalPosition,
79
    /// Scroll offset when drag started
80
    pub start_scroll_offset: f32,
81
    /// Current mouse position
82
    pub current_mouse_position: LogicalPosition,
83
    /// Track length in pixels (for calculating scroll ratio)
84
    pub track_length_px: f32,
85
    /// Content length in pixels (for calculating scroll ratio)
86
    pub content_length_px: f32,
87
    /// Viewport length in pixels (for calculating scroll ratio)
88
    pub viewport_length_px: f32,
89
}
90

            
91
/// Which scrollbar axis is being dragged
92
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
93
#[repr(C)]
94
pub enum ScrollbarAxis {
95
    Vertical,
96
    Horizontal,
97
}
98

            
99
/// Node drag-and-drop state.
100
///
101
/// Tracks a DOM node being dragged for reordering or moving.
102
#[derive(Debug, Clone, PartialEq, Eq)]
103
#[repr(C)]
104
pub struct NodeDrag {
105
    /// DOM ID of the node being dragged
106
    pub dom_id: DomId,
107
    /// Node ID being dragged
108
    pub node_id: NodeId,
109
    /// Position where drag started
110
    pub start_position: LogicalPosition,
111
    /// Current drag position
112
    pub current_position: LogicalPosition,
113
    /// Offset from node origin to click point (for correct visual positioning)
114
    pub drag_offset: LogicalPosition,
115
    /// Optional: DOM node currently under cursor (drop target)
116
    pub current_drop_target: OptionDomNodeId,
117
    /// Previous drop target (for generating DragEnter/DragLeave events)
118
    pub previous_drop_target: OptionDomNodeId,
119
    /// Drag data (MIME types and content)
120
    pub drag_data: DragData,
121
    /// Whether the current drop target has accepted the drop via `accept_drop()`
122
    pub drop_accepted: bool,
123
    /// Drop effect set by the drop target
124
    pub drop_effect: DropEffect,
125
}
126

            
127
/// Window move drag state.
128
///
129
/// Tracks the window being moved via titlebar drag.
130
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
131
#[repr(C)]
132
pub struct WindowMoveDrag {
133
    /// Position where window drag started (in screen coordinates)
134
    pub start_position: LogicalPosition,
135
    /// Current drag position
136
    pub current_position: LogicalPosition,
137
    /// Initial window position before drag
138
    pub initial_window_position: WindowPosition,
139
}
140

            
141
/// Window resize drag state.
142
///
143
/// Tracks the window being resized via edge/corner drag.
144
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
145
#[repr(C)]
146
pub struct WindowResizeDrag {
147
    /// Which edge/corner is being dragged
148
    pub edge: WindowResizeEdge,
149
    /// Position where resize started
150
    pub start_position: LogicalPosition,
151
    /// Current drag position
152
    pub current_position: LogicalPosition,
153
    /// Initial window size before resize
154
    pub initial_width: u32,
155
    /// Initial window height before resize
156
    pub initial_height: u32,
157
}
158

            
159
/// Which edge or corner of the window is being resized
160
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
161
#[repr(C)]
162
pub enum WindowResizeEdge {
163
    Top,
164
    Bottom,
165
    Left,
166
    Right,
167
    TopLeft,
168
    TopRight,
169
    BottomLeft,
170
    BottomRight,
171
}
172

            
173
/// File drop from OS drag state.
174
///
175
/// Tracks files being dragged from the operating system.
176
#[derive(Debug, Clone, PartialEq, Eq)]
177
#[repr(C)]
178
pub struct FileDropDrag {
179
    /// Files being dragged (as string paths)
180
    pub files: StringVec,
181
    /// Current position of drag cursor
182
    pub position: LogicalPosition,
183
    /// DOM node under cursor (potential drop target)
184
    pub drop_target: OptionDomNodeId,
185
    /// Allowed drop effect
186
    pub drop_effect: DropEffect,
187
}
188

            
189
/// Drop effect — the operation that will happen if the data is dropped
190
/// on the current target (HTML5 `DataTransfer.dropEffect`).
191
///
192
/// This is a strict subset of `DragEffect`: a drop target selects one of
193
/// these four outcomes, which must also be allowed by the source's
194
/// `effect_allowed`.
195
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
196
#[repr(C)]
197
pub enum DropEffect {
198
    /// No drop allowed / the drop is rejected. Default.
199
    #[default]
200
    None,
201
    /// Drop will copy the data (source retains its copy).
202
    Copy,
203
    /// Drop will create a link/shortcut to the data.
204
    Link,
205
    /// Drop will move the data (source should remove its copy).
206
    Move,
207
}
208

            
209
/// Allowed drag effects — the set of operations the drag source permits
210
/// (HTML5 `DataTransfer.effectAllowed`).
211
///
212
/// The drop target's `DropEffect` must be a member of this set for the
213
/// drop to succeed. Semantic superset of `DropEffect` that adds the
214
/// HTML5 combined-permission values (`CopyLink`, `CopyMove`, `LinkMove`,
215
/// `All`) and the pre-drag `Uninitialized` sentinel.
216
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
217
#[repr(C)]
218
pub enum DragEffect {
219
    /// Allowed set has not been initialized yet (equivalent to `All` in
220
    /// most user agents). Default for fresh drags.
221
    #[default]
222
    Uninitialized,
223
    /// No drop is permitted.
224
    None,
225
    /// Only Copy is permitted.
226
    Copy,
227
    /// Copy or Link is permitted.
228
    CopyLink,
229
    /// Copy or Move is permitted.
230
    CopyMove,
231
    /// Only Link is permitted.
232
    Link,
233
    /// Link or Move is permitted.
234
    LinkMove,
235
    /// Only Move is permitted.
236
    Move,
237
    /// Any of Copy, Link, or Move is permitted.
238
    All,
239
}
240

            
241
/// FFI-safe (`mime_type`, `data`) pair used by [`DragData`] in place of
242
/// a `BTreeMap<AzString, Vec<u8>>` entry.
243
#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
244
#[repr(C)]
245
pub struct MimeTypeData {
246
    pub mime_type: AzString,
247
    pub data: U8Vec,
248
}
249

            
250
impl_option!(
251
    MimeTypeData,
252
    OptionMimeTypeData,
253
    copy = false,
254
    [Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash]
255
);
256

            
257
impl_vec!(
258
    MimeTypeData,
259
    MimeTypeDataVec,
260
    MimeTypeDataVecDestructor,
261
    MimeTypeDataVecDestructorType,
262
    MimeTypeDataVecSlice,
263
    OptionMimeTypeData
264
);
265
impl_vec_mut!(MimeTypeData, MimeTypeDataVec);
266
impl_vec_debug!(MimeTypeData, MimeTypeDataVec);
267
impl_vec_partialord!(MimeTypeData, MimeTypeDataVec);
268
impl_vec_ord!(MimeTypeData, MimeTypeDataVec);
269
impl_vec_clone!(MimeTypeData, MimeTypeDataVec, MimeTypeDataVecDestructor);
270
impl_vec_partialeq!(MimeTypeData, MimeTypeDataVec);
271
impl_vec_eq!(MimeTypeData, MimeTypeDataVec);
272
impl_vec_hash!(MimeTypeData, MimeTypeDataVec);
273

            
274
/// Drag data (HTML5 `DataTransfer`).
275
///
276
/// Holds the payload(s) being transferred during a drag operation, keyed
277
/// by MIME type, plus the set of operations the source allows.
278
#[derive(Debug, Default, Clone, PartialEq, Eq)]
279
#[repr(C)]
280
pub struct DragData {
281
    /// MIME type -> data mapping (vec-of-pairs for FFI compatibility).
282
    ///
283
    /// e.g., `"text/plain" -> "Hello World"`.
284
    pub data: MimeTypeDataVec,
285
    /// Set of drag operations the source permits for this drag.
286
    pub effect_allowed: DragEffect,
287
}
288

            
289
impl DragData {
290
    /// Create new empty drag data
291
    #[must_use]
292
75
    pub const fn new() -> Self {
293
75
        Self {
294
75
            data: MimeTypeDataVec::new(),
295
75
            effect_allowed: DragEffect::Uninitialized,
296
75
        }
297
75
    }
298

            
299
    /// Set data for a MIME type. Replaces any existing entry for the
300
    /// same MIME type.
301
1038
    pub fn set_data(&mut self, mime_type: impl Into<AzString>, data: Vec<u8>) {
302
1038
        let mime_type = mime_type.into();
303
1038
        let value: U8Vec = data.into();
304
1038
        if let Some(entry) = self
305
1038
            .data
306
1038
            .as_mut()
307
1038
            .iter_mut()
308
499508
            .find(|e| e.mime_type == mime_type)
309
3
        {
310
3
            entry.data = value;
311
1035
        } else {
312
1035
            self.data.push(MimeTypeData {
313
1035
                mime_type,
314
1035
                data: value,
315
1035
            });
316
1035
        }
317
1038
    }
318

            
319
    /// Get data for a MIME type
320
    #[must_use]
321
82
    pub fn get_data(&self, mime_type: &str) -> Option<&[u8]> {
322
82
        self.data
323
82
            .as_ref()
324
82
            .iter()
325
2080
            .find(|e| e.mime_type.as_str() == mime_type)
326
82
            .map(|e| e.data.as_ref())
327
82
    }
328

            
329
    /// Set plain text data
330
15
    pub fn set_text(&mut self, text: impl Into<AzString>) {
331
15
        let text_str = text.into();
332
15
        self.set_data("text/plain", text_str.as_str().as_bytes().to_vec());
333
15
    }
334

            
335
    /// Get plain text data
336
    #[must_use]
337
17
    pub fn get_text(&self) -> Option<AzString> {
338
17
        self.get_data("text/plain")
339
17
            .map(|bytes| AzString::from(core::str::from_utf8(bytes).unwrap_or("")))
340
17
    }
341
}
342

            
343
/// The unified drag context.
344
///
345
/// This struct wraps `ActiveDragType` and provides common metadata
346
/// that applies to all drag operations.
347
///
348
/// Note: this type is Rust-only and not exposed through the C API.
349
#[derive(Debug, Clone, PartialEq)]
350
pub struct DragContext {
351
    /// The specific type of drag operation
352
    pub drag_type: ActiveDragType,
353
    /// Session ID from gesture detection (links back to `GestureManager`)
354
    pub session_id: u64,
355
    /// Whether the drag has been cancelled (e.g., Escape pressed)
356
    pub cancelled: bool,
357
}
358

            
359
impl DragContext {
360
    /// Create a new drag context
361
    #[must_use]
362
907
    pub const fn new(drag_type: ActiveDragType, session_id: u64) -> Self {
363
907
        Self {
364
907
            drag_type,
365
907
            session_id,
366
907
            cancelled: false,
367
907
        }
368
907
    }
369

            
370
    /// Create a text selection drag
371
    #[must_use]
372
14
    pub const fn text_selection(
373
14
        dom_id: DomId,
374
14
        anchor_ifc_node: NodeId,
375
14
        start_mouse_position: LogicalPosition,
376
14
        session_id: u64,
377
14
    ) -> Self {
378
14
        Self::new(
379
14
            ActiveDragType::TextSelection(TextSelectionDrag {
380
14
                dom_id,
381
14
                anchor_ifc_node,
382
14
                anchor_cursor: None,
383
14
                start_mouse_position,
384
14
                current_mouse_position: start_mouse_position,
385
14
            }),
386
14
            session_id,
387
        )
388
14
    }
389

            
390
    /// Create a scrollbar thumb drag
391
    #[must_use]
392
46
    pub const fn scrollbar_thumb(
393
46
        dom_id: DomId,
394
46
        scroll_container_node: NodeId,
395
46
        axis: ScrollbarAxis,
396
46
        start_mouse_position: LogicalPosition,
397
46
        start_scroll_offset: f32,
398
46
        track_length_px: f32,
399
46
        content_length_px: f32,
400
46
        viewport_length_px: f32,
401
46
        session_id: u64,
402
46
    ) -> Self {
403
46
        Self::new(
404
46
            ActiveDragType::ScrollbarThumb(ScrollbarThumbDrag {
405
46
                dom_id,
406
46
                scroll_container_node,
407
46
                axis,
408
46
                start_mouse_position,
409
46
                start_scroll_offset,
410
46
                current_mouse_position: start_mouse_position,
411
46
                track_length_px,
412
46
                content_length_px,
413
46
                viewport_length_px,
414
46
            }),
415
46
            session_id,
416
        )
417
46
    }
418

            
419
    /// Create a node drag
420
    #[must_use]
421
323
    pub const fn node_drag(
422
323
        dom_id: DomId,
423
323
        node_id: NodeId,
424
323
        start_position: LogicalPosition,
425
323
        drag_data: DragData,
426
323
        session_id: u64,
427
323
    ) -> Self {
428
323
        Self::new(
429
323
            ActiveDragType::Node(NodeDrag {
430
323
                dom_id,
431
323
                node_id,
432
323
                start_position,
433
323
                current_position: start_position,
434
323
                drag_offset: LogicalPosition::zero(),
435
323
                current_drop_target: OptionDomNodeId::None,
436
323
                previous_drop_target: OptionDomNodeId::None,
437
323
                drag_data,
438
323
                drop_accepted: false,
439
323
                drop_effect: DropEffect::None,
440
323
            }),
441
323
            session_id,
442
        )
443
323
    }
444

            
445
    /// Create a window move drag
446
    #[must_use]
447
76
    pub const fn window_move(
448
76
        start_position: LogicalPosition,
449
76
        initial_window_position: WindowPosition,
450
76
        session_id: u64,
451
76
    ) -> Self {
452
76
        Self::new(
453
76
            ActiveDragType::WindowMove(WindowMoveDrag {
454
76
                start_position,
455
76
                current_position: start_position,
456
76
                initial_window_position,
457
76
            }),
458
76
            session_id,
459
        )
460
76
    }
461

            
462
    /// Create a file drop drag
463
    #[must_use]
464
29
    pub fn file_drop(files: Vec<AzString>, position: LogicalPosition, session_id: u64) -> Self {
465
29
        Self::new(
466
29
            ActiveDragType::FileDrop(FileDropDrag {
467
29
                files: files.into(),
468
29
                position,
469
29
                drop_target: OptionDomNodeId::None,
470
29
                drop_effect: DropEffect::Copy,
471
29
            }),
472
29
            session_id,
473
        )
474
29
    }
475

            
476
    /// Update the current mouse position for all drag types
477
1058
    pub const fn update_position(&mut self, position: LogicalPosition) {
478
1058
        match &mut self.drag_type {
479
3
            ActiveDragType::TextSelection(ref mut drag) => {
480
3
                drag.current_mouse_position = position;
481
3
            }
482
1037
            ActiveDragType::ScrollbarThumb(ref mut drag) => {
483
1037
                drag.current_mouse_position = position;
484
1037
            }
485
4
            ActiveDragType::Node(ref mut drag) => {
486
4
                drag.current_position = position;
487
4
            }
488
7
            ActiveDragType::WindowMove(ref mut drag) => {
489
7
                drag.current_position = position;
490
7
            }
491
4
            ActiveDragType::WindowResize(ref mut drag) => {
492
4
                drag.current_position = position;
493
4
            }
494
3
            ActiveDragType::FileDrop(ref mut drag) => {
495
3
                drag.position = position;
496
3
            }
497
        }
498
1058
    }
499

            
500
    /// Get the current mouse position
501
    #[must_use]
502
23
    pub const fn current_position(&self) -> LogicalPosition {
503
23
        match &self.drag_type {
504
3
            ActiveDragType::TextSelection(drag) => drag.current_mouse_position,
505
4
            ActiveDragType::ScrollbarThumb(drag) => drag.current_mouse_position,
506
4
            ActiveDragType::Node(drag) => drag.current_position,
507
3
            ActiveDragType::WindowMove(drag) => drag.current_position,
508
6
            ActiveDragType::WindowResize(drag) => drag.current_position,
509
3
            ActiveDragType::FileDrop(drag) => drag.position,
510
        }
511
23
    }
512

            
513
    /// Get the start position
514
    #[must_use]
515
15
    pub const fn start_position(&self) -> LogicalPosition {
516
15
        match &self.drag_type {
517
2
            ActiveDragType::TextSelection(drag) => drag.start_mouse_position,
518
3
            ActiveDragType::ScrollbarThumb(drag) => drag.start_mouse_position,
519
2
            ActiveDragType::Node(drag) => drag.start_position,
520
2
            ActiveDragType::WindowMove(drag) => drag.start_position,
521
4
            ActiveDragType::WindowResize(drag) => drag.start_position,
522
2
            ActiveDragType::FileDrop(drag) => drag.position, // No start for file drops
523
        }
524
15
    }
525

            
526
    /// Check if this is a text selection drag
527
    #[must_use]
528
9
    pub const fn is_text_selection(&self) -> bool {
529
9
        matches!(self.drag_type, ActiveDragType::TextSelection(_))
530
9
    }
531

            
532
    /// Check if this is a scrollbar thumb drag
533
    #[must_use]
534
9
    pub const fn is_scrollbar_thumb(&self) -> bool {
535
9
        matches!(self.drag_type, ActiveDragType::ScrollbarThumb(_))
536
9
    }
537

            
538
    /// Check if this is a node drag
539
    #[must_use]
540
72
    pub const fn is_node_drag(&self) -> bool {
541
72
        matches!(self.drag_type, ActiveDragType::Node(_))
542
72
    }
543

            
544
    /// Check if this is a window move drag
545
    #[must_use]
546
12
    pub const fn is_window_move(&self) -> bool {
547
12
        matches!(self.drag_type, ActiveDragType::WindowMove(_))
548
12
    }
549

            
550
    /// Check if this is a file drop
551
    #[must_use]
552
7
    pub const fn is_file_drop(&self) -> bool {
553
7
        matches!(self.drag_type, ActiveDragType::FileDrop(_))
554
7
    }
555

            
556
    /// Get as text selection drag (if applicable)
557
    #[must_use]
558
14
    pub const fn as_text_selection(&self) -> Option<&TextSelectionDrag> {
559
14
        match &self.drag_type {
560
8
            ActiveDragType::TextSelection(drag) => Some(drag),
561
6
            _ => None,
562
        }
563
14
    }
564

            
565
    /// Get as mutable text selection drag (if applicable)
566
7
    pub const fn as_text_selection_mut(&mut self) -> Option<&mut TextSelectionDrag> {
567
7
        match &mut self.drag_type {
568
2
            ActiveDragType::TextSelection(drag) => Some(drag),
569
5
            _ => None,
570
        }
571
7
    }
572

            
573
    /// Get as scrollbar thumb drag (if applicable)
574
    #[must_use]
575
147
    pub const fn as_scrollbar_thumb(&self) -> Option<&ScrollbarThumbDrag> {
576
147
        match &self.drag_type {
577
125
            ActiveDragType::ScrollbarThumb(drag) => Some(drag),
578
22
            _ => None,
579
        }
580
147
    }
581

            
582
    /// Get as mutable scrollbar thumb drag (if applicable)
583
7
    pub const fn as_scrollbar_thumb_mut(&mut self) -> Option<&mut ScrollbarThumbDrag> {
584
7
        match &mut self.drag_type {
585
2
            ActiveDragType::ScrollbarThumb(drag) => Some(drag),
586
5
            _ => None,
587
        }
588
7
    }
589

            
590
    /// Get as node drag (if applicable)
591
    #[must_use]
592
91
    pub const fn as_node_drag(&self) -> Option<&NodeDrag> {
593
91
        match &self.drag_type {
594
86
            ActiveDragType::Node(drag) => Some(drag),
595
5
            _ => None,
596
        }
597
91
    }
598

            
599
    /// Get as mutable node drag (if applicable)
600
13
    pub const fn as_node_drag_mut(&mut self) -> Option<&mut NodeDrag> {
601
13
        match &mut self.drag_type {
602
8
            ActiveDragType::Node(drag) => Some(drag),
603
5
            _ => None,
604
        }
605
13
    }
606

            
607
    /// Get as window move drag (if applicable)
608
    #[must_use]
609
20
    pub const fn as_window_move(&self) -> Option<&WindowMoveDrag> {
610
20
        match &self.drag_type {
611
13
            ActiveDragType::WindowMove(drag) => Some(drag),
612
7
            _ => None,
613
        }
614
20
    }
615

            
616
    /// Get as file drop (if applicable)
617
    #[must_use]
618
14
    pub const fn as_file_drop(&self) -> Option<&FileDropDrag> {
619
14
        match &self.drag_type {
620
9
            ActiveDragType::FileDrop(drag) => Some(drag),
621
5
            _ => None,
622
        }
623
14
    }
624

            
625
    /// Get as mutable file drop (if applicable)
626
8
    pub const fn as_file_drop_mut(&mut self) -> Option<&mut FileDropDrag> {
627
8
        match &mut self.drag_type {
628
3
            ActiveDragType::FileDrop(drag) => Some(drag),
629
5
            _ => None,
630
        }
631
8
    }
632

            
633
    /// Calculate scroll delta for scrollbar thumb drag
634
    ///
635
    /// Returns the new scroll offset based on current mouse position.
636
    #[must_use]
637
134
    pub fn calculate_scrollbar_scroll_offset(&self) -> Option<f32> {
638
134
        let drag = self.as_scrollbar_thumb()?;
639

            
640
        // Calculate mouse delta along the drag axis
641
117
        let mouse_delta = match drag.axis {
642
115
            ScrollbarAxis::Vertical => drag.current_mouse_position.y - drag.start_mouse_position.y,
643
            ScrollbarAxis::Horizontal => {
644
2
                drag.current_mouse_position.x - drag.start_mouse_position.x
645
            }
646
        };
647

            
648
        // Calculate the scrollable range
649
117
        let scrollable_range = drag.content_length_px - drag.viewport_length_px;
650
        // The explicit `is_nan()` (equivalent to the old `!(x > 0.0)`) catches a NaN
651
        // scrollable_range — from a NaN, or inf-minus-inf, content/viewport length —
652
        // so it never reaches the `clamp(0.0, scrollable_range)` below, whose
653
        // f32::clamp would panic (it asserts min <= max, and NaN fails every compare).
654
117
        if scrollable_range <= 0.0 || scrollable_range.is_nan() || drag.track_length_px <= 0.0 {
655
35
            return Some(drag.start_scroll_offset);
656
82
        }
657

            
658
        // Calculate thumb length (proportional to viewport/content ratio)
659
82
        let thumb_length =
660
82
            (drag.viewport_length_px / drag.content_length_px) * drag.track_length_px;
661
82
        let scrollable_track = drag.track_length_px - thumb_length;
662

            
663
82
        if scrollable_track <= 0.0 {
664
            return Some(drag.start_scroll_offset);
665
82
        }
666

            
667
        // Convert mouse delta to scroll delta
668
82
        let scroll_ratio = mouse_delta / scrollable_track;
669
82
        let scroll_delta = scroll_ratio * scrollable_range;
670

            
671
        // Calculate new scroll offset
672
82
        let new_offset = drag.start_scroll_offset + scroll_delta;
673

            
674
        // Clamp to valid range
675
82
        Some(new_offset.clamp(0.0, scrollable_range))
676
134
    }
677

            
678
    /// Remap a drop target's `NodeId` using the old→new mapping.
679
    /// Clears the target if the old `NodeId` was removed.
680
42
    fn remap_drop_target(
681
42
        target: &mut OptionDomNodeId,
682
42
        dom_id: DomId,
683
42
        node_id_map: &alloc::collections::BTreeMap<NodeId, NodeId>,
684
42
    ) {
685
42
        let dt = match target.into_option() {
686
14
            Some(dt) if dt.dom == dom_id => dt,
687
30
            _ => return,
688
        };
689
12
        let Some(old_nid) = dt.node.into_crate_internal() else {
690
1
            return;
691
        };
692
11
        if let Some(&new_nid) = node_id_map.get(&old_nid) {
693
7
            *target = Some(DomNodeId {
694
7
                dom: dom_id,
695
7
                node: crate::styled_dom::NodeHierarchyItemId::from_crate_internal(Some(new_nid)),
696
7
            })
697
7
            .into();
698
7
        } else {
699
4
            *target = OptionDomNodeId::None;
700
4
        }
701
42
    }
702

            
703
    /// Remap `NodeIds` stored in this drag context after DOM reconciliation.
704
    ///
705
    /// When the DOM is regenerated during an active drag, `NodeIds` can change.
706
    /// This updates all stored `NodeIds` using the old→new mapping.
707
    /// Returns `false` if a critical `NodeId` was removed (drag should be cancelled).
708
46
    pub fn remap_node_ids(
709
46
        &mut self,
710
46
        dom_id: DomId,
711
46
        node_id_map: &alloc::collections::BTreeMap<NodeId, NodeId>,
712
46
    ) -> bool {
713
46
        match &mut self.drag_type {
714
5
            ActiveDragType::TextSelection(ref mut drag) => {
715
5
                if drag.dom_id != dom_id {
716
1
                    return true;
717
4
                }
718
4
                if let Some(&new_id) = node_id_map.get(&drag.anchor_ifc_node) {
719
2
                    drag.anchor_ifc_node = new_id;
720
2
                } else {
721
2
                    return false; // anchor node removed
722
                }
723
2
                true
724
            }
725
4
            ActiveDragType::ScrollbarThumb(ref mut drag) => {
726
                // Scope the remap to the DOM this drag belongs to: a different
727
                // DOM's reconciliation must not touch our scroll container id.
728
4
                if drag.dom_id != dom_id {
729
1
                    return true;
730
3
                }
731
3
                if let Some(&new_id) = node_id_map.get(&drag.scroll_container_node) {
732
2
                    drag.scroll_container_node = new_id;
733
2
                    true
734
                } else {
735
1
                    false // scroll container removed
736
                }
737
            }
738
31
            ActiveDragType::Node(ref mut drag) => {
739
31
                if drag.dom_id != dom_id {
740
                    return true;
741
31
                }
742
31
                if let Some(&new_id) = node_id_map.get(&drag.node_id) {
743
18
                    drag.node_id = new_id;
744
18
                } else {
745
13
                    return false; // dragged node removed
746
                }
747
                // Drop target remap — both current AND previous, otherwise a
748
                // stale `previous_drop_target` keeps a pre-reconciliation NodeId
749
                // and later generates spurious DragEnter/DragLeave against a
750
                // node that no longer exists (or a different node reusing the id).
751
18
                Self::remap_drop_target(&mut drag.current_drop_target, dom_id, node_id_map);
752
18
                Self::remap_drop_target(&mut drag.previous_drop_target, dom_id, node_id_map);
753
18
                true
754
            }
755
            // WindowMove, WindowResize, and FileDrop don't reference DOM NodeIds
756
3
            ActiveDragType::WindowMove(_) | ActiveDragType::WindowResize(_) => true,
757
3
            ActiveDragType::FileDrop(ref mut drag) => {
758
3
                Self::remap_drop_target(&mut drag.drop_target, dom_id, node_id_map);
759
3
                true
760
            }
761
        }
762
46
    }
763
}
764

            
765
azul_css::impl_option!(
766
    DragContext,
767
    OptionDragContext,
768
    copy = false,
769
    [Debug, Clone, PartialEq]
770
);
771

            
772
/// Drag offset from the cursor position at drag start (logical pixels).
773
/// `dx`/`dy` are the delta from drag start to current position.
774
#[derive(Default, Debug, Copy, Clone, PartialEq, PartialOrd)]
775
#[repr(C)]
776
pub struct DragDelta {
777
    pub dx: f32,
778
    pub dy: f32,
779
}
780

            
781
impl DragDelta {
782
    #[inline]
783
    #[must_use]
784
12
    pub const fn new(dx: f32, dy: f32) -> Self {
785
12
        Self { dx, dy }
786
12
    }
787
    #[inline]
788
    #[must_use]
789
3
    pub const fn zero() -> Self {
790
3
        Self::new(0.0, 0.0)
791
3
    }
792
}
793

            
794
impl_option!(
795
    DragDelta,
796
    OptionDragDelta,
797
    [Debug, Copy, Clone, PartialEq, PartialOrd]
798
);
799

            
800
#[cfg(test)]
801
#[path = "drag_test.rs"]
802
mod drag_test;