Skip to main content

bhoo/
reorder.rs

1//! Keyed placement motion for reorderable grids and lists.
2
3use crate::{Frame, Rect};
4use std::collections::HashMap;
5
6#[derive(Clone, Copy)]
7struct Placement {
8    from: [f32; 2],
9    to: [f32; 2],
10    start: f64,
11    epoch: u64,
12}
13
14impl Placement {
15    fn sample(self, now: f64, duration: f64) -> [f32; 2] {
16        let t = ((now - self.start) / duration).clamp(0.0, 1.0) as f32;
17        let eased = (1.0 - (std::f32::consts::PI * t).cos()) * 0.5;
18        std::array::from_fn(|i| self.from[i] + (self.to[i] - self.from[i]) * eased)
19    }
20}
21
22/// Keeps the presented position of each item while the caller changes slot order.
23#[derive(Default)]
24pub struct ReorderMotion {
25    placements: HashMap<u64, Placement>,
26    epoch: u64,
27}
28
29impl ReorderMotion {
30    pub fn clear(&mut self) {
31        self.placements.clear();
32    }
33
34    /// Return presented bounds in destination order. Keys must be stable and
35    /// unique. Supply bounds and viewport in unscrolled content coordinates.
36    /// The caller owns drag tracking, slot choice, clipping and item rendering.
37    pub fn layout(
38        &mut self,
39        frame: &mut Frame<'_>,
40        viewport: Rect,
41        duration: f64,
42        items: impl IntoIterator<Item = (u64, Rect)>,
43    ) -> Vec<Rect> {
44        let reduced = frame.reduced_motion() || !duration.is_finite() || duration <= 0.0;
45        let now = frame.time();
46        self.epoch = self.epoch.wrapping_add(1);
47        let epoch = self.epoch;
48        let mut visible_motion = false;
49        let bounds = items
50            .into_iter()
51            .map(|(id, target)| {
52                let to = [target.x, target.y];
53                let placement = self.placements.entry(id).or_insert(Placement {
54                    from: to,
55                    to,
56                    start: now,
57                    epoch,
58                });
59                let current = if reduced {
60                    to
61                } else {
62                    placement.sample(now, duration)
63                };
64                if reduced || placement.to != to {
65                    *placement = Placement {
66                        from: current,
67                        to,
68                        start: now,
69                        epoch,
70                    };
71                }
72                placement.epoch = epoch;
73                let presented = Rect {
74                    x: current[0],
75                    y: current[1],
76                    ..target
77                };
78                let on_screen = |rect: Rect| {
79                    let area = rect.intersect(viewport);
80                    area.width > 0.0 && area.height > 0.0
81                };
82                visible_motion |=
83                    !reduced && current != to && (on_screen(presented) || on_screen(target));
84                presented
85            })
86            .collect();
87        self.placements
88            .retain(|_, placement| placement.epoch == epoch);
89        if visible_motion {
90            // Visibility was checked in content coordinates above.
91            frame.continuous(frame.clip);
92        }
93        bounds
94    }
95}
96
97/// Move an item to its destination while preserving the order of its neighbors.
98pub fn move_reorder_item<T>(items: &mut [T], from: usize, to: usize) -> bool {
99    if from == to || from >= items.len() || to >= items.len() {
100        return false;
101    }
102    if from < to {
103        items[from..=to].rotate_left(1);
104    } else {
105        items[to..=from].rotate_right(1);
106    }
107    true
108}
109
110#[cfg(test)]
111#[path = "reorder.spec.rs"]
112mod tests;