dioxus-dnd 3.0.0

Modular, accessible drag-and-drop for Dioxus: sortable lists, kanban boards, trees, grids, file drops, multi-select, touch support and more
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
//! The zone registry: every mounted [`crate::core::DropZone`] records itself
//! here (id, label, drop callback, acceptance filter, and its mounted DOM
//! handle). Pointer drags hit-test against cached client rects; keyboard
//! navigation walks the zones in spatial order (top-to-bottom, left-to-right,
//! with unmeasured zones last in registration order).

use std::rc::Rc;
use std::sync::atomic::{AtomicU64, Ordering};

use dioxus::html::MountedData;
use dioxus::prelude::*;

use super::types::{Direction, DropOutcome, Point, Rect, ZoneId};

static NEXT_ZONE_REGISTRATION: AtomicU64 = AtomicU64::new(1);

/// Identifies one particular registration of a [`ZoneId`].
///
/// A zone id can be replaced in place. Async measurements carry this token
/// so a result started for the old registration cannot land in its
/// same-id replacement.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ZoneRegistration {
    id: ZoneId,
    generation: u64,
}

/// One registered drop zone.
pub struct ZoneRecord<T: Clone + 'static> {
    pub id: ZoneId,
    /// The enclosing zone, when this zone is nested inside another
    /// `DropZone` (discovered automatically via context).
    pub parent: Option<ZoneId>,
    /// Human label used in screen-reader announcements.
    pub label: Option<String>,
    /// Delivers a completed drop to the zone's owner.
    pub on_drop: Callback<DropOutcome<T>>,
    /// The zone's acceptance filter, if any.
    pub accepts: Option<Callback<T, bool>>,
    /// The zone's mounted element, once available. This plain value lives in
    /// the provider-owned registry storage; zones update it through
    /// [`ZoneRegistry::set_mounted`].
    pub mounted: Option<Rc<MountedData>>,
    /// Cached client rect (refreshed via [`ZoneRegistry::refresh_rects`]).
    /// This plain value lives in the provider-owned registry storage; zones
    /// update it through [`ZoneRegistry::set_rect_if_present`].
    pub rect: Option<Rect>,
}

impl<T: Clone + 'static> Clone for ZoneRecord<T> {
    fn clone(&self) -> Self {
        Self {
            id: self.id,
            parent: self.parent,
            label: self.label.clone(),
            on_drop: self.on_drop,
            accepts: self.accepts,
            mounted: self.mounted.clone(),
            rect: self.rect,
        }
    }
}

impl<T: Clone + 'static> ZoneRecord<T> {
    /// Does this zone accept the payload?
    pub fn accepts_payload(&self, payload: &T) -> bool {
        match self.accepts {
            Some(cb) => cb.call(payload.clone()),
            None => true,
        }
    }

    /// The cached client rect in this registry snapshot.
    pub fn cached_rect(&self) -> Option<Rect> {
        self.rect
    }

    /// The mounted element in this registry snapshot.
    pub fn mounted_handle(&self) -> Option<Rc<MountedData>> {
        self.mounted.clone()
    }
}

/// Registry of the currently mounted drop zones, in mount order.
pub struct ZoneRegistry<T: Clone + 'static> {
    zones: Signal<Vec<ZoneRecord<T>>>,
    /// Current generation for each id in `zones`. Kept separately so
    /// `ZoneRecord` remains constructible with a public struct literal.
    registrations: Signal<Vec<(ZoneId, u64)>>,
    /// Changes only when the zone set or a mounted handle changes. The debug
    /// overlay subscribes here so rect writes cannot retrigger measurement.
    mount_revision: Signal<u64>,
    /// Layout direction for spatial ordering (keyboard navigation).
    dir: Signal<Direction>,
}

