use dioxus::html::input_data::MouseButton;
use dioxus::prelude::*;
use super::structure::use_direction;
use crate::class::compose;
use crate::{ButtonSize, ButtonVariant};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum KanbanMoveInput {
Keyboard,
Pointer,
}
impl KanbanMoveInput {
pub fn as_str(self) -> &'static str {
match self {
Self::Keyboard => "keyboard",
Self::Pointer => "pointer",
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct KanbanMoveDetail {
pub before_id: Option<String>,
pub from_column: String,
pub input: KanbanMoveInput,
pub item_id: String,
pub to_column: String,
}
impl KanbanMoveDetail {
pub fn new(
item_id: &str,
from_column: &str,
to_column: &str,
input: KanbanMoveInput,
before_id: Option<&str>,
) -> Option<Self> {
let item_id = item_id.trim();
let from_column = from_column.trim();
let to_column = to_column.trim();
if item_id.is_empty() || from_column.is_empty() || to_column.is_empty() {
return None;
}
Some(Self {
before_id: before_id
.map(str::trim)
.filter(|id| !id.is_empty())
.map(str::to_string),
from_column: from_column.to_string(),
input,
item_id: item_id.to_string(),
to_column: to_column.to_string(),
})
}
}
pub fn adjacent_kanban_column<'a>(
columns: &'a [String],
current: &str,
forward: bool,
right_to_left: bool,
) -> Option<&'a str> {
let index = columns.iter().position(|column| column == current)?;
let next = if forward == right_to_left {
index.checked_sub(1)?
} else {
index + 1
};
columns.get(next).map(String::as_str)
}
#[derive(Clone, Debug, PartialEq)]
struct KanbanDrag {
item_id: String,
from_column: String,
start: (f64, f64),
active: bool,
}
const DRAG_THRESHOLD: f64 = 8.0;
#[derive(Clone, Copy)]
struct KanbanContext {
next_order: CopyValue<usize>,
columns: Signal<Vec<(usize, String)>>,
on_move: Signal<Option<EventHandler<KanbanMoveDetail>>>,
drag: Signal<Option<KanbanDrag>>,
drop_target: Signal<Option<String>>,
right_to_left: Signal<bool>,
}
impl KanbanContext {
fn column_values(&self) -> Vec<String> {
let mut columns = self.columns.peek().clone();
columns.sort_by_key(|(order, _)| *order);
columns.into_iter().map(|(_, value)| value).collect()
}
fn request(&self, item_id: &str, from: &str, to: &str, input: KanbanMoveInput) {
let Some(detail) = KanbanMoveDetail::new(item_id, from, to, input, None) else {
return;
};
if let Some(handler) = *self.on_move.peek() {
handler.call(detail);
}
}
fn clear_drag(&self) {
let (mut drag, mut target) = (self.drag, self.drop_target);
if drag.peek().is_some() {
drag.set(None);
}
if target.peek().is_some() {
target.set(None);
}
}
fn active_drag(&self) -> Option<KanbanDrag> {
self.drag.peek().clone().filter(|drag| drag.active)
}
}
fn use_kanban(component: &str) -> KanbanContext {
try_use_context::<KanbanContext>()
.unwrap_or_else(|| panic!("{component} must be used inside a Lumen KanbanBoard."))
}
#[derive(Props, Clone, PartialEq)]
pub struct KanbanBoardProps {
pub on_move_request: Option<EventHandler<KanbanMoveDetail>>,
#[props(default = "0".to_string(), into)]
pub tabindex: String,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = section)]
pub attributes: Vec<Attribute>,
pub children: Element,
}
#[component]
pub fn KanbanBoard(props: KanbanBoardProps) -> Element {
let right_to_left = use_direction().is_rtl();
let mut on_move = use_signal(|| props.on_move_request);
let mut direction = use_signal(|| right_to_left);
let board = use_context_provider(|| KanbanContext {
next_order: CopyValue::new(0),
columns: Signal::new(Vec::new()),
on_move,
drag: Signal::new(None),
drop_target: Signal::new(None),
right_to_left: direction,
});
if *on_move.peek() != props.on_move_request {
on_move.set(props.on_move_request);
}
if *direction.peek() != right_to_left {
direction.set(right_to_left);
}
let class = compose([Some("ui-kanban-board ui-kanban"), props.class.as_deref()]);
rsx! {
section {
aria_orientation: "horizontal",
class,
"data-ui-kanban": "true",
tabindex: props.tabindex,
onmousemove: move |event| {
let Some(drag) = board.drag.peek().clone() else {
return;
};
if event.held_buttons().is_empty() {
board.clear_drag();
return;
}
if !drag.active {
let point = event.client_coordinates();
let distance = (point.x - drag.start.0).hypot(point.y - drag.start.1);
if distance >= DRAG_THRESHOLD {
let mut state = board.drag;
state.set(Some(KanbanDrag { active: true, ..drag }));
}
}
},
onmouseup: move |_| board.clear_drag(),
onmouseleave: move |_| board.clear_drag(),
..props.attributes,
{props.children}
}
}
}
#[derive(Clone, Copy)]
struct KanbanColumnContext(Signal<String>);
#[derive(Props, Clone, PartialEq)]
pub struct KanbanColumnProps {
#[props(into)]
pub value: String,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = section)]
pub attributes: Vec<Attribute>,
pub children: Element,
}
#[component]
pub fn KanbanColumn(props: KanbanColumnProps) -> Element {
let board = use_kanban("KanbanColumn");
let mut current = use_signal(|| props.value.clone());
use_context_provider(|| KanbanColumnContext(current));
if *current.peek() != props.value {
current.set(props.value.clone());
}
let order = use_hook(|| {
let mut next_order = board.next_order;
let order = *next_order.peek();
next_order.set(order + 1);
order
});
let mut columns = board.columns;
use_effect(use_reactive((&props.value,), move |(value,)| {
let mut list = columns.write();
list.retain(|(entry, _)| *entry != order);
list.push((order, value));
}));
use_drop(move || {
columns.write().retain(|(entry, _)| *entry != order);
});
let value = props.value.clone();
let is_target = board.drop_target.read().as_deref() == Some(value.as_str());
let class = compose([Some("ui-kanban__column"), props.class.as_deref()]);
let (move_value, up_value) = (value.clone(), value.clone());
rsx! {
section {
class,
"data-state": is_target.then_some("drop-target"),
"data-ui-kanban-column": value,
onmousemove: move |_| {
if board.active_drag().is_none() {
return;
}
let mut target = board.drop_target;
if target.peek().as_deref() != Some(move_value.as_str()) {
target.set(Some(move_value.clone()));
}
},
onmouseup: move |_| {
if let Some(drag) = board.active_drag() {
board.request(&drag.item_id, &drag.from_column, &up_value, KanbanMoveInput::Pointer);
}
board.clear_drag();
},
..props.attributes,
{props.children}
}
}
}
#[derive(Clone, Copy)]
struct KanbanItemContext {
id: Signal<String>,
busy: Signal<bool>,
}
#[derive(Props, Clone, PartialEq)]
pub struct KanbanItemProps {
#[props(into)]
pub item_id: String,
#[props(into)]
pub id: Option<String>,
#[props(default)]
pub busy: bool,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = article)]
pub attributes: Vec<Attribute>,
pub children: Element,
}
#[component]
pub fn KanbanItem(props: KanbanItemProps) -> Element {
let board = use_kanban("KanbanItem");
let mut id = use_signal(|| props.item_id.clone());
let mut busy = use_signal(|| props.busy);
use_context_provider(|| KanbanItemContext { id, busy });
if *id.peek() != props.item_id {
id.set(props.item_id.clone());
}
if *busy.peek() != props.busy {
busy.set(props.busy);
}
let dragging = board
.drag
.read()
.as_ref()
.is_some_and(|drag| drag.active && drag.item_id == props.item_id);
let element_id = props.id.clone().unwrap_or_else(|| props.item_id.clone());
rsx! {
article {
aria_busy: props.busy.then_some("true"),
class: props.class,
"data-state": dragging.then_some("dragging"),
"data-ui-kanban-item": props.item_id,
id: element_id,
..props.attributes,
{props.children}
}
}
}
fn button_size_class(size: ButtonSize) -> &'static str {
match size {
ButtonSize::Default => "ui-button--default-size",
ButtonSize::Sm => "ui-button--sm",
ButtonSize::Lg => "ui-button--lg",
ButtonSize::Icon => "ui-button--icon",
}
}
#[derive(Props, Clone, PartialEq)]
pub struct KanbanHandleProps {
#[props(default = ButtonVariant::Ghost)]
pub variant: ButtonVariant,
#[props(default = ButtonSize::Sm)]
pub size: ButtonSize,
#[props(default = "ArrowLeft ArrowRight".to_string(), into)]
pub aria_keyshortcuts: String,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = button)]
pub attributes: Vec<Attribute>,
pub children: Element,
}
#[component]
pub fn KanbanHandle(props: KanbanHandleProps) -> Element {
let board = use_kanban("KanbanHandle");
let item = try_use_context::<KanbanItemContext>()
.unwrap_or_else(|| panic!("KanbanHandle must be used inside a Lumen KanbanItem."));
let column = try_use_context::<KanbanColumnContext>()
.unwrap_or_else(|| panic!("KanbanHandle must be used inside a Lumen KanbanColumn."));
let variant = format!("ui-button--{}", props.variant.as_str());
let class = compose([
Some("ui-button"),
Some(variant.as_str()),
Some(button_size_class(props.size)),
props.class.as_deref(),
]);
let item_id = (item.id)();
rsx! {
button {
aria_keyshortcuts: props.aria_keyshortcuts,
class,
"data-slot": "button",
"data-ui-kanban-handle": item_id,
r#type: "button",
onkeydown: move |event| {
let forward = match event.key() {
Key::ArrowRight => true,
Key::ArrowLeft => false,
_ => return,
};
if *item.busy.peek() {
return;
}
let item_id = item.id.peek().clone();
let from = column.0.peek().clone();
let columns = board.column_values();
let right_to_left = *board.right_to_left.peek();
if let Some(to) = adjacent_kanban_column(&columns, &from, forward, right_to_left) {
event.prevent_default();
board.request(&item_id, &from, to, KanbanMoveInput::Keyboard);
}
},
onmousedown: move |event| {
if event.trigger_button() != Some(MouseButton::Primary) || *item.busy.peek() {
return;
}
let point = event.client_coordinates();
let mut drag = board.drag;
drag.set(Some(KanbanDrag {
item_id: item.id.peek().clone(),
from_column: column.0.peek().clone(),
start: (point.x, point.y),
active: false,
}));
},
..props.attributes,
span { class: "ui-button__content", {props.children} }
}
}
}
#[cfg(test)]
mod tests {
use super::{KanbanMoveDetail, KanbanMoveInput, adjacent_kanban_column};
fn columns() -> Vec<String> {
["planned", "active", "released"]
.iter()
.map(|column| (*column).to_string())
.collect()
}
#[test]
fn adjacent_columns_follow_direction() {
let columns = columns();
assert_eq!(
adjacent_kanban_column(&columns, "planned", true, false),
Some("active")
);
assert_eq!(
adjacent_kanban_column(&columns, "active", false, false),
Some("planned")
);
assert_eq!(
adjacent_kanban_column(&columns, "planned", false, false),
None
);
assert_eq!(
adjacent_kanban_column(&columns, "released", true, false),
None
);
assert_eq!(
adjacent_kanban_column(&columns, "active", true, true),
Some("planned")
);
assert_eq!(
adjacent_kanban_column(&columns, "active", false, true),
Some("released")
);
assert_eq!(
adjacent_kanban_column(&columns, "missing", true, false),
None
);
}
#[test]
fn move_details_trim_and_reject_blank_ids() {
let detail =
KanbanMoveDetail::new(" a ", " x ", "y", KanbanMoveInput::Keyboard, Some(" "))
.expect("valid detail");
assert_eq!(detail.item_id, "a");
assert_eq!(detail.from_column, "x");
assert_eq!(detail.before_id, None);
assert_eq!(
KanbanMoveDetail::new("a", "x", "y", KanbanMoveInput::Pointer, Some(" b "))
.and_then(|detail| detail.before_id),
Some("b".to_string())
);
assert!(KanbanMoveDetail::new(" ", "x", "y", KanbanMoveInput::Pointer, None).is_none());
assert!(KanbanMoveDetail::new("a", "", "y", KanbanMoveInput::Pointer, None).is_none());
assert!(KanbanMoveDetail::new("a", "x", "\t", KanbanMoveInput::Pointer, None).is_none());
}
}