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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
//! `ReorderableList`: a vertical list reordered by keyboard, Move buttons, or dragging a handle.

// cspell:words onfocusout onmousedown onmousemove onmouseup

use std::collections::HashMap;
use std::rc::Rc;

use dioxus::prelude::*;

use super::stat::fill_template;
use crate::class::compose;
use crate::hooks::use_unique_id;
use crate::icons::{IconData, icon_svg, icon_svg_class, lucide};
use crate::overlay::focus_element;

/// Distance in CSS pixels a pointer must travel on a handle before a drag starts.
pub const REORDERABLE_LIST_DRAG_THRESHOLD: f64 = 4.0;

/// Catalog artwork for a grip or move button, with the same classes as lumen-react.
fn control_icon(icon: &'static IconData) -> Element {
    icon_svg(icon, &icon_svg_class(icon))
}

/// One item of a [`ReorderableList`].
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ReorderableListItem {
    /// Stable identity reported in `on_reorder`.
    pub id: String,
    /// Plain-text name used for the handle, buttons, and announcements.
    pub label: String,
    /// Secondary text shown under the label.
    pub description: Option<String>,
    /// Prevents grabbing and cancels a pending or active grab of this item. Other items can still
    /// move around it.
    pub disabled: bool,
}

impl ReorderableListItem {
    /// An item with an id and a label.
    pub fn new(id: impl Into<String>, label: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            ..Self::default()
        }
    }

    /// Sets the secondary text.
    #[must_use]
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Marks the item disabled.
    #[must_use]
    pub fn disabled(mut self) -> Self {
        self.disabled = true;
        self
    }
}

/// Copy for [`ReorderableList`] controls and announcements. `{item}` is the item label,
/// `{position}` its one-based position, and `{count}` the number of items.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ReorderableListLabels {
    /// Announced when a grab is canceled.
    pub canceled: String,
    /// Announced when an item is dropped.
    pub dropped: String,
    /// Announced when an item is grabbed.
    pub grabbed: String,
    /// Accessible name of a handle.
    pub handle: String,
    /// Keyboard instructions, referenced by every handle.
    pub instructions: String,
    /// Accessible name of a Move down button.
    pub move_down: String,
    /// Accessible name of a Move up button.
    pub move_up: String,
    /// Announced after each move.
    pub moved: String,
}

impl Default for ReorderableListLabels {
    fn default() -> Self {
        Self {
            canceled: "Reorder canceled. {item} returned to position {position} of {count}.".into(),
            dropped: "Dropped {item} at position {position} of {count}.".into(),
            grabbed: "Grabbed {item}. Position {position} of {count}.".into(),
            handle: "Reorder {item}".into(),
            instructions: "Press Space or Enter on a reorder handle to grab an item. Use the up and down arrow keys to move it, Space or Enter to drop it, and Escape to cancel.".into(),
            move_down: "Move {item} down".into(),
            move_up: "Move {item} up".into(),
            moved: "Moved {item} to position {position} of {count}.".into(),
        }
    }
}

/// Details of a committed move.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ReorderableListDetail {
    /// Id of the moved item.
    pub id: String,
    /// Zero-based index the item started from.
    pub from: usize,
    /// Zero-based index the item was dropped at.
    pub to: usize,
    /// Item ids in their new order.
    pub order: Vec<String>,
    /// The items in their new order.
    pub items: Vec<ReorderableListItem>,
}

/// Moves the entry at `from` to `to` and returns the new order. Out-of-range requests return the
/// original order.
pub fn move_reorderable_list_item<T: Clone>(items: &[T], from: usize, to: usize) -> Vec<T> {
    let mut next = items.to_vec();

    if from >= next.len() || to >= next.len() || from == to {
        return next;
    }

    let item = next.remove(from);
    next.insert(to, item);
    next
}

/// What a key does while an item is grabbed.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ReorderKey {
    Previous,
    Next,
    First,
    Last,
    Cancel,
}