impl<T: Clone + 'static> Copy for ZoneRegistry<T> {}
impl<T: Clone + 'static> Clone for ZoneRegistry<T> {
    fn clone(&self) -> Self {
        *self
    }
}
impl<T: Clone + 'static> PartialEq for ZoneRegistry<T> {
    fn eq(&self, other: &Self) -> bool {
        self.zones == other.zones && self.dir == other.dir
    }
}

impl<T: Clone + 'static> ZoneRegistry<T> {
    /// Wrap an existing signal. Prefer [`crate::core::hooks::use_dnd_provider`].
    pub fn from_signal(zones: Signal<Vec<ZoneRecord<T>>>) -> Self {
        Self {
            zones,
            registrations: Signal::new(Vec::new()),
            mount_revision: Signal::new(0),
            dir: Signal::new(Direction::default()),
        }
    }

    /// Layout direction spatial ordering follows.
    pub fn direction(&self) -> Direction {
        self.dir.try_peek().map(|dir| *dir).unwrap_or_default()
    }

    /// Set the layout direction (no-op if unchanged; safe to call every
    /// render). `DndProvider`'s `dir` prop calls this for you.
    pub fn set_direction(&mut self, dir: Direction) {
        let changed = self.dir.try_peek().map(|current| *current != dir);
        if changed == Ok(true) {
            if let Ok(mut current) = self.dir.try_write() {
                *current = dir;
            }
        }
    }

    /// Add (or replace, by id) a zone.
    pub fn register(&mut self, record: ZoneRecord<T>) -> ZoneRegistration {
        let registration = ZoneRegistration {
            id: record.id,
            generation: NEXT_ZONE_REGISTRATION.fetch_add(1, Ordering::Relaxed),
        };
        if let Ok(mut zones) = self.zones.try_write() {
            if let Some(existing) = zones.iter_mut().find(|z| z.id == record.id) {
                *existing = record;
            } else {
                zones.push(record);
            }
        }
        if let Ok(mut registrations) = self.registrations.try_write() {
            if let Some(existing) = registrations
                .iter_mut()
                .find(|(id, _)| *id == registration.id)
            {
                existing.1 = registration.generation;
            } else {
                registrations.push((registration.id, registration.generation));
            }
        }
        self.bump_mount_revision();
        registration
    }

    /// Update a zone's label in place (no-op if unchanged or unknown).
    pub fn sync_label(&mut self, id: ZoneId, label: Option<String>) {
        let needs = self
            .zones
            .try_peek()
            .map(|zones| zones.iter().any(|z| z.id == id && z.label != label))
            .unwrap_or(false);
        if needs {
            if let Ok(mut zones) = self.zones.try_write() {
                if let Some(z) = zones.iter_mut().find(|z| z.id == id) {
                    z.label = label;
                }
            }
        }
    }

    /// Remove a zone (call when its component unmounts).
    pub fn unregister(&mut self, id: ZoneId) {
        let removed = self.zones.try_write().is_ok_and(|mut zones| {
            let old_len = zones.len();
            zones.retain(|z| z.id != id);
            zones.len() != old_len
        });
        if let Ok(mut registrations) = self.registrations.try_write() {
            registrations.retain(|(registered_id, _)| *registered_id != id);
        }
        if removed {
            self.bump_mount_revision();
        }
    }

    /// Attach the mounted element to this exact registration. A stale
    /// registration token is ignored.
    pub fn set_mounted(&mut self, registration: ZoneRegistration, mounted: Rc<MountedData>) {
        if !self.is_current(registration) {
            return;
        }
        let mut changed = false;
        if let Ok(mut zones) = self.zones.try_write() {
            if let Some(zone) = zones.iter_mut().find(|z| z.id == registration.id) {
                zone.mounted = Some(mounted);
                changed = true;
            }
        }
        if changed {
            self.bump_mount_revision();
        }
    }

    /// Store a rect only while the registration that requested it is still
    /// current. This never inserts a missing zone and therefore cannot
    /// resurrect one that unmounted during an async measurement.
    pub fn set_rect_if_present(&mut self, registration: ZoneRegistration, rect: Rect) {
        if !self.is_current(registration) {
            return;
        }
        if let Ok(mut zones) = self.zones.try_write() {
            if let Some(zone) = zones.iter_mut().find(|z| z.id == registration.id) {
                zone.rect = Some(rect);
            }
        }
    }

    /// Set geometry for the current registration of `id`. This is the
    /// synchronous/manual counterpart to [`Self::set_rect_if_present`], used
    /// by custom layout adapters and the headless test driver.
    pub fn set_rect(&mut self, id: ZoneId, rect: Rect) {
        if let Some(registration) = self.current_registration(id) {
            self.set_rect_if_present(registration, rect);
        }
    }

    /// Look up a zone by id.
    pub fn get(&self, id: ZoneId) -> Option<ZoneRecord<T>> {
        self.zones
            .try_peek()
            .ok()?
            .iter()
            .find(|z| z.id == id)
            .cloned()
    }

    /// The zone's cached client rect, read without subscribing. Returns
    /// `None` when unmeasured, unknown, or the provider is already gone.
    pub fn cached_rect(&self, id: ZoneId) -> Option<Rect> {
        self.zones
            .try_peek()
            .ok()?
            .iter()
            .find(|z| z.id == id)
            .and_then(ZoneRecord::cached_rect)
    }

    /// The zone's mounted element, read without subscribing. Returns `None`
    /// before mount, for an unknown zone, or after provider teardown.
    pub fn mounted_handle(&self, id: ZoneId) -> Option<Rc<MountedData>> {
        self.zones
            .try_peek()
            .ok()?
            .iter()
            .find(|z| z.id == id)
            .and_then(ZoneRecord::mounted_handle)
    }

    /// Every registered zone, in registration order. Unlike the peeking
    /// lookups around it this is a *subscribing* read - a component
    /// rendering from it re-renders when zones mount or unmount - because
    /// its consumers (the debug overlay, your own devtools) are renderers.
    pub fn records(&self) -> Vec<ZoneRecord<T>> {
        self.zones
            .try_read()
            .map(|zones| zones.to_vec())
            .unwrap_or_default()
    }

    /// Is a zone with this id registered *here*? The parent-zone context is
    /// shared across payload types, so a record's `parent` can name a zone
    /// living in another type's registry - check before navigating to one.
    pub fn contains(&self, id: ZoneId) -> bool {
        self.zones
            .try_peek()
            .is_ok_and(|zones| zones.iter().any(|z| z.id == id))
    }

    /// The zone keyboard navigation should enter when ascending from
    /// `current`: its parent, but only when that parent is registered in
    /// this registry. A `DropZone<A>` nested inside a `DropZone<B>` records
    /// B's id as its parent, and entering an id this registry can't resolve
    /// would leave the drag hovering a zone that can never receive it.
    pub fn ascend(&self, current: ZoneId) -> Option<ZoneId> {
        self.parent_of(current).filter(|pid| self.contains(*pid))
    }

    /// All zones accepting `payload`, in registration order.
    pub fn acceptable(&self, payload: &T) -> Vec<ZoneRecord<T>> {
        self.zones
            .try_peek()
            .map(|zones| {
                zones
                    .iter()
                    .filter(|z| z.accepts_payload(payload))
                    .cloned()
                    .collect()
            })
            .unwrap_or_default()
    }

    /// The next/previous zone (cyclic) relative to `current` among zones that
    /// accept `payload`. `step` is `+1` or `-1`.
    ///
    /// Order is **spatial** (top-to-bottom, then left-to-right) for zones
    /// with measured rects - call [`Self::refresh_rects`] first, as the
    /// built-in keyboard interaction does on pickup. Unmeasured zones keep
    /// registration order, after the measured ones.
    pub fn step_zone(&self, current: Option<ZoneId>, payload: &T, step: isize) -> Option<ZoneId> {
        let mut zones = self.acceptable(payload);
        spatial_sort(&mut zones, self.direction());
        let current_ix = current.and_then(|c| zones.iter().position(|z| z.id == c));
        cycle(zones.len(), current_ix, step).map(|ix| zones[ix].id)
    }

    /// The parent of a zone, if it's nested.
    pub fn parent_of(&self, id: ZoneId) -> Option<ZoneId> {
        self.zones
            .try_peek()
            .ok()?
            .iter()
            .find(|z| z.id == id)?
            .parent
    }

    /// Zones directly inside `parent` (`None` = root level) that accept
    /// `payload`, in spatial order (top-to-bottom, left-to-right; unmeasured
    /// zones keep registration order at the end).
    pub fn children_of(&self, parent: Option<ZoneId>, payload: &T) -> Vec<ZoneRecord<T>> {
        let mut zones: Vec<_> = self
            .zones
            .try_peek()
            .map(|zones| {
                zones
                    .iter()
                    .filter(|z| z.parent == parent && z.accepts_payload(payload))
                    .cloned()
                    .collect()
            })
            .unwrap_or_default();
        spatial_sort(&mut zones, self.direction());
        zones
    }

    /// Next/previous zone (cyclic) among the *siblings* of `current` -
    /// zones sharing its parent. With no `current`, cycles the root level.
    pub fn step_sibling(
        &self,
        current: Option<ZoneId>,
        payload: &T,
        step: isize,
    ) -> Option<ZoneId> {
        let parent = current.and_then(|c| self.parent_of(c));
        let siblings = self.children_of(parent, payload);
        let current_ix = current.and_then(|c| siblings.iter().position(|z| z.id == c));
        cycle(siblings.len(), current_ix, step).map(|ix| siblings[ix].id)
    }

    /// The first (spatially) acceptable zone nested inside `id`.
    pub fn first_child(&self, id: ZoneId, payload: &T) -> Option<ZoneId> {
        self.children_of(Some(id), payload).first().map(|z| z.id)
    }

    /// Topmost zone containing `point` (client coordinates), using cached
    /// rects - call [`Self::refresh_rects`] when a drag starts. Later-mounted
    /// zones win, approximating DOM paint order.
    pub fn hit_test(&self, point: Point) -> Option<ZoneId> {
        self.zones
            .try_peek()
            .ok()?
            .iter()
            .rev()
            .find(|z| z.cached_rect().map(|r| r.contains(point)).unwrap_or(false))
            .map(|z| z.id)
    }

    /// Like [`Self::hit_test`], but acceptance-aware: it returns the topmost
    /// zone that both contains the point **and** accepts `payload`, and when
    /// no such zone contains the point, falls back to the acceptable zone
    /// whose *rect* is nearest - within `max_distance` CSS px of its closest
    /// edge, not its center, so a large zone snaps a release right beside it
    /// even though its center sits far away. Skipping zones that reject the
    /// payload lets a drop land on an accepting zone sitting *under* a
    /// rejecting (or decorative) one, and is friendlier for imprecise
    /// (touch) drops that land in the gutter between zones.
    pub fn hit_test_closest(&self, point: Point, payload: &T, max_distance: f64) -> Option<ZoneId> {
        if let Some(hit) = self
            .zones
            .try_peek()
            .ok()?
            .iter()
            .rev()
            .find(|z| {
                z.accepts_payload(payload)
                    && z.cached_rect().map(|r| r.contains(point)).unwrap_or(false)
            })
            .map(|z| z.id)
        {
            return Some(hit);
        }
        let mut best: Option<(ZoneId, f64)> = None;
        for z in self.acceptable(payload) {
            let Some(r) = z.cached_rect() else { continue };
            // Distance to the rect's nearest point (zero on either axis the
            // point already overlaps), not to its center.
            let dx = (r.x - point.x).max(point.x - (r.x + r.width)).max(0.0);
            let dy = (r.y - point.y).max(point.y - (r.y + r.height)).max(0.0);
            let d = (dx * dx + dy * dy).sqrt();
            if d <= max_distance && best.map(|(_, bd)| d < bd).unwrap_or(true) {
                best = Some((z.id, d));
            }
        }
        best.map(|(id, _)| id)
    }

    /// Re-measure every mounted zone's client rect and **wait** for the
    /// measurements to land - unlike [`Self::refresh_rects`], which fires
    /// and forgets. Use before a hit-test that must see fresh geometry
    /// (e.g. retrying a missed touch drop after a layout change).
    pub async fn measure_all(&self) {
        let zones = self.measurement_targets();
        for (registration, mounted) in zones {
            if let Ok(r) = mounted.get_client_rect().await {
                // The zone can unmount or be replaced during the await (a
                // closing window mid-drag is the common case). The
                // generation check quietly drops that stale measurement.
                let mut registry = *self;
                registry.set_rect_if_present(
                    registration,
                    Rect::new(r.origin.x, r.origin.y, r.size.width, r.size.height),
                );
            }
        }
    }

    /// Re-measure every mounted zone's client rect (async, spawned).
    pub fn refresh_rects(&self) {
        for (registration, mounted) in self.measurement_targets() {
            let mut registry = *self;
            spawn(async move {
                if let Ok(r) = mounted.get_client_rect().await {
                    // See measure_all: the zone can die or be replaced
                    // while this measurement is in flight.
                    registry.set_rect_if_present(
                        registration,
                        Rect::new(r.origin.x, r.origin.y, r.size.width, r.size.height),
                    );
                }
            });
        }
    }

    /// Subscribe an effect to registration/mount changes without also
    /// subscribing it to rect writes in the main registry vector.
    pub(crate) fn track_mounts(&self) {
        let _ = self.mount_revision.try_read();
    }

    fn measurement_targets(&self) -> Vec<(ZoneRegistration, Rc<MountedData>)> {
        let registrations = self
            .registrations
            .try_peek()
            .map(|registrations| registrations.clone())
            .unwrap_or_default();
        self.zones
            .try_peek()
            .map(|zones| {
                zones
                    .iter()
                    .filter_map(|zone| {
                        let mounted = zone.mounted_handle()?;
                        let generation = registrations
                            .iter()
                            .find(|(id, _)| *id == zone.id)
                            .map(|(_, generation)| *generation)?;
                        Some((
                            ZoneRegistration {
                                id: zone.id,
                                generation,
                            },
                            mounted,
                        ))
                    })
                    .collect()
            })
            .unwrap_or_default()
    }

    fn is_current(&self, registration: ZoneRegistration) -> bool {
        self.registrations.try_peek().is_ok_and(|registrations| {
            registrations.iter().any(|(id, generation)| {
                *id == registration.id && *generation == registration.generation
            })
        })
    }

    fn current_registration(&self, id: ZoneId) -> Option<ZoneRegistration> {
        self.registrations
            .try_peek()
            .ok()?
            .iter()
            .find(|(registered_id, _)| *registered_id == id)
            .map(|(_, generation)| ZoneRegistration {
                id,
                generation: *generation,
            })
    }

    fn bump_mount_revision(&mut self) {
        if let Ok(mut revision) = self.mount_revision.try_write() {
            *revision = revision.wrapping_add(1);
        }
    }
}

