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#[derive(Debug, Clone, PartialEq)]
17#[non_exhaustive]
18pub struct CanvasDrop<T> {
19 pub payload: T,
20 pub position: Point,
23 pub pointer: Point,
25}
26
27#[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#[derive(Debug, Clone, Copy, PartialEq, Default)]
48pub enum CanvasKeyboardPlacement {
49 #[default]
51 Center,
52 Origin,
54 Fixed(Point),
56}
57
58#[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 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 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
95pub fn client_to_canvas(client: Point, canvas_rect: Rect) -> Point {
97 client - canvas_rect.origin()
98}
99
100pub fn canvas_to_client(point: Point, canvas_rect: Rect) -> Point {
102 point + canvas_rect.origin()
103}
104
105pub 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
123pub 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 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#[component]
155pub fn CanvasDropZone<T: Clone + PartialEq + 'static>(
156 #[props(default)]
158 id: Option<ZoneId>,
159 #[props(default)]
161 snap: Option<SnapGrid>,
162 #[props(default)]
164 bounds: Option<Bounds>,
165 #[props(default)]
167 keyboard: CanvasKeyboardPlacement,
168 #[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 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 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 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 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 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 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}