Skip to main content

dioxus_dnd/
canvas.rs

1#![doc = include_str!("../docs/api/canvas.md")]
2
3use std::rc::Rc;
4
5use dioxus::prelude::*;
6
7use crate::core::{
8    use_dnd, use_zone_id, use_zone_registry, DragMode, DropOutcome, ParentZone, Point, Rect,
9    ZoneId, ZoneRecord,
10};
11
12/// A payload dropped at a position on the canvas.
13///
14/// Non-exhaustive: emitted by the zone, only ever consumed by callers, and
15/// likely to grow context fields (modifiers, effect) - destructure with `..`.
16#[derive(Debug, Clone, PartialEq)]
17#[non_exhaustive]
18pub struct CanvasDrop<T> {
19    pub payload: T,
20    /// Top-left position for the dropped element, relative to the canvas -
21    /// already corrected for grab offset, snapping, and bounds.
22    pub position: Point,
23    /// The raw pointer position relative to the canvas, untouched.
24    pub pointer: Point,
25}
26
27/// Snap positions to a square grid.
28#[derive(Debug, Clone, Copy, PartialEq)]
29pub struct SnapGrid(pub f64);
30
31impl SnapGrid {
32    pub fn snap(&self, p: Point) -> Point {
33        if self.0 <= 0.0 {
34            return p;
35        }
36        Point::new(
37            (p.x / self.0).round() * self.0,
38            (p.y / self.0).round() * self.0,
39        )
40    }
41}
42
43/// Where a keyboard-driven canvas drop should place its pointer.
44///
45/// Pointer drops use their event geometry. This policy is only applied when
46/// the completed drop came from keyboard interaction.
47#[derive(Debug, Clone, Copy, PartialEq, Default)]
48pub enum CanvasKeyboardPlacement {
49    /// Use the selected zone geometry supplied by core keyboard navigation.
50    #[default]
51    Center,
52    /// Place at the canvas origin.
53    Origin,
54    /// Place at a fixed canvas-local point.
55    Fixed(Point),
56}
57
58/// Clamp reported top-left positions into `0..=width` × `0..=height`.
59///
60/// Bounds constrain the drop position returned in [`CanvasDrop::position`].
61/// They do not account for the dropped element's own width or height; subtract
62/// that yourself when you need the whole element to stay inside the canvas.
63#[derive(Debug, Clone, Copy, PartialEq)]
64pub struct Bounds {
65    pub width: f64,
66    pub height: f64,
67}
68
69impl Bounds {
70    pub fn clamp(&self, p: Point) -> Point {
71        Point::new(
72            clamp_axis(p.x, 0.0, self.width),
73            clamp_axis(p.y, 0.0, self.height),
74        )
75    }
76
77    /// Clamp a top-left position so an item of `width` × `height` stays fully
78    /// inside these bounds. If the item is larger than the bounds on an axis,
79    /// that axis pins to zero.
80    pub fn clamp_item(&self, p: Point, width: f64, height: f64) -> Point {
81        Point::new(
82            clamp_axis(p.x, 0.0, self.width - width),
83            clamp_axis(p.y, 0.0, self.height - height),
84        )
85    }
86
87    /// Clamp a rectangle by moving its top-left corner so the whole rectangle
88    /// stays inside these bounds. The returned point is the corrected
89    /// top-left.
90    pub fn clamp_rect(&self, rect: Rect) -> Point {
91        self.clamp_item(Point::new(rect.x, rect.y), rect.width, rect.height)
92    }
93}
94
95/// Convert a viewport/client point to canvas-local coordinates.
96pub fn client_to_canvas(client: Point, canvas_rect: Rect) -> Point {
97    client - canvas_rect.origin()
98}
99
100/// Convert a canvas-local point to viewport/client coordinates.
101pub fn canvas_to_client(point: Point, canvas_rect: Rect) -> Point {
102    point + canvas_rect.origin()
103}
104
105/// Compute the corrected top-left canvas placement from a raw canvas-relative
106/// pointer position and grab offset, then apply optional snap and bounds.
107pub fn canvas_position(
108    pointer: Point,
109    grab: Point,
110    snap: Option<SnapGrid>,
111    bounds: Option<Bounds>,
112) -> Point {
113    let mut position = pointer - grab;
114    if let Some(g) = snap {
115        position = g.snap(position);
116    }
117    if let Some(b) = bounds {
118        position = b.clamp(position);
119    }
120    position
121}
122
123/// Resolve the canvas-local pointer for a keyboard drop.
124pub fn canvas_keyboard_pointer(policy: CanvasKeyboardPlacement, element: Point) -> Point {
125    match policy {
126        CanvasKeyboardPlacement::Center => element,
127        CanvasKeyboardPlacement::Origin => Point::default(),
128        CanvasKeyboardPlacement::Fixed(point) => point,
129    }
130}
131
132fn clamp_axis(v: f64, min: f64, max: f64) -> f64 {
133    // std `f64::clamp` panics when a bound is NaN or when min > max. Treat a
134    // NaN bound as "unconstrained" on that side (rather than snapping the item
135    // to the origin), and an inverted *finite* range - e.g. an item larger than
136    // the container - pins to `min`, matching KeepInside's oversized behavior.
137    let lo = if min.is_nan() { f64::NEG_INFINITY } else { min };
138    let hi = if max.is_nan() { f64::INFINITY } else { max };
139    if lo > hi {
140        return if min.is_nan() { v } else { min };
141    }
142    v.clamp(lo, hi)
143}
144
145/// A canvas that reports drop positions.
146///
147/// Uses the shared `DndContext<T>`; start drags with the core `Draggable`
148/// (its recorded grab offset is what makes the drop position feel exact -
149/// the element lands where its ghost was, not where the pointer tip was).
150///
151/// While a drag is in flight the div carries `data-active="true"` (absent
152/// otherwise) - style the canvas as a target then, e.g. Tailwind
153/// `data-active:outline-dashed`.
154#[component]
155pub fn CanvasDropZone<T: Clone + PartialEq + 'static>(
156    /// Stable identity; auto-generated if omitted.
157    #[props(default)]
158    id: Option<ZoneId>,
159    /// Snap the corrected position to a grid.
160    #[props(default)]
161    snap: Option<SnapGrid>,
162    /// Clamp the corrected top-left position into these bounds.
163    #[props(default)]
164    bounds: Option<Bounds>,
165    /// Placement policy for keyboard-driven canvas drops.
166    #[props(default)]
167    keyboard: CanvasKeyboardPlacement,
168    /// Announced to screen readers when a keyboard drag targets the canvas.
169    #[props(default)]
170    label: Option<String>,
171    on_drop: EventHandler<CanvasDrop<T>>,
172    #[props(extends = div, extends = GlobalAttributes)] attributes: Vec<Attribute>,
173    children: Element,
174) -> Element {
175    let dnd = use_dnd::<T>();
176    let mut registry = use_zone_registry::<T>();
177    let auto_id = use_zone_id();
178    let zone_id = id.unwrap_or(auto_id);
179
180    // Mirror `snap`/`bounds` into signals so the registry callback - which is
181    // registered once (first render) - reads the *current* values, not the
182    // ones captured at mount. Keep them current during render so child probes
183    // and same-frame drops observe the latest geometry.
184    let mut snap_now = use_signal(|| snap);
185    let mut bounds_now = use_signal(|| bounds);
186    let mut keyboard_now = use_signal(|| keyboard);
187    if *snap_now.peek() != snap {
188        snap_now.set(snap);
189    }
190    if *bounds_now.peek() != bounds {
191        bounds_now.set(bounds);
192    }
193    if *keyboard_now.peek() != keyboard {
194        keyboard_now.set(keyboard);
195    }
196
197    // Turn a corrected drop at `pointer` (canvas-relative) into a CanvasDrop.
198    let place = move |payload: T, pointer: Point, grab: Point| {
199        let position = canvas_position(pointer, grab, *snap_now.peek(), *bounds_now.peek());
200        on_drop.call(CanvasDrop {
201            payload,
202            position,
203            pointer,
204        });
205    };
206
207    // Register as a zone so pointer and keyboard drags can drop here. The
208    // registry delivers a `DropOutcome`; `element` is the pointer relative to
209    // the canvas and `grab` is the pickup offset.
210    let parent = try_use_context::<ParentZone>().map(|p| p.0);
211    let registered_drop = Callback::new(move |o: DropOutcome<T>| {
212        let pointer = if o.mode == DragMode::Keyboard {
213            canvas_keyboard_pointer(*keyboard_now.peek(), o.element)
214        } else {
215            o.element
216        };
217        place(o.payload, pointer, o.grab);
218    });
219    let registration = use_hook(|| {
220        registry.register(ZoneRecord {
221            id: zone_id,
222            parent,
223            label: label.clone(),
224            on_drop: registered_drop,
225            accepts: None,
226            mounted: None,
227            rect: None,
228        })
229    });
230    use_drop(move || {
231        registry.unregister(zone_id);
232    });
233    // Keep the registered label in sync if the prop changes across renders.
234    // Registry readers only `peek`, so this render-time write can't loop.
235    registry.sync_label(zone_id, label.clone());
236
237    rsx! {
238        div {
239            "data-active": if dnd.dragging() { "true" },
240            onmounted: move |evt: Event<MountedData>| {
241                let m: Rc<MountedData> = evt.data();
242                let mut registry = registry;
243                registry.set_mounted(registration, m.clone());
244                spawn(async move {
245                    if let Ok(r) = m.get_client_rect().await {
246                        registry.set_rect_if_present(registration, Rect::new(
247                            r.origin.x,
248                            r.origin.y,
249                            r.size.width,
250                            r.size.height,
251                        ));
252                    }
253                });
254            },
255            ..attributes,
256            {children}
257        }
258    }
259}
260
261#[cfg(test)]
262mod tests {
263    use super::*;
264
265    #[test]
266    fn snap_and_clamp() {
267        let g = SnapGrid(10.0);
268        let p = g.snap(Point::new(14.9, 15.1));
269        assert_eq!((p.x, p.y), (10.0, 20.0));
270        assert_eq!(
271            SnapGrid(0.0).snap(Point::new(3.3, 4.4)),
272            Point::new(3.3, 4.4)
273        );
274
275        let b = Bounds {
276            width: 100.0,
277            height: 50.0,
278        };
279        let p = b.clamp(Point::new(-5.0, 999.0));
280        assert_eq!((p.x, p.y), (0.0, 50.0));
281
282        let corrected = Point::new(107.0, 46.0) - Point::new(9.0, 8.0);
283        let positioned = b.clamp(g.snap(corrected));
284        assert_eq!(positioned, Point::new(100.0, 40.0));
285    }
286
287    #[test]
288    fn clamp_does_not_panic_on_non_finite_bounds() {
289        // Caller-supplied NaN/inf bounds must not panic (std `f64::clamp`
290        // would). A NaN bound is treated as unconstrained on that axis, and a
291        // negative position still can't go below the origin.
292        let b = Bounds {
293            width: f64::NAN,
294            height: f64::INFINITY,
295        };
296        let p = b.clamp(Point::new(25.0, 25.0));
297        assert_eq!((p.x, p.y), (25.0, 25.0), "unconstrained, unchanged");
298        let p = b.clamp(Point::new(-10.0, -10.0));
299        assert_eq!((p.x, p.y), (0.0, 0.0), "still floored at the origin");
300        // clamp_item is NaN-guarded via clamp_axis too.
301        let q = b.clamp_item(Point::new(-3.0, 10.0), 5.0, 5.0);
302        assert_eq!(q.x, 0.0);
303    }
304
305    #[test]
306    fn bounds_can_clamp_whole_items() {
307        let b = Bounds {
308            width: 100.0,
309            height: 50.0,
310        };
311
312        assert_eq!(
313            b.clamp_item(Point::new(90.0, 45.0), 20.0, 12.0),
314            Point::new(80.0, 38.0)
315        );
316        assert_eq!(
317            b.clamp_rect(Rect::new(-5.0, 60.0, 20.0, 10.0)),
318            Point::new(0.0, 40.0)
319        );
320        assert_eq!(
321            b.clamp_item(Point::new(20.0, 20.0), 150.0, 80.0),
322            Point::new(0.0, 0.0)
323        );
324    }
325
326    #[test]
327    fn coordinate_helpers_convert_between_client_and_canvas() {
328        let rect = Rect::new(40.0, 80.0, 320.0, 200.0);
329        let client = Point::new(64.0, 128.0);
330        let canvas = client_to_canvas(client, rect);
331
332        assert_eq!(canvas, Point::new(24.0, 48.0));
333        assert_eq!(canvas_to_client(canvas, rect), client);
334    }
335
336    #[test]
337    fn canvas_position_applies_grab_snap_then_bounds() {
338        let p = canvas_position(
339            Point::new(107.0, 46.0),
340            Point::new(9.0, 8.0),
341            Some(SnapGrid(10.0)),
342            Some(Bounds {
343                width: 100.0,
344                height: 50.0,
345            }),
346        );
347
348        assert_eq!(p, Point::new(100.0, 40.0));
349    }
350
351    #[test]
352    fn canvas_keyboard_pointer_uses_center_element_by_default() {
353        assert_eq!(
354            canvas_keyboard_pointer(CanvasKeyboardPlacement::default(), Point::new(40.0, 20.0)),
355            Point::new(40.0, 20.0)
356        );
357    }
358
359    #[test]
360    fn canvas_keyboard_pointer_can_use_origin() {
361        assert_eq!(
362            canvas_keyboard_pointer(CanvasKeyboardPlacement::Origin, Point::new(40.0, 20.0)),
363            Point::default()
364        );
365    }
366
367    #[test]
368    fn canvas_keyboard_pointer_can_use_fixed_point() {
369        assert_eq!(
370            canvas_keyboard_pointer(
371                CanvasKeyboardPlacement::Fixed(Point::new(12.0, 18.0)),
372                Point::new(40.0, 20.0),
373            ),
374            Point::new(12.0, 18.0)
375        );
376    }
377
378    #[test]
379    fn item_clamp_composes_after_canvas_position() {
380        let top_left = canvas_position(Point::new(156.0, 86.0), Point::new(4.0, 5.0), None, None);
381        let constrained = Bounds {
382            width: 160.0,
383            height: 90.0,
384        }
385        .clamp_item(top_left, 48.0, 32.0);
386
387        assert_eq!(top_left, Point::new(152.0, 81.0));
388        assert_eq!(constrained, Point::new(112.0, 58.0));
389    }
390}