use std::rc::Rc;
use dioxus::html::MountedData;
use dioxus::prelude::*;
use crate::core::{
element_point, use_dnd, use_zone_id, use_zone_registry, DragMode, DropOutcome, ParentZone,
Rect, ZoneRecord,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct NodeId(pub u64);
impl From<u64> for NodeId {
fn from(v: u64) -> Self {
Self(v)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DropIntent {
Before,
After,
Into,
}
#[derive(Debug, Clone, PartialEq)]
pub struct TreeDropEvent<T> {
pub payload: T,
pub target: NodeId,
pub intent: DropIntent,
}
pub fn intent_from_offset(y: f64, row_height: f64) -> DropIntent {
let h = row_height.max(1.0);
let ratio = (y / h).clamp(0.0, 1.0);
if ratio < 0.25 {
DropIntent::Before
} else if ratio > 0.75 {
DropIntent::After
} else {
DropIntent::Into
}
}
pub fn would_create_cycle(
parent_of: impl Fn(NodeId) -> Option<NodeId>,
dragged: NodeId,
target: NodeId,
) -> bool {
if dragged == target {
return true;
}
let mut cursor = Some(target);
for _ in 0..10_000 {
match cursor {
Some(n) if n == dragged => return true,
Some(n) => cursor = parent_of(n),
None => return false,
}
}
true
}
#[component]
pub fn TreeNodeTarget<T: Clone + PartialEq + 'static>(
node: NodeId,
#[props(default = 28.0)]
row_height: f64,
#[props(default)]
accepts: Option<Callback<(T, DropIntent), bool>>,
on_drop: EventHandler<TreeDropEvent<T>>,
#[props(default)]
label: Option<String>,
#[props(extends = div, extends = GlobalAttributes)] attributes: Vec<Attribute>,
children: Element,
) -> Element {
let mut dnd = use_dnd::<T>();
let mut registry = use_zone_registry::<T>();
let mut intent = use_signal(|| None::<DropIntent>);
let zone_id = use_zone_id();
let parent = try_use_context::<ParentZone>().map(|p| p.0);
let mounted = use_signal(|| None::<Rc<MountedData>>);
let rect = use_signal(|| None::<Rect>);
let registered_accepts = accepts.map(|cb| {
Callback::new(move |p: T| {
cb.call((p.clone(), DropIntent::Before))
|| cb.call((p.clone(), DropIntent::After))
|| cb.call((p, DropIntent::Into))
})
});
let registered_drop = Callback::new(move |o: DropOutcome<T>| {
let it = intent_from_offset(o.element.y, row_height);
let ok = accepts.map_or(true, |cb| cb.call((o.payload.clone(), it)));
if ok {
on_drop.call(TreeDropEvent {
payload: o.payload,
target: node,
intent: it,
});
}
});
use_hook(|| {
registry.register(ZoneRecord {
id: zone_id,
parent,
label: label.clone(),
on_drop: registered_drop,
accepts: registered_accepts,
mounted,
rect,
});
});
use_drop(move || {
registry.unregister(zone_id);
});
let display_intent = move || -> Option<DropIntent> {
if let Some(it) = intent() {
return Some(it);
}
if dnd.dragging() && dnd.mode() == DragMode::Pointer && dnd.over() == Some(zone_id) {
let r = (*rect.peek())?;
return Some(intent_from_offset(dnd.pointer().y - r.y, row_height));
}
None
};
let intent_str = move || match display_intent() {
Some(DropIntent::Before) => "before",
Some(DropIntent::After) => "after",
Some(DropIntent::Into) => "into",
None => "",
};
rsx! {
div {
"data-intent": intent_str(),
onmounted: move |evt: Event<MountedData>| {
let m: Rc<MountedData> = evt.data();
let mut mounted = mounted;
let mut rect = rect;
mounted.set(Some(m.clone()));
spawn(async move {
if let Ok(r) = m.get_client_rect().await {
rect.set(Some(Rect::new(
r.origin.x,
r.origin.y,
r.size.width,
r.size.height,
)));
}
});
},
ondragover: move |evt: DragEvent| {
if !dnd.dragging() {
return;
}
let it = intent_from_offset(element_point(&evt).y, row_height);
let ok = match (&accepts, dnd.payload()) {
(Some(cb), Some(p)) => cb.call((p, it)),
(None, Some(_)) => true,
_ => false,
};
if ok {
evt.prevent_default();
if intent() != Some(it) {
intent.set(Some(it));
}
} else if intent().is_some() {
intent.set(None);
}
},
ondragleave: move |_| {
intent.set(None);
},
ondrop: move |evt: DragEvent| {
evt.prevent_default();
evt.stop_propagation();
let it = intent_from_offset(element_point(&evt).y, row_height);
intent.set(None);
let ok = match (&accepts, dnd.payload()) {
(Some(cb), Some(p)) => cb.call((p, it)),
(None, Some(_)) => true,
_ => false,
};
if !ok {
return;
}
if let Some((payload, _)) = dnd.take() {
on_drop.call(TreeDropEvent { payload, target: node, intent: it });
}
},
..attributes,
{children}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn intent_bands() {
assert_eq!(intent_from_offset(2.0, 28.0), DropIntent::Before);
assert_eq!(intent_from_offset(14.0, 28.0), DropIntent::Into);
assert_eq!(intent_from_offset(26.0, 28.0), DropIntent::After);
assert_eq!(intent_from_offset(0.0, 0.0), DropIntent::Before);
}
#[test]
fn cycle_detection() {
let parent = |n: NodeId| match n.0 {
3 => Some(NodeId(2)),
2 => Some(NodeId(1)),
_ => None,
};
assert!(would_create_cycle(parent, NodeId(1), NodeId(3)));
assert!(would_create_cycle(parent, NodeId(2), NodeId(2)));
assert!(!would_create_cycle(parent, NodeId(3), NodeId(1)));
}
}