lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
//! `KanbanBoard`, `KanbanColumn`, `KanbanItem`, and `KanbanHandle`.
//!
//! The board never moves items itself. Like `useKanban` in `@santi020k/lumen-react` and
//! `lumen-core`'s kanban helpers, it reports a [`KanbanMoveDetail`] and the app updates its data.
//!
//! - Keyboard: Left and Right arrows on a [`KanbanHandle`] request a move to the adjacent column,
//!   flipped in right-to-left layouts.
//! - Pointer: pressing a handle and releasing over another column requests a move. It uses mouse
//!   events, which every Dioxus renderer delivers, instead of HTML drag and drop, which Dioxus
//!   Native does not support. Touch dragging on the web is not implemented; the keyboard path and
//!   app-provided move actions cover it.

// cspell:words hypot keyshortcuts onmousedown onmousemove onmouseup

use dioxus::html::input_data::MouseButton;
use dioxus::prelude::*;

use super::structure::use_direction;
use crate::class::compose;
use crate::{ButtonSize, ButtonVariant};

/// How a kanban move was requested.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum KanbanMoveInput {
    /// Arrow keys on a handle.
    Keyboard,
    /// Pressing a handle and releasing over a column.
    Pointer,
}

impl KanbanMoveInput {
    /// The `lumen-core` input name.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Keyboard => "keyboard",
            Self::Pointer => "pointer",
        }
    }
}

/// A request to move a kanban item between columns, like `LumenKanbanMoveDetail`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct KanbanMoveDetail {
    /// Item to insert before in the target column, when known.
    pub before_id: Option<String>,
    /// Column the item leaves.
    pub from_column: String,
    /// How the move was requested.
    pub input: KanbanMoveInput,
    /// The moving item.
    pub item_id: String,
    /// Column the item joins.
    pub to_column: String,
}

impl KanbanMoveDetail {
    /// A trimmed move request, or `None` when the item or a column is blank, like
    /// `createLumenKanbanMoveDetail`.
    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(),
        })
    }
}

/// The column next to `current` in visual order, like `getAdjacentKanbanColumn`.
///
/// `forward` moves toward the inline end (right in left-to-right layouts); `right_to_left` flips
/// it. Returns `None` at either end or when `current` is not a column.
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,
}

/// Pointer travel, in pixels, before a press becomes a drag (matches `lumen-react`).
const DRAG_THRESHOLD: f64 = 8.0;

#[derive(Clone, Copy)]
struct KanbanContext {
    next_order: CopyValue<usize>,
    /// `(order, value)` for every mounted column.
    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."))
}

/// Props for [`KanbanBoard`].
#[derive(Props, Clone, PartialEq)]
pub struct KanbanBoardProps {
    /// Called when a handle requests a move. Update the app's data to apply it.
    pub on_move_request: Option<EventHandler<KanbanMoveDetail>>,
    /// Tab order of the scrollable board. Defaults to `0`.
    #[props(default = "0".to_string(), into)]
    pub tabindex: String,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<section>` or global attribute. Name the board with `aria_label`.
    #[props(extends = GlobalAttributes, extends = section)]
    pub attributes: Vec<Attribute>,
    /// [`KanbanColumn`]s.
    pub children: Element,
}

/// A horizontally scrolling board of [`KanbanColumn`]s.
#[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() {
                    // The button was released outside the board.
                    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>);

/// Props for [`KanbanColumn`].
#[derive(Props, Clone, PartialEq)]
pub struct KanbanColumnProps {
    /// Column identifier reported in move requests.
    #[props(into)]
    pub value: String,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<section>` or global attribute.
    #[props(extends = GlobalAttributes, extends = section)]
    pub attributes: Vec<Attribute>,
    /// A heading and the column's [`KanbanItem`]s.
    pub children: Element,
}

/// One column of a [`KanbanBoard`]. Highlights as a drop target while an item is dragged over it.
#[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>,
}

/// Props for [`KanbanItem`].
#[derive(Props, Clone, PartialEq)]
pub struct KanbanItemProps {
    /// Item identifier reported in move requests.
    #[props(into)]
    pub item_id: String,
    /// Element id. Defaults to `item_id`, like `lumen-react`.
    #[props(into)]
    pub id: Option<String>,
    /// Marks the item busy (`aria-busy`) and ignores move requests from its handle.
    #[props(default)]
    pub busy: bool,
    /// Extra classes for the item.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<article>` or global attribute.
    #[props(extends = GlobalAttributes, extends = article)]
    pub attributes: Vec<Attribute>,
    /// Card content and a [`KanbanHandle`].
    pub children: Element,
}

/// One card in a [`KanbanColumn`] (`data-ui-kanban-item`).
#[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",
    }
}

/// Props for [`KanbanHandle`].
#[derive(Props, Clone, PartialEq)]
pub struct KanbanHandleProps {
    /// Button variant. Defaults to ghost.
    #[props(default = ButtonVariant::Ghost)]
    pub variant: ButtonVariant,
    /// Button size. Defaults to small.
    #[props(default = ButtonSize::Sm)]
    pub size: ButtonSize,
    /// Keyboard shortcuts announced to assistive technology.
    #[props(default = "ArrowLeft ArrowRight".to_string(), into)]
    pub aria_keyshortcuts: String,
    /// Extra classes appended after the button classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<button>` or global attribute. Give it an `aria_label` such as "Move Release
    /// notes".
    #[props(extends = GlobalAttributes, extends = button)]
    pub attributes: Vec<Attribute>,
    /// Button label.
    pub children: Element,
}

/// The move control of a [`KanbanItem`] (`data-ui-kanban-handle`), styled like a Lumen button.
#[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());
    }
}