/// A payload-type-erased "re-measure your zones" channel, shared by every
/// registry under one provider tree.
///
/// Cached client rects go stale the moment layout moves under a live drag -
/// scrolling being the everyday case. Registries are per payload type, but
/// the things that move layout (an auto-scrolling container, your own
/// scroll surface, a collapsing panel) shouldn't need to know any payload
/// type to say "geometry changed". Each provider registers a thunk here
/// that re-measures its own registry **only while it has a drag in
/// flight**, so pinging the channel from every scroll event costs nothing
/// while idle.
///
/// [`crate::autoscroll::AutoScroll`] pings this automatically after every
/// scroll it performs (and on any other scroll of its container); grab the
/// channel with [`crate::core::hooks::use_rect_refresh`] to wire up custom
/// layout mutators.
pub struct RectRefresh {
    thunks: Signal<Vec<(u64, Callback<()>)>>,
}

impl Copy for RectRefresh {}
impl Clone for RectRefresh {
    fn clone(&self) -> Self {
        *self
    }
}
impl PartialEq for RectRefresh {
    fn eq(&self, other: &Self) -> bool {
        self.thunks == other.thunks
    }
}

impl RectRefresh {
    /// Wrap an existing signal. Prefer [`crate::core::hooks::use_dnd_provider`],
    /// which creates one per provider *tree* (nested providers inherit and
    /// re-provide the outermost channel).
    pub fn from_signal(thunks: Signal<Vec<(u64, Callback<()>)>>) -> Self {
        Self { thunks }
    }