pub(crate) fn reorder_key(key: &Key) -> Option<ReorderKey> {
    match key {
        Key::ArrowUp => Some(ReorderKey::Previous),
        Key::ArrowDown => Some(ReorderKey::Next),
        Key::Home => Some(ReorderKey::First),
        Key::End => Some(ReorderKey::Last),
        Key::Escape => Some(ReorderKey::Cancel),
        _ => None,
    }
}

/// Target index of a keyboard move, clamped to the list.
pub(crate) fn reorder_key_target(action: ReorderKey, index: usize, count: usize) -> usize {
    let last = count.saturating_sub(1);

    match action {
        ReorderKey::First => 0,
        ReorderKey::Last => last,
        ReorderKey::Previous => index.saturating_sub(1),
        ReorderKey::Next => (index + 1).min(last),
        ReorderKey::Cancel => index,
    }
}

/// Index a dragged item takes for a pointer at `position`, given the vertical midpoints of the
/// other items in display order. Non-finite positions keep the item where it is.
pub fn reorderable_list_pointer_index(midpoints: &[f64], position: f64, current: usize) -> usize {
    if !position.is_finite() {
        return current;
    }

    midpoints
        .iter()
        .filter(|midpoint| midpoint.is_finite() && position > **midpoint)
        .count()
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Input {
    Keyboard,
    Pointer,
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct Session {
    id: String,
    input: Input,
    initial_order: Vec<String>,
    order: Vec<String>,
    origin: usize,
}

#[derive(Clone, Debug, PartialEq)]
struct PointerState {
    active: bool,
    epoch: u64,
    id: String,
    initial_order: Vec<String>,
    start_y: f64,
}

fn matches_item_order(order: &[String], items: &[ReorderableListItem]) -> bool {
    order.len() == items.len() && order.iter().zip(items).all(|(id, item)| *id == item.id)
}

fn can_reorder(id: &str, order: &[String], items: &[ReorderableListItem]) -> bool {
    matches_item_order(order, items) && items.iter().any(|item| item.id == id && !item.disabled)
}

fn committed_ids(items: &[ReorderableListItem]) -> Vec<String> {
    items.iter().map(|item| item.id.clone()).collect()
}

fn reorder_detail(
    order: Vec<String>,
    id: &str,
    origin: usize,
    initial_order: &[String],
    committed: &[ReorderableListItem],
) -> Option<ReorderableListDetail> {
    if !can_reorder(id, initial_order, committed) {
        return None;
    }

    let to = order.iter().position(|entry| entry == id)?;

    if to == origin {
        return None;
    }

    let items: Option<Vec<ReorderableListItem>> = order
        .iter()
        .map(|entry| committed.iter().find(|item| item.id == *entry).cloned())
        .collect();

    Some(ReorderableListDetail {
        id: id.to_string(),
        from: origin,
        to,
        order,
        items: items?,
    })
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
enum Slot {
    Handle,
    MoveUp,
    MoveDown,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Message {
    Canceled,
    Dropped,
    Grabbed,
    Moved,
}

/// Commits `order` for the item `id`, given its origin index and the order it was grabbed from.
type CommitFn = dyn Fn(Vec<String>, &str, usize, &[String]);

/// Announces `message` for the item `id` at its position in `order`.
type AnnounceFn = dyn Fn(Message, &str, &[String]);

fn format_message(
    labels: &ReorderableListLabels,
    message: Message,
    item: &str,
    index: usize,
    count: usize,
) -> String {
    let template = match message {
        Message::Canceled => &labels.canceled,
        Message::Dropped => &labels.dropped,
        Message::Grabbed => &labels.grabbed,
        Message::Moved => &labels.moved,
    };

    fill_template(
        template,
        &[
            ("count", &count.to_string()),
            ("item", item),
            ("position", &(index + 1).to_string()),
        ],
    )
}

/// Props for [`ReorderableList`].
#[derive(Props, Clone, PartialEq)]
pub struct ReorderableListProps {
    /// Items in display order. Pass with `on_reorder` to control the order. Changing their ids or
    /// order, or disabling the grabbed item, cancels the grab. Updates to labels and descriptions
    /// preserve it, as does disabling another item.
    pub items: Option<Vec<ReorderableListItem>>,
    /// Initial items for an uncontrolled list.
    #[props(default)]
    pub default_items: Vec<ReorderableListItem>,
    /// Accessible name of the list.
    #[props(into)]
    pub label: Option<String>,
    /// Localized copy.
    #[props(default)]
    pub labels: ReorderableListLabels,
    /// Shows Move up and Move down buttons beside each item.
    #[props(default)]
    pub move_buttons: bool,
    /// Called after an item is dropped at a new position.
    pub on_reorder: Option<EventHandler<ReorderableListDetail>>,
    /// Renders an item's content. Defaults to its label and description.
    pub render_item: Option<Callback<ReorderableListItem, Element>>,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
}

/// A vertical list whose items reorder by keyboard (Space or Enter on a handle to grab, arrow
/// keys, Home, and End to move, Space or Enter to drop, Escape to cancel), with optional Move up
/// and Move down buttons, or by dragging a handle where the renderer reports pointer events.
///
/// Like lumen-react, the first render is the no-script state (hidden controls); the controls
/// appear once the component is mounted.
#[component]
#[allow(clippy::too_many_lines)]
pub fn ReorderableList(props: ReorderableListProps) -> Element {
    let unique = use_unique_id();
    let instructions_id = format!("ui-reorderable-list-{unique}-instructions");
    let uncontrolled = use_signal(|| props.default_items.clone());
    let mut session = use_signal(|| None::<Session>);
    let announcement = use_signal(String::new);
    let mut enhanced = use_signal(|| false);
    let mut pointer = use_signal(|| None::<PointerState>);
    let mut pointer_epoch = use_signal(|| 0_u64);
    let mut slots = use_signal(Vec::<f64>::new);
    let mut suppress_click = use_signal(|| false);
    let mut moving = use_signal(|| false);
    let mut focus_request = use_signal(|| None::<(String, Slot)>);
    let mut controls = use_signal(HashMap::<(String, Slot), Rc<MountedData>>::new);
    let mut rows = use_signal(HashMap::<String, Rc<MountedData>>::new);

    use_effect(move || enhanced.set(true));

    use_effect(move || {
        let Some((id, slot)) = focus_request() else {
            return;
        };

        focus_element(controls.peek().get(&(id, slot)).cloned());
        focus_request.set(None);
        moving.set(false);
    });

    let controlled = props.items.is_some();
    let committed: Rc<[ReorderableListItem]> = Rc::from(
        props
            .items
            .clone()
            .unwrap_or_else(|| uncontrolled.read().clone()),
    );
    let labels = Rc::new(props.labels.clone());
    let on_reorder = props.on_reorder;
    let stale_session = session
        .peek()
        .as_ref()
        .is_some_and(|active| !can_reorder(&active.id, &active.initial_order, &committed));

    // A refresh owns the current membership and order. Clear the old grab before rendering it,
    // while leaving content-only updates available to the eventual reorder callback.
    if stale_session {
        session.set(None);
        focus_request.set(None);
        moving.set(false);
    }

    let stale_pointer = pointer
        .peek()
        .as_ref()
        .filter(|state| !can_reorder(&state.id, &state.initial_order, &committed))
        .map(|state| {
            state.active
                && committed
                    .iter()
                    .any(|item| item.id == state.id && !item.disabled)
        });

    if let Some(active) = stale_pointer {
        suppress_click.set(active);
        pointer.set(None);
        slots.set(Vec::new());
    }

    let active = session();
    let by_id: HashMap<&str, &ReorderableListItem> = committed
        .iter()
        .map(|item| (item.id.as_str(), item))
        .collect();
    let displayed: Vec<ReorderableListItem> = match &active {
        Some(active)
            if active.order.len() == committed.len()
                && active
                    .order
                    .iter()
                    .all(|id| by_id.contains_key(id.as_str())) =>
        {
            active
                .order
                .iter()
                .filter_map(|id| by_id.get(id.as_str()).map(|item| (*item).clone()))
                .collect()
        }
        _ => committed.to_vec(),
    };

    let announce = {
        let committed = committed.clone();
        let labels = labels.clone();

        move |message: Message, id: &str, order: &[String]| {
            let mut announcement = announcement;

            if let Some(item) = committed.iter().find(|item| item.id == id) {
                let index = order.iter().position(|entry| entry == id).unwrap_or(0);
                announcement.set(format_message(
                    &labels,
                    message,
                    &item.label,
                    index,
                    order.len(),
                ));
            }
        }
    };

    let commit = {
        let committed = committed.clone();

        move |order: Vec<String>, id: &str, origin: usize, initial_order: &[String]| {
            let mut uncontrolled = uncontrolled;
            let Some(detail) = reorder_detail(order, id, origin, initial_order, &committed) else {
                return;
            };

            if !controlled {
                uncontrolled.set(detail.items.clone());
            }

            if let Some(handler) = on_reorder {
                handler.call(detail);
            }
        }
    };

    let drop_active = {
        let commit = commit.clone();
        let announce = announce.clone();
        let committed = committed.clone();

        move || {
            let mut session = session;
            let Some(active) = session.peek().clone() else {
                return;
            };

            session.set(None);

            if !can_reorder(&active.id, &active.initial_order, &committed) {
                return;
            }

            commit(
                active.order.clone(),
                &active.id,
                active.origin,
                &active.initial_order,
            );
            announce(Message::Dropped, &active.id, &active.order);
        }
    };

    let cancel = {
        let announce = announce.clone();
        let committed = committed.clone();

        move || {
            let (mut pointer, mut session, mut slots) = (pointer, session, slots);
            pointer.set(None);
            slots.set(Vec::new());

            let Some(active) = session.peek().clone() else {
                return;
            };

            session.set(None);
            announce(Message::Canceled, &active.id, &committed_ids(&committed));
        }
    };

    let move_to = {
        let announce = announce.clone();

        move |active: Session, target: usize| {
            let (mut moving, mut focus_request, mut session) = (moving, focus_request, session);
            let Some(current) = active.order.iter().position(|id| *id == active.id) else {
                return;
            };

            if target == current {
                return;
            }

            let order = move_reorderable_list_item(&active.order, current, target);

            if active.input == Input::Keyboard {
                moving.set(true);
                focus_request.set(Some((active.id.clone(), Slot::Handle)));
                announce(Message::Moved, &active.id, &order);
            }

            session.set(Some(Session { order, ..active }));
        }
    };

    let onkeydown = {
        let cancel = cancel.clone();
        let move_to = move_to.clone();

        move |event: KeyboardEvent| {
            let Some(active) = session.peek().clone() else {
                return;
            };
            let Some(action) = reorder_key(&event.key()) else {
                return;
            };

            if event.is_composing() {
                return;
            }

            event.prevent_default();

            if action == ReorderKey::Cancel {
                cancel();
                return;
            }

            if active.input == Input::Keyboard {
                let index = active
                    .order
                    .iter()
                    .position(|id| *id == active.id)
                    .unwrap_or(0);
                let target = reorder_key_target(action, index, active.order.len());
                move_to(active, target);
            }
        }
    };

    let onmousemove = {
        let cancel = cancel.clone();
        let move_to = move_to.clone();
        let committed = committed.clone();

        move |event: MouseEvent| {
            let (mut pointer, mut session, mut slots) = (pointer, session, slots);
            let Some(mut state) = pointer.peek().clone() else {
                return;
            };

            if !can_reorder(&state.id, &state.initial_order, &committed) {
                cancel();
                return;
            }

            let y = event.client_coordinates().y;

            if !state.active {
                if (y - state.start_y).abs() < REORDERABLE_LIST_DRAG_THRESHOLD {
                    return;
                }

                state.active = true;

                if session.peek().is_some() {
                    cancel();
                }

                let order = committed_ids(&committed);
                let origin = order.iter().position(|id| *id == state.id).unwrap_or(0);

                pointer.set(Some(state.clone()));
                slots.set(Vec::new());
                session.set(Some(Session {
                    id: state.id.clone(),
                    input: Input::Pointer,
                    initial_order: order.clone(),
                    order: order.clone(),
                    origin,
                }));

                // Slot midpoints are read once per drag; rows keep their slots while items move.
                let mounted: Vec<Option<Rc<MountedData>>> = order
                    .iter()
                    .map(|id| rows.peek().get(id).cloned())
                    .collect();

                spawn(async move {
                    let mut midpoints = Vec::with_capacity(mounted.len());

                    for row in mounted {
                        let midpoint = match row {
                            Some(row) => row
                                .get_client_rect()
                                .await
                                .map_or(f64::NAN, |rect| rect.min_y() + rect.height() / 2.0),
                            None => f64::NAN,
                        };
                        midpoints.push(midpoint);
                    }

                    // The renderer may finish an old measurement after a cancel and a new grab
                    // of the same item. Only this pointer interaction may publish its geometry.
                    let current_pointer = pointer
                        .peek()
                        .as_ref()
                        .is_some_and(|current| current.active && current.epoch == state.epoch);
                    let current_session = session.peek().as_ref().is_some_and(|current| {
                        current.input == Input::Pointer
                            && current.id == state.id
                            && current.initial_order == state.initial_order
                    });

                    if current_pointer && current_session {
                        slots.set(midpoints);
                    }
                });

                return;
            }

            event.prevent_default();

            let Some(active) = session.peek().clone() else {
                return;
            };
            let current = active
                .order
                .iter()
                .position(|id| *id == active.id)
                .unwrap_or(0);
            let slot_midpoints = slots.peek();

            if slot_midpoints.len() != active.order.len() {
                return;
            }

            // Midpoints of the other items where they sit now: every slot except the dragged one.
            let others: Vec<f64> = (0..active.order.len())
                .filter(|slot| *slot != current)
                .map(|slot| slot_midpoints[slot])
                .collect();
            drop(slot_midpoints);

            move_to(active, reorderable_list_pointer_index(&others, y, current));
        }
    };

    let finish_pointer = {
        let drop_active = drop_active.clone();
        let cancel = cancel.clone();

        move |commit_move: bool| {
            let (mut pointer, mut slots, mut suppress_click) = (pointer, slots, suppress_click);
            let Some(state) = pointer.peek().clone() else {
                return;
            };

            pointer.set(None);
            slots.set(Vec::new());

            if !state.active {
                return;
            }

            suppress_click.set(commit_move);

            if commit_move {
                drop_active();
            } else {
                cancel();
            }
        }
    };
    let finish_leave = finish_pointer.clone();

    let root_state = active.as_ref().map(|active| match active.input {
        Input::Pointer => "dragging",
        Input::Keyboard => "grabbed",
    });
    let class = compose([Some("ui-reorderable-list"), props.class.as_deref()]);
    let show = enhanced();
    let count = displayed.len();
    let move_buttons = props.move_buttons;

    rsx! {
        div {
            class,
            "data-enhanced": show.then_some("true"),
            "data-move-buttons": move_buttons.then_some(""),
            "data-slot": "reorderable-list",
            "data-state": root_state,
            "data-ui-owner": "dioxus",
            "data-ui-reorderable-list": "",
            onkeydown,
            onmousemove,
            onmouseup: move |_| finish_pointer(true),
            // Mouse events stop at the list edge, so leaving it drops the item where it is.
            onmouseleave: move |_| finish_leave(true),
            ..props.attributes,
            ol {
                aria_label: props.label.clone(),
                class: "ui-reorderable-list__items",
                "data-slot": "reorderable-list-items",
                // Map to the keyed rows themselves. A `for` body that is a block wraps each row in
                // a node without a key, so a reorder would replace rows (and their focused handle)
                // instead of moving them.
                {displayed.into_iter().enumerate().map(|(index, item)| {
                        let grabbed = active.as_ref().is_some_and(|active| active.id == item.id);
                        let disabled = item.disabled;
                        let handle_label = fill_template(&labels.handle, &[("item", &item.label)]);
                        let up_label = fill_template(&labels.move_up, &[("item", &item.label)]);
                        let down_label = fill_template(&labels.move_down, &[("item", &item.label)]);
                        let (row_id, handle_id, up_id, down_id) = (item.id.clone(), item.id.clone(), item.id.clone(), item.id.clone());
                        let click_item = item.clone();
                        let (click_drop, click_cancel, click_announce) = (drop_active.clone(), cancel.clone(), announce.clone());
                        let click_committed = committed.clone();
                        let pointer_committed = committed.clone();
                        let pointer_id = item.id.clone();
                        let (up_item, down_item) = (item.id.clone(), item.id.clone());
                        let (up_commit, down_commit) = (commit.clone(), commit.clone());
                        let (up_announce, down_announce) = (announce.clone(), announce.clone());
                        let (up_committed, down_committed) = (committed.clone(), committed.clone());
                        let blur_cancel = cancel.clone();
                        let blur_id = item.id.clone();
                        let content = match props.render_item {
                            Some(render) => render.call(item.clone()),
                            None => rsx! {
                                "{item.label}"
                                if let Some(description) = item.description.clone() {
                                    span {
                                        class: "ui-reorderable-list__description",
                                        "data-slot": "reorderable-list-description",
                                        "{description}"
                                    }
                                }
                            },
                        };
                        let move_by = move |id: &str, direction: isize, committed: &[ReorderableListItem], commit: &CommitFn, announce: &AnnounceFn| {
                            let mut focus_request = focus_request;

                            if session.peek().is_some() {
                                return;
                            }

                            let order = committed_ids(committed);
                            let Some(from) = order.iter().position(|entry| entry == id) else {
                                return;
                            };
                            let Some(to) = from.checked_add_signed(direction).filter(|to| *to < order.len()) else {
                                return;
                            };

                            if committed.get(from).is_some_and(|item| item.disabled) {
                                return;
                            }

                            let next = move_reorderable_list_item(&order, from, to);
                            let slot = if direction < 0 { Slot::MoveUp } else { Slot::MoveDown };

                            focus_request.set(Some((id.to_string(), slot)));
                            commit(next.clone(), id, from, &order);
                            announce(Message::Moved, id, &next);
                        };

                        rsx! {
                            li {
                                key: "{item.id}",
                                class: "ui-reorderable-list__item",
                                "data-disabled": disabled.then_some(""),
                                "data-label": "{item.label}",
                                "data-slot": "reorderable-list-item",
                                "data-state": if grabbed { root_state } else { None },
                                "data-value": "{item.id}",
                                onmounted: move |event| {
                                    rows.write().insert(row_id.clone(), event.data());
                                },
                                button {
                                    aria_describedby: "{instructions_id}",
                                    aria_label: "{handle_label}",
                                    aria_pressed: if grabbed { "true" } else { "false" },
                                    class: "ui-reorderable-list__handle",
                                    "data-slot": "reorderable-list-handle",
                                    disabled,
                                    hidden: !show,
                                    r#type: "button",
                                    onmounted: move |event| {
                                        controls.write().insert((handle_id.clone(), Slot::Handle), event.data());
                                    },
                                    onclick: move |_| {
                                        if suppress_click() {
                                            suppress_click.set(false);
                                            return;
                                        }

                                        if click_item.disabled {
                                            return;
                                        }

                                        let current = session.peek().clone();

                                        if current.as_ref().is_some_and(|active| active.id == click_item.id) {
                                            click_drop();
                                            return;
                                        }

                                        if current.is_some() {
                                            click_cancel();
                                        }

                                        let order = committed_ids(&click_committed);
                                        let origin = order.iter().position(|id| *id == click_item.id).unwrap_or(0);

                                        session.set(Some(Session { id: click_item.id.clone(), input: Input::Keyboard, initial_order: order.clone(), order: order.clone(), origin }));
                                        click_announce(Message::Grabbed, &click_item.id, &order);
                                    },
                                    onfocusout: move |_| {
                                        let keyboard = session.peek().as_ref().is_some_and(|active| active.input == Input::Keyboard && active.id == blur_id);

                                        if keyboard && !*moving.peek() {
                                            blur_cancel();
                                        }
                                    },
                                    onmousedown: move |event| {
                                        let primary = event.trigger_button().is_none_or(|button| button == dioxus::html::input_data::MouseButton::Primary);

                                        if disabled || !primary {
                                            return;
                                        }

                                        suppress_click.set(false);
                                        let epoch = pointer_epoch.peek().wrapping_add(1);
                                        pointer_epoch.set(epoch);
                                        pointer.set(Some(PointerState {
                                            active: false,
                                            epoch,
                                            id: pointer_id.clone(),
                                            initial_order: committed_ids(&pointer_committed),
                                            start_y: event.client_coordinates().y,
                                        }));
                                    },
                                    {control_icon(&lucide::GRIP_VERTICAL)}
                                }
                                div { class: "ui-reorderable-list__content", "data-slot": "reorderable-list-content", {content} }
                                div {
                                    class: "ui-reorderable-list__moves",
                                    "data-slot": "reorderable-list-moves",
                                    hidden: !show || !move_buttons,
                                    button {
                                        aria_disabled: if disabled || index == 0 { "true" } else { "false" },
                                        aria_label: "{up_label}",
                                        class: "ui-reorderable-list__move",
                                        "data-slot": "reorderable-list-move-up",
                                        r#type: "button",
                                        onmounted: move |event| {
                                            controls.write().insert((up_id.clone(), Slot::MoveUp), event.data());
                                        },
                                        onclick: move |_| move_by(&up_item, -1, &up_committed, &up_commit, &up_announce),
                                        {control_icon(&lucide::CHEVRON_UP)}
                                    }
                                    button {
                                        aria_disabled: if disabled || index + 1 == count { "true" } else { "false" },
                                        aria_label: "{down_label}",
                                        class: "ui-reorderable-list__move",
                                        "data-slot": "reorderable-list-move-down",
                                        r#type: "button",
                                        onmounted: move |event| {
                                            controls.write().insert((down_id.clone(), Slot::MoveDown), event.data());
                                        },
                                        onclick: move |_| move_by(&down_item, 1, &down_committed, &down_commit, &down_announce),
                                        {control_icon(&lucide::CHEVRON_DOWN)}
                                    }
                                }
                            }
                        }
                })}
            }
            p {
                class: "ui-reorderable-list__instructions",
                "data-slot": "reorderable-list-instructions",
                id: "{instructions_id}",
                "{labels.instructions}"
            }
            span {
                aria_atomic: "true",
                aria_live: "polite",
                class: "ui-reorderable-list__status",
                "data-slot": "reorderable-list-status",
                role: "status",
                "{announcement}"
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{
        Key, ReorderKey, ReorderableListItem, committed_ids, move_reorderable_list_item,
        reorder_detail, reorder_key, reorder_key_target, reorderable_list_pointer_index,
    };

    #[test]
    fn moves_keep_out_of_range_requests_unchanged() {
        assert_eq!(
            move_reorderable_list_item(&["a", "b", "c"], 0, 2),
            ["b", "c", "a"]
        );
        assert_eq!(
            move_reorderable_list_item(&["a", "b", "c"], 2, 0),
            ["c", "a", "b"]
        );
        assert_eq!(move_reorderable_list_item(&["a", "b"], 5, 0), ["a", "b"]);
    }

    #[test]
    fn keyboard_targets_clamp_to_the_list() {
        assert_eq!(reorder_key(&Key::ArrowUp), Some(ReorderKey::Previous));
        assert_eq!(reorder_key(&Key::Enter), None);
        assert_eq!(reorder_key_target(ReorderKey::Previous, 0, 3), 0);
        assert_eq!(reorder_key_target(ReorderKey::Next, 2, 3), 2);
        assert_eq!(reorder_key_target(ReorderKey::Last, 0, 3), 2);
        assert_eq!(reorder_key_target(ReorderKey::First, 2, 3), 0);
    }

    #[test]
    fn pointer_index_counts_midpoints_above_the_pointer() {
        assert_eq!(reorderable_list_pointer_index(&[10.0, 30.0], 5.0, 1), 0);
        assert_eq!(reorderable_list_pointer_index(&[10.0, 30.0], 20.0, 0), 1);
        assert_eq!(
            reorderable_list_pointer_index(&[10.0, f64::NAN, 30.0], 40.0, 0),
            2
        );
        assert_eq!(reorderable_list_pointer_index(&[10.0], f64::NAN, 1), 1);
    }

    #[test]
    fn commit_rejects_orders_captured_before_membership_or_order_changes() {
        let initial = vec![
            ReorderableListItem::new("a", "Alpha"),
            ReorderableListItem::new("b", "Beta"),
            ReorderableListItem::new("c", "Gamma"),
        ];
        let initial_order = committed_ids(&initial);
        let moved = move_reorderable_list_item(&initial_order, 0, 2);
        let mut appended = initial.clone();
        appended.push(ReorderableListItem::new("d", "Delta"));
        let mut replaced = initial.clone();
        replaced[2] = ReorderableListItem::new("d", "Delta");

        for current in [
            appended,
            initial[..2].to_vec(),
            initial[1..].to_vec(),
            replaced,
            move_reorderable_list_item(&initial, 1, 2),
        ] {
            assert!(reorder_detail(moved.clone(), "a", 0, &initial_order, &current).is_none());
        }
    }

    #[test]
    fn commit_uses_current_content_when_item_identities_are_unchanged() {
        let initial = vec![
            ReorderableListItem::new("a", "Alpha"),
            ReorderableListItem::new("b", "Beta"),
        ];
        let initial_order = committed_ids(&initial);
        let mut updated = initial;
        updated[0].label = "Updated alpha".into();
        let detail = reorder_detail(
            vec!["b".into(), "a".into()],
            "a",
            0,
            &initial_order,
            &updated,
        )
        .expect("content updates preserve a valid reorder");

        assert_eq!(detail.items, vec![updated[1].clone(), updated[0].clone()]);
    }

    #[test]
    fn commit_rejects_a_disabled_grab_but_allows_other_disabled_items() {
        let mut items = vec![
            ReorderableListItem::new("a", "Alpha"),
            ReorderableListItem::new("b", "Beta"),
        ];
        let initial_order = committed_ids(&items);
        let moved = vec!["b".into(), "a".into()];
        items[0].disabled = true;

        assert!(reorder_detail(moved.clone(), "a", 0, &initial_order, &items).is_none());

        items[0].disabled = false;
        items[1].disabled = true;
        let detail = reorder_detail(moved, "a", 0, &initial_order, &items)
            .expect("another disabled item does not prevent this reorder");

        assert_eq!(detail.items, vec![items[1].clone(), items[0].clone()]);
    }
}