Skip to main content

sui_widgets/
reorderable.rs

1use std::sync::atomic::{AtomicU64, Ordering};
2
3use sui_core::{
4    DragDropScope, DragEventKind, DragOutcome, DragPayload, DragSessionId, DropEffect, Event,
5    KeyState, KeyboardEvent, Path, Point, PointerButton, PointerEventKind, Rect, SemanticsAction,
6    SemanticsLiveRegion, SemanticsNode, SemanticsRole, SemanticsValue, Size, Transform, Vector,
7    WidgetId,
8};
9use sui_layout::Constraints;
10use sui_runtime::{
11    ArrangeCtx, EventCtx, EventPhase, FrameClock, MeasureCtx, Motion, PaintCtx, SemanticsCtx,
12    Widget, WidgetChildren, WidgetPod, WidgetPodMutVisitor, WidgetPodVisitor,
13};
14
15use crate::frame::stroke_border;
16use crate::{AnimationSpec, DefaultTheme, Easing};
17
18const DEFAULT_DRAG_THRESHOLD: f32 = 4.0;
19const REORDERABLE_LIST_PAYLOAD_KIND: &str = "sui-widgets.reorderable-list";
20/// Tags the ids of the status nodes that announce keyboard moves.
21const SYNTHETIC_REORDER_STATUS_TAG: u64 = 7_u64 << 60;
22
23static NEXT_REORDER_STATUS_ID: AtomicU64 = AtomicU64::new(1);
24
25type ReorderCallback = Box<dyn FnMut(&mut EventCtx, ReorderableListChange)>;
26type ItemName = Box<dyn Fn(usize) -> String>;
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub struct ReorderableListChange {
30    pub item: usize,
31    pub from: usize,
32    pub to: usize,
33}
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36struct ReorderPayload {
37    list: u64,
38    item: usize,
39}
40
41#[derive(Debug, Clone, Copy)]
42struct ReorderPress {
43    pointer_id: u64,
44    start_position: Point,
45    item: usize,
46    from: usize,
47    drag_offset_y: f32,
48}
49
50#[derive(Debug, Clone, Copy)]
51struct ActiveReorderDrag {
52    pointer_id: u64,
53    session_id: DragSessionId,
54    item: usize,
55    from: usize,
56    target: usize,
57    drag_offset_y: f32,
58    position: Point,
59}
60
61/// Where a row is presented while rows slide into a new order. The runtime
62/// animates it; rows sliding into place are movement, which reduced motion
63/// skips.
64#[derive(Debug, Clone, Copy)]
65struct RowMotion {
66    y: Motion<f32>,
67}
68
69impl RowMotion {
70    fn new(y: f32) -> Self {
71        Self {
72            y: Motion::new(y).movement(),
73        }
74    }
75
76    fn at(&self, clock: &impl FrameClock) -> f32 {
77        self.y.get(clock)
78    }
79
80    fn jump_to(&mut self, y: f32) {
81        self.y.jump_to(y);
82    }
83
84    fn set_target(&mut self, target_y: f32, duration: f64, easing: Easing, ctx: &mut EventCtx) {
85        if (self.y.get(ctx) - target_y).abs() <= 0.5 && !self.y.is_animating(ctx) {
86            self.jump_to(target_y);
87            return;
88        }
89        ctx.animate(
90            &mut self.y,
91            target_y,
92            AnimationSpec::tween(duration, easing),
93        );
94    }
95
96    fn is_animating(&self, clock: &impl FrameClock) -> bool {
97        self.y.is_animating(clock)
98    }
99}
100
101pub struct ReorderableList {
102    theme: Box<DefaultTheme>,
103    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
104    scope: DragDropScope,
105    name: String,
106    children: WidgetChildren,
107    order: Vec<usize>,
108    spacing: f32,
109    drag_threshold: f32,
110    animation_duration: Option<f64>,
111    animation_easing: Option<Easing>,
112    preview_label: Option<String>,
113    press: Option<ReorderPress>,
114    active_drag: Option<ActiveReorderDrag>,
115    row_sizes: Vec<Size>,
116    row_offsets: Vec<f32>,
117    row_bounds: Vec<Rect>,
118    row_motions: Vec<RowMotion>,
119    content_y: f32,
120    content_height: f32,
121    on_reorder: Option<ReorderCallback>,
122    item_name: Option<ItemName>,
123    /// The row, by position, that the keyboard acts on while the list has
124    /// focus.
125    current: usize,
126    /// What the last keyboard move did, for assistive technology.
127    announcement: Option<String>,
128    status_id: WidgetId,
129}
130
131impl ReorderableList {
132    pub fn new(name: impl Into<String>) -> Self {
133        Self {
134            theme: Box::new(DefaultTheme::default()),
135            theme_reader: None,
136            scope: DragDropScope::new(),
137            name: name.into(),
138            children: WidgetChildren::new(),
139            order: Vec::new(),
140            spacing: 8.0,
141            drag_threshold: DEFAULT_DRAG_THRESHOLD,
142            animation_duration: None,
143            animation_easing: None,
144            preview_label: None,
145            press: None,
146            active_drag: None,
147            row_sizes: Vec::new(),
148            row_offsets: Vec::new(),
149            row_bounds: Vec::new(),
150            row_motions: Vec::new(),
151            content_y: 0.0,
152            content_height: 0.0,
153            on_reorder: None,
154            item_name: None,
155            current: 0,
156            announcement: None,
157            status_id: WidgetId::new(
158                SYNTHETIC_REORDER_STATUS_TAG
159                    | NEXT_REORDER_STATUS_ID.fetch_add(1, Ordering::Relaxed),
160            ),
161        }
162    }
163
164    pub fn theme(mut self, theme: DefaultTheme) -> Self {
165        self.theme = Box::new(theme);
166        self.theme_reader = None;
167        self
168    }
169
170    pub fn theme_when<F>(mut self, theme: F) -> Self
171    where
172        F: Fn() -> DefaultTheme + 'static,
173    {
174        self.theme_reader = Some(Box::new(theme));
175        self
176    }
177
178    pub fn scope(mut self, scope: DragDropScope) -> Self {
179        self.scope = scope;
180        self
181    }
182
183    pub fn gap(mut self, gap: f32) -> Self {
184        self.spacing = gap.max(0.0);
185        self
186    }
187
188    pub fn drag_threshold(mut self, threshold: f32) -> Self {
189        self.drag_threshold = threshold.max(0.0);
190        self
191    }
192
193    pub fn animation_duration(mut self, duration: f64) -> Self {
194        self.animation_duration = Some(duration.max(0.0));
195        self
196    }
197
198    pub fn animation_easing(mut self, easing: Easing) -> Self {
199        self.animation_easing = Some(easing);
200        self
201    }
202
203    pub fn preview_label(mut self, label: impl Into<String>) -> Self {
204        self.preview_label = Some(label.into());
205        self
206    }
207
208    pub fn item<W>(mut self, child: W) -> Self
209    where
210        W: Widget + 'static,
211    {
212        self.children.push(child);
213        self
214    }
215
216    pub fn on_reorder<F>(mut self, callback: F) -> Self
217    where
218        F: FnMut(ReorderableListChange) + 'static,
219    {
220        let mut callback = callback;
221        self.on_reorder = Some(Box::new(move |_, change| callback(change)));
222        self
223    }
224
225    pub fn on_reorder_with_ctx<F>(mut self, callback: F) -> Self
226    where
227        F: FnMut(&mut EventCtx, ReorderableListChange) + 'static,
228    {
229        self.on_reorder = Some(Box::new(callback));
230        self
231    }
232
233    /// Names item `index` (in the order items were added) when announcing a
234    /// keyboard move, such as "Moved Draft to position 2 of 4". Items are
235    /// "Item 1", "Item 2"… otherwise.
236    pub fn item_name<F>(mut self, name: F) -> Self
237    where
238        F: Fn(usize) -> String + 'static,
239    {
240        self.item_name = Some(Box::new(name));
241        self
242    }
243
244    pub fn order(&self) -> &[usize] {
245        &self.order
246    }
247
248    fn name_of(&self, item: usize) -> String {
249        self.item_name
250            .as_ref()
251            .map_or_else(|| format!("Item {}", item + 1), |name| name(item))
252    }
253
254    /// The row, by position, whose widget holds `focused`.
255    fn row_holding(&self, focused: WidgetId) -> Option<usize> {
256        let item = self
257            .children
258            .as_slice()
259            .iter()
260            .position(|row| pod_contains(row, focused))?;
261        self.visual_index_of(item)
262    }
263
264    /// Keys that move rows: Alt+Up and Alt+Down move the row with focus one
265    /// place, Alt+Home and Alt+End to either end. While the list itself has
266    /// focus, Up, Down, Home and End choose the row the keys act on.
267    fn handle_key(&mut self, ctx: &mut EventCtx, key: &KeyboardEvent) {
268        if key.state != KeyState::Pressed
269            || key.is_composing
270            || ctx.phase() == EventPhase::Capture
271            || self.order.is_empty()
272            || self.active_drag.is_some()
273        {
274            return;
275        }
276        let list_focused = ctx.is_focused();
277        let row = if list_focused {
278            self.current.min(self.order.len() - 1)
279        } else if let Some(row) = ctx
280            .focused_widget_id()
281            .and_then(|focused| self.row_holding(focused))
282        {
283            row
284        } else {
285            return;
286        };
287        let last = self.order.len() - 1;
288        let modifiers = key.modifiers;
289        let plain = !modifiers.any();
290        let only_alt = modifiers.alt && !modifiers.control && !modifiers.shift && !modifiers.meta;
291        let destination = |key: &str| match key {
292            "ArrowUp" => Some(row.saturating_sub(1)),
293            "ArrowDown" => Some((row + 1).min(last)),
294            "Home" => Some(0),
295            "End" => Some(last),
296            _ => None,
297        };
298        let Some(to) = destination(key.key.as_str()) else {
299            return;
300        };
301        if only_alt {
302            self.move_row(ctx, row, to);
303            ctx.set_handled();
304        } else if plain && list_focused {
305            if to != self.current {
306                self.current = to;
307                ctx.request_paint();
308                ctx.request_semantics();
309            }
310            ctx.set_handled();
311        }
312    }
313
314    /// Move the row at position `from` to position `to`, as a keyboard move.
315    fn move_row(&mut self, ctx: &mut EventCtx, from: usize, to: usize) {
316        self.current = to;
317        let item = self.order[from];
318        let count = self.order.len();
319        self.announcement = Some(if from == to {
320            format!(
321                "{} is already at position {} of {count}",
322                self.name_of(item),
323                to + 1
324            )
325        } else {
326            format!(
327                "Moved {} to position {} of {count}",
328                self.name_of(item),
329                to + 1
330            )
331        });
332        ctx.request_semantics();
333        ctx.request_paint();
334        if from == to {
335            return;
336        }
337        self.order.remove(from);
338        self.order.insert(to, item);
339        // Rows slide from where they were drawn to their new places.
340        self.retarget_row_motions(ctx, true);
341        ctx.request_arrange();
342        if let Some(callback) = &mut self.on_reorder {
343            callback(ctx, ReorderableListChange { item, from, to });
344        }
345    }
346
347    pub fn scope_ref(&self) -> &DragDropScope {
348        &self.scope
349    }
350
351    fn resolved_theme(&self) -> DefaultTheme {
352        self.theme_reader
353            .as_ref()
354            .map(|reader| reader())
355            .unwrap_or_else(|| *self.theme)
356    }
357
358    fn sync_storage(&mut self) {
359        let len = self.children.len();
360        if self.order.len() != len {
361            self.order = (0..len).collect();
362        }
363        self.row_sizes.resize(len, Size::ZERO);
364        self.row_offsets.resize(len, 0.0);
365        self.row_bounds.resize(len, Rect::ZERO);
366        if self.row_motions.len() != len {
367            self.row_motions = (0..len).map(|_| RowMotion::new(0.0)).collect();
368        }
369        if self
370            .active_drag
371            .is_some_and(|drag| drag.item >= len || drag.from >= len || drag.target >= len)
372        {
373            self.active_drag = None;
374            self.press = None;
375        }
376    }
377
378    fn compute_offsets_for_order(&self, order: &[usize]) -> (Vec<f32>, f32) {
379        let mut offsets = vec![0.0; self.children.len()];
380        let mut y: f32 = 0.0;
381        for (visual, item) in order.iter().copied().enumerate() {
382            if visual > 0 {
383                y += self.spacing;
384            }
385            offsets[item] = y;
386            y += self
387                .row_sizes
388                .get(item)
389                .copied()
390                .unwrap_or(Size::ZERO)
391                .height;
392        }
393        (offsets, y)
394    }
395
396    fn desired_order(&self) -> Vec<usize> {
397        let Some(drag) = self.active_drag else {
398            return self.order.clone();
399        };
400
401        let mut order = self.order.clone();
402        let Some(from) = order.iter().position(|item| *item == drag.item) else {
403            return order;
404        };
405        let item = order.remove(from);
406        let target = drag.target.min(order.len());
407        order.insert(target, item);
408        order
409    }
410
411    fn visual_index_of(&self, item: usize) -> Option<usize> {
412        self.order.iter().position(|candidate| *candidate == item)
413    }
414
415    fn insertion_index_at(&self, position: Point) -> usize {
416        let local_y = position.y - self.content_y;
417        let mut y = 0.0;
418        for visual in 0..self.order.len() {
419            if visual > 0 {
420                y += self.spacing;
421            }
422            let item = self.order[visual];
423            let height = self
424                .row_sizes
425                .get(item)
426                .copied()
427                .unwrap_or(Size::ZERO)
428                .height;
429            if local_y < y + (height * 0.5) {
430                return visual;
431            }
432            y += height;
433        }
434        self.order.len()
435    }
436
437    fn target_index_at(&self, item: usize, position: Point) -> usize {
438        if self.order.is_empty() {
439            return 0;
440        }
441
442        let insertion = self.insertion_index_at(position);
443        let from = self.visual_index_of(item).unwrap_or(0);
444        let target = if insertion > from {
445            insertion.saturating_sub(1)
446        } else {
447            insertion
448        };
449        target.min(self.order.len().saturating_sub(1))
450    }
451
452    fn press_at(&self, pointer_id: u64, position: Point) -> Option<ReorderPress> {
453        for (visual, item) in self.order.iter().copied().enumerate() {
454            let rect = self.row_bounds.get(item).copied().unwrap_or(Rect::ZERO);
455            if rect.contains(position) {
456                return Some(ReorderPress {
457                    pointer_id,
458                    start_position: position,
459                    item,
460                    from: visual,
461                    drag_offset_y: position.y - rect.y(),
462                });
463            }
464        }
465        None
466    }
467
468    fn start_drag(&mut self, ctx: &mut EventCtx, press: ReorderPress, position: Point) {
469        let session_id = ctx.begin_drag(
470            self.scope.id(),
471            press.pointer_id,
472            press.start_position,
473            DragPayload::custom(
474                REORDERABLE_LIST_PAYLOAD_KIND,
475                ReorderPayload {
476                    list: ctx.widget_id().get(),
477                    item: press.item,
478                },
479            ),
480            DropEffect::Move,
481            self.preview_label.clone(),
482        );
483        let target = self.target_index_at(press.item, position);
484        self.active_drag = Some(ActiveReorderDrag {
485            pointer_id: press.pointer_id,
486            session_id,
487            item: press.item,
488            from: press.from,
489            target,
490            drag_offset_y: press.drag_offset_y,
491            position,
492        });
493        if let Some(motion) = self.row_motions.get_mut(press.item) {
494            motion.jump_to(position.y - press.drag_offset_y);
495        }
496        self.retarget_row_motions(ctx, true);
497    }
498
499    fn set_drag_target(&mut self, ctx: &mut EventCtx, target: usize, position: Point) {
500        let Some(drag) = &mut self.active_drag else {
501            return;
502        };
503        drag.position = position;
504        if drag.target != target {
505            drag.target = target;
506            self.retarget_row_motions(ctx, true);
507        } else {
508            ctx.request_paint();
509        }
510    }
511
512    fn retarget_row_motions(&mut self, ctx: &mut EventCtx, animate: bool) {
513        let order = self.desired_order();
514        let (offsets, _) = self.compute_offsets_for_order(&order);
515        let base_y = self.content_y;
516        let theme = self.resolved_theme();
517        let duration = self
518            .animation_duration
519            .unwrap_or_else(|| theme.motion.duration_fast.into());
520        let easing = self
521            .animation_easing
522            .unwrap_or(theme.motion.easing_standard);
523        for item in 0..self.row_motions.len() {
524            if self.active_drag.is_some_and(|drag| drag.item == item) {
525                continue;
526            }
527            let target_y = base_y + offsets.get(item).copied().unwrap_or(0.0);
528            let motion = &mut self.row_motions[item];
529            if animate {
530                motion.set_target(target_y, duration, easing, ctx);
531            } else {
532                motion.jump_to(target_y);
533            }
534        }
535
536        ctx.request_paint();
537    }
538
539    fn reset_drag(&mut self, ctx: &mut EventCtx, animate: bool) {
540        self.press = None;
541        self.active_drag = None;
542        self.retarget_row_motions(ctx, animate);
543    }
544
545    fn finish_reorder(&mut self, ctx: &mut EventCtx) {
546        let Some(drag) = self.active_drag else {
547            self.reset_drag(ctx, true);
548            return;
549        };
550        let Some(from) = self.order.iter().position(|item| *item == drag.item) else {
551            self.reset_drag(ctx, true);
552            return;
553        };
554        let mut to = drag.target.min(self.order.len().saturating_sub(1));
555
556        if let Some(motion) = self.row_motions.get_mut(drag.item) {
557            motion.jump_to(drag.position.y - drag.drag_offset_y);
558        }
559
560        if from != to {
561            let item = self.order.remove(from);
562            if to > self.order.len() {
563                to = self.order.len();
564            }
565            self.order.insert(to, item);
566            self.current = to;
567            if let Some(callback) = &mut self.on_reorder {
568                callback(ctx, ReorderableListChange { item, from, to });
569            }
570            ctx.request_semantics();
571        }
572
573        self.reset_drag(ctx, true);
574    }
575
576    fn marker_y(&self) -> Option<f32> {
577        let drag = self.active_drag?;
578        let order = self.desired_order();
579        let (offsets, _) = self.compute_offsets_for_order(&order);
580        let base_y = self.content_y;
581        Some(base_y + offsets.get(drag.item).copied().unwrap_or(0.0))
582    }
583}
584
585impl Widget for ReorderableList {
586    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
587        match event {
588            Event::Keyboard(key) => self.handle_key(ctx, key),
589            Event::Pointer(pointer)
590                if pointer.kind == PointerEventKind::Down
591                    && pointer.button == Some(PointerButton::Primary)
592                    && ctx.phase() != sui_runtime::EventPhase::Capture =>
593            {
594                if let Some(press) = self.press_at(pointer.pointer_id, pointer.position) {
595                    // Keys act on the row last pressed.
596                    self.current = press.from;
597                    self.press = Some(press);
598                    ctx.request_focus();
599                    ctx.request_pointer_capture(pointer.pointer_id);
600                    ctx.set_handled();
601                }
602            }
603            Event::Pointer(pointer)
604                if pointer.kind == PointerEventKind::Move
605                    && self
606                        .press
607                        .is_some_and(|press| press.pointer_id == pointer.pointer_id) =>
608            {
609                if let Some(drag) = self.active_drag {
610                    if drag.pointer_id == pointer.pointer_id {
611                        let target = self.target_index_at(drag.item, pointer.position);
612                        self.set_drag_target(ctx, target, pointer.position);
613                        ctx.set_handled();
614                    }
615                    return;
616                }
617
618                let press = self.press.unwrap();
619                let delta = pointer.position - press.start_position;
620                let distance_sq = (delta.x * delta.x) + (delta.y * delta.y);
621                if distance_sq >= self.drag_threshold * self.drag_threshold {
622                    self.start_drag(ctx, press, pointer.position);
623                    ctx.set_handled();
624                }
625            }
626            Event::Pointer(pointer)
627                if matches!(
628                    pointer.kind,
629                    PointerEventKind::Up | PointerEventKind::Cancel
630                ) && self
631                    .press
632                    .is_some_and(|press| press.pointer_id == pointer.pointer_id) =>
633            {
634                if self.active_drag.is_none() {
635                    self.press = None;
636                }
637                ctx.release_pointer_capture(pointer.pointer_id);
638                ctx.set_handled();
639            }
640            Event::Drag(drag) if drag.scope_id == self.scope.id() => {
641                if drag.payload.custom_kind() != Some(REORDERABLE_LIST_PAYLOAD_KIND) {
642                    return;
643                }
644                let Some(payload) = drag.payload.custom_data::<ReorderPayload>() else {
645                    return;
646                };
647                if payload.list != ctx.widget_id().get() {
648                    return;
649                }
650
651                match drag.kind {
652                    DragEventKind::Enter | DragEventKind::Over => {
653                        let target = self.target_index_at(payload.item, drag.position);
654                        self.set_drag_target(ctx, target, drag.position);
655                        ctx.accept_drop(DropEffect::Move);
656                    }
657                    DragEventKind::Leave => {
658                        if self
659                            .active_drag
660                            .is_some_and(|active| active.session_id == drag.session_id)
661                        {
662                            let from = self.active_drag.map(|active| active.from).unwrap_or(0);
663                            self.set_drag_target(ctx, from, drag.position);
664                        }
665                    }
666                    DragEventKind::Drop if drag.target == Some(ctx.widget_id()) => {
667                        self.finish_reorder(ctx);
668                        ctx.set_handled();
669                    }
670                    DragEventKind::End => {
671                        if matches!(drag.outcome, Some(DragOutcome::Cancelled)) {
672                            self.reset_drag(ctx, true);
673                        } else {
674                            self.press = None;
675                            self.active_drag = None;
676                        }
677                    }
678                    _ => {}
679                }
680            }
681            _ => {}
682        }
683    }
684
685    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
686        self.sync_storage();
687
688        let child_constraints = Constraints::new(
689            Size::ZERO,
690            Size::new(constraints.max.width.max(0.0), f32::INFINITY),
691        );
692        let mut width: f32 = 0.0;
693        for index in 0..self.children.len() {
694            let size = self.children.measure_child(index, ctx, child_constraints);
695            self.row_sizes[index] = size;
696            width = width.max(size.width);
697        }
698
699        let (_, height) = self.compute_offsets_for_order(&self.order);
700        self.content_height = height;
701        constraints.clamp(Size::new(width, height))
702    }
703
704    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
705        self.sync_storage();
706        let (offsets, height) = self.compute_offsets_for_order(&self.order);
707        self.content_y = bounds.y();
708        self.row_offsets = offsets.clone();
709        self.content_height = height;
710
711        for (item, &offset) in offsets.iter().enumerate().take(self.children.len()) {
712            let size = Size::new(bounds.width(), self.row_sizes[item].height);
713            let rect = Rect::new(bounds.x(), bounds.y() + offset, size.width, size.height);
714            self.row_bounds[item] = rect;
715            self.children.arrange_child(item, ctx, rect);
716            if !self.row_motions[item].is_animating(ctx) && self.active_drag.is_none() {
717                self.row_motions[item].jump_to(rect.y());
718            }
719        }
720    }
721
722    fn paint(&self, ctx: &mut PaintCtx) {
723        let bounds = ctx.bounds();
724        ctx.push_clip_rect(bounds);
725
726        let active_item = self.active_drag.map(|drag| drag.item);
727        for item in self.desired_order() {
728            if active_item == Some(item) {
729                continue;
730            }
731            let rect = self.row_bounds.get(item).copied().unwrap_or(Rect::ZERO);
732            let y = self
733                .row_motions
734                .get(item)
735                .map(|motion| motion.at(ctx))
736                .unwrap_or(rect.y());
737            ctx.translate(Vector::new(0.0, y - rect.y()));
738            self.children.as_slice()[item].paint(ctx);
739            ctx.pop_transform();
740        }
741
742        if let Some(marker_y) = self.marker_y() {
743            let theme = self.resolved_theme();
744            let marker = Rect::new(
745                bounds.x() + 4.0,
746                (marker_y - 1.0).max(bounds.y()),
747                (bounds.width() - 8.0).max(0.0),
748                2.0,
749            );
750            ctx.fill(Path::rounded_rect(marker, 1.0), theme.palette.border_focus);
751        }
752
753        if let Some(drag) = self.active_drag {
754            let item = drag.item;
755            let rect = self.row_bounds.get(item).copied().unwrap_or(Rect::ZERO);
756            let y = drag.position.y - drag.drag_offset_y;
757            ctx.push_transform(Transform::translation(0.0, y - rect.y()));
758            self.children.as_slice()[item].paint(ctx);
759            ctx.pop_transform();
760        } else if ctx.is_focused()
761            && let Some(item) = self.order.get(self.current).copied()
762        {
763            // The row the keyboard acts on, drawn inside the list's clip.
764            let theme = self.resolved_theme();
765            let width = ctx
766                .dpi()
767                .physical_pixels_to_logical(theme.metrics.focus_ring_width.max(1.0));
768            let rect = self.row_bounds.get(item).copied().unwrap_or(Rect::ZERO);
769            let y = self
770                .row_motions
771                .get(item)
772                .map_or(rect.y(), |motion| motion.at(ctx));
773            stroke_border(
774                ctx,
775                Rect::new(rect.x(), y, rect.width(), rect.height()),
776                theme.metrics.corner_radius,
777                width,
778                theme.palette.focus_ring,
779            );
780        }
781
782        ctx.pop_clip();
783    }
784
785    fn accepts_focus(&self) -> bool {
786        true
787    }
788
789    fn semantics(&self, ctx: &mut SemanticsCtx) {
790        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::List, ctx.bounds());
791        node.name = Some(self.name.clone());
792        node.description = Some(
793            "Alt+Up and Alt+Down move the focused row; Alt+Home and Alt+End move it to either end"
794                .to_string(),
795        );
796        if let Some(item) = self.order.get(self.current).copied() {
797            node.value = Some(SemanticsValue::Text(format!(
798                "{}, position {} of {}",
799                self.name_of(item),
800                self.current + 1,
801                self.order.len()
802            )));
803        }
804        node.actions = vec![SemanticsAction::Focus];
805        ctx.push(node);
806        if let Some(announcement) = &self.announcement {
807            let mut status = SemanticsNode::new(self.status_id, SemanticsRole::Status, Rect::ZERO);
808            status.parent = Some(ctx.widget_id());
809            status.name = Some(announcement.clone());
810            status.live_region = Some(SemanticsLiveRegion::Polite);
811            ctx.push(status);
812        }
813        self.children.semantics(ctx);
814    }
815
816    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
817        self.children.visit_children(visitor);
818    }
819
820    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
821        self.children.visit_children_mut(visitor);
822    }
823}
824
825/// Whether `target` is `root` or one of its descendants.
826fn pod_contains(root: &WidgetPod, target: WidgetId) -> bool {
827    struct Finder {
828        target: WidgetId,
829        found: bool,
830    }
831
832    impl WidgetPodVisitor for Finder {
833        fn visit(&mut self, child: &WidgetPod) {
834            if self.found {
835                return;
836            }
837            if child.id() == self.target {
838                self.found = true;
839            } else {
840                child.visit_children(self);
841            }
842        }
843    }
844
845    if root.id() == target {
846        return true;
847    }
848    let mut finder = Finder {
849        target,
850        found: false,
851    };
852    root.visit_children(&mut finder);
853    finder.found
854}
855
856#[cfg(test)]
857mod tests {
858    use std::{cell::RefCell, rc::Rc};
859
860    use super::*;
861    use crate::{Button, SizedBox, Stack};
862    use sui_core::{Modifiers, PointerButtons, PointerEvent, PointerKind, Result, WindowId};
863    use sui_runtime::{Application, Runtime, WindowBuilder};
864
865    fn primary_pointer(kind: PointerEventKind, position: Point, pressed: bool) -> Event {
866        let mut buttons = PointerButtons::NONE;
867        if pressed {
868            buttons.insert(PointerButton::Primary);
869        }
870        Event::Pointer(PointerEvent {
871            pointer_id: 1,
872            kind,
873            position,
874            delta: Vector::ZERO,
875            scroll_delta: None,
876            button: Some(PointerButton::Primary),
877            buttons,
878            modifiers: Modifiers::NONE,
879            pointer_kind: PointerKind::Mouse,
880            is_primary: true,
881        })
882    }
883
884    fn build_runtime<W>(root: W) -> (Runtime, WindowId)
885    where
886        W: Widget + 'static,
887    {
888        let runtime = Application::new()
889            .window(WindowBuilder::new().title("Reorder").root(root))
890            .build()
891            .unwrap();
892        let window_id = runtime.window_ids()[0];
893        (runtime, window_id)
894    }
895
896    #[test]
897    fn reorderable_list_reports_reorder_after_pointer_drag() -> Result<()> {
898        let changes = Rc::new(RefCell::new(Vec::new()));
899        let list = ReorderableList::new("Tasks")
900            .gap(0.0)
901            .item(SizedBox::new().width(120.0).height(30.0))
902            .item(SizedBox::new().width(120.0).height(30.0))
903            .item(SizedBox::new().width(120.0).height(30.0))
904            .on_reorder({
905                let changes = Rc::clone(&changes);
906                move |change| changes.borrow_mut().push(change)
907            });
908        let (mut runtime, window_id) = build_runtime(list);
909        let _ = runtime.render(window_id)?;
910
911        runtime.handle_event(
912            window_id,
913            primary_pointer(PointerEventKind::Down, Point::new(10.0, 15.0), true),
914        )?;
915        runtime.handle_event(
916            window_id,
917            primary_pointer(PointerEventKind::Move, Point::new(10.0, 48.0), true),
918        )?;
919        runtime.handle_event(
920            window_id,
921            primary_pointer(PointerEventKind::Move, Point::new(10.0, 78.0), true),
922        )?;
923        runtime.handle_event(
924            window_id,
925            primary_pointer(PointerEventKind::Up, Point::new(10.0, 78.0), false),
926        )?;
927
928        assert_eq!(
929            &*changes.borrow(),
930            &[ReorderableListChange {
931                item: 0,
932                from: 0,
933                to: 2
934            }]
935        );
936        Ok(())
937    }
938
939    fn key(name: &str, alt: bool) -> Event {
940        let mut event = KeyboardEvent::new(name, KeyState::Pressed);
941        event.modifiers.alt = alt;
942        Event::Keyboard(event)
943    }
944
945    const NAMES: [&str; 3] = ["Draft", "Review", "Ship"];
946
947    fn status(runtime: &Runtime, window_id: WindowId) -> Option<String> {
948        runtime
949            .semantics(window_id)
950            .ok()?
951            .iter()
952            .find(|node| node.role == SemanticsRole::Status)
953            .and_then(|node| node.name.clone())
954    }
955
956    #[test]
957    fn alt_arrows_move_the_row_the_keyboard_is_on() -> Result<()> {
958        let changes = Rc::new(RefCell::new(Vec::new()));
959        let list = ReorderableList::new("Tasks")
960            .gap(0.0)
961            .item(SizedBox::new().width(120.0).height(30.0))
962            .item(SizedBox::new().width(120.0).height(30.0))
963            .item(SizedBox::new().width(120.0).height(30.0))
964            .item_name(|item| NAMES[item].to_string())
965            .on_reorder({
966                let changes = Rc::clone(&changes);
967                move |change| changes.borrow_mut().push(change)
968            });
969        let (mut runtime, window_id) = build_runtime(list);
970        let _ = runtime.render(window_id)?;
971
972        // Pressing a row focuses the list with the keyboard on that row.
973        runtime.handle_event(
974            window_id,
975            primary_pointer(PointerEventKind::Down, Point::new(10.0, 15.0), true),
976        )?;
977        runtime.handle_event(
978            window_id,
979            primary_pointer(PointerEventKind::Up, Point::new(10.0, 15.0), false),
980        )?;
981        let list_node = |runtime: &Runtime| {
982            runtime
983                .semantics(window_id)
984                .unwrap()
985                .iter()
986                .find(|node| node.role == SemanticsRole::List)
987                .cloned()
988                .unwrap()
989        };
990        let _ = runtime.render(window_id)?;
991        assert_eq!(
992            runtime.focused_widget(window_id)?,
993            Some(list_node(&runtime).id)
994        );
995
996        runtime.handle_event(window_id, key("ArrowDown", false))?;
997        let _ = runtime.render(window_id)?;
998        assert_eq!(
999            list_node(&runtime).value,
1000            Some(SemanticsValue::Text("Review, position 2 of 3".to_string()))
1001        );
1002        assert!(changes.borrow().is_empty(), "plain arrows only choose");
1003
1004        runtime.handle_event(window_id, key("ArrowDown", true))?;
1005        let _ = runtime.render(window_id)?;
1006        assert_eq!(
1007            status(&runtime, window_id).as_deref(),
1008            Some("Moved Review to position 3 of 3")
1009        );
1010        runtime.handle_event(window_id, key("Home", true))?;
1011        let _ = runtime.render(window_id)?;
1012        assert_eq!(
1013            status(&runtime, window_id).as_deref(),
1014            Some("Moved Review to position 1 of 3")
1015        );
1016        runtime.handle_event(window_id, key("ArrowUp", true))?;
1017        let _ = runtime.render(window_id)?;
1018        assert_eq!(
1019            status(&runtime, window_id).as_deref(),
1020            Some("Review is already at position 1 of 3")
1021        );
1022
1023        assert_eq!(
1024            &*changes.borrow(),
1025            &[
1026                ReorderableListChange {
1027                    item: 1,
1028                    from: 1,
1029                    to: 2
1030                },
1031                ReorderableListChange {
1032                    item: 1,
1033                    from: 2,
1034                    to: 0
1035                },
1036            ]
1037        );
1038        Ok(())
1039    }
1040
1041    #[test]
1042    fn alt_arrows_move_the_row_holding_focus() -> Result<()> {
1043        let changes = Rc::new(RefCell::new(Vec::new()));
1044        let row = |name: &'static str| Stack::horizontal().with_child(Button::new(name));
1045        let list = ReorderableList::new("Tasks")
1046            .item(row("Draft"))
1047            .item(row("Review"))
1048            .item(row("Ship"))
1049            .on_reorder({
1050                let changes = Rc::clone(&changes);
1051                move |change| changes.borrow_mut().push(change)
1052            });
1053        let (mut runtime, window_id) = build_runtime(list);
1054        let _ = runtime.render(window_id)?;
1055        let ship = runtime
1056            .semantics(window_id)?
1057            .iter()
1058            .find(|node| node.name.as_deref() == Some("Ship"))
1059            .map(|node| node.id)
1060            .unwrap();
1061        runtime.handle_semantics_action(
1062            window_id,
1063            ship,
1064            sui_core::SemanticsActionRequest::Focus,
1065        )?;
1066        assert_eq!(runtime.focused_widget(window_id)?, Some(ship));
1067
1068        runtime.handle_event(window_id, key("ArrowUp", true))?;
1069        assert_eq!(
1070            &*changes.borrow(),
1071            &[ReorderableListChange {
1072                item: 2,
1073                from: 2,
1074                to: 1
1075            }]
1076        );
1077        assert_eq!(
1078            runtime.focused_widget(window_id)?,
1079            Some(ship),
1080            "focus stays"
1081        );
1082        Ok(())
1083    }
1084}