    /// Ask every provider in the tree to re-measure its zones. Providers
    /// without a drag in flight ignore the ping, so this is safe to call
    /// from high-frequency sources like scroll events.
    pub fn refresh_all(&self) {
        for (_, thunk) in self.thunks.peek().iter() {
            thunk.call(());
        }
    }

    /// Number of registered providers. Diagnostics and tests.
    pub fn len(&self) -> usize {
        self.thunks.peek().len()
    }

    /// Whether any provider is registered.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Add (or replace, by key) a provider's re-measure thunk.
    pub(crate) fn register(&mut self, key: u64, thunk: Callback<()>) {
        let mut thunks = self.thunks.write();
        if let Some(existing) = thunks.iter_mut().find(|(k, _)| *k == key) {
            existing.1 = thunk;
        } else {
            thunks.push((key, thunk));
        }
    }

    /// Remove a provider's thunk (call when the provider unmounts).
    pub(crate) fn unregister(&mut self, key: u64) {
        self.thunks.write().retain(|(k, _)| *k != key);
    }
}

/// Sort zones spatially: measured rects by (top, reading order), unmeasured
/// last in their original relative order. Reading order within a row is
/// left-to-right in LTR and right-to-left in RTL, so keyboard traversal
/// follows what the user sees either way.
fn spatial_sort<T: Clone + 'static>(zones: &mut [ZoneRecord<T>], dir: Direction) {
    let reading_x = move |x: f64| match dir {
        Direction::Ltr => x,
        Direction::Rtl => -x,
    };
    zones.sort_by(|a, b| match (a.cached_rect(), b.cached_rect()) {
        (Some(ra), Some(rb)) => (ra.y, reading_x(ra.x))
            .partial_cmp(&(rb.y, reading_x(rb.x)))
            .unwrap_or(std::cmp::Ordering::Equal),
        (Some(_), None) => std::cmp::Ordering::Less,
        (None, Some(_)) => std::cmp::Ordering::Greater,
        (None, None) => std::cmp::Ordering::Equal,
    });
}

/// Cyclic index stepping: `None` current starts at the first (or last)
/// element depending on direction. Pure, for testability.
pub(crate) fn cycle(len: usize, current: Option<usize>, step: isize) -> Option<usize> {
    if len == 0 {
        return None;
    }
    Some(match current {
        None => {
            if step >= 0 {
                0
            } else {
                len - 1
            }
        }
        Some(ix) => (ix as isize + step).rem_euclid(len as isize) as usize,
    })
}

#[cfg(test)]
mod tests {
    use super::cycle;

    #[test]
    fn cycle_steps_and_wraps() {
        assert_eq!(cycle(0, None, 1), None);
        assert_eq!(cycle(3, None, 1), Some(0));
        assert_eq!(cycle(3, None, -1), Some(2));
        assert_eq!(cycle(3, Some(2), 1), Some(0));
        assert_eq!(cycle(3, Some(0), -1), Some(2));
        assert_eq!(cycle(3, Some(1), 1), Some(2));
    }
}