Skip to main content

gpui_material_extras/carousel/
state.rs

1use std::{collections::HashMap, rc::Rc};
2
3use gpui::{Context, FocusHandle, SharedString, Task};
4
5use super::{CarouselFling, CarouselItem};
6
7pub(super) struct ItemFocus {
8    pub(super) id: SharedString,
9    pub(super) enabled: bool,
10    pub(super) focus: FocusHandle,
11}
12
13/// Retained scroll position for one carousel. Observe the entity to read
14/// changes from input, programmatic navigation, or item replacement.
15pub struct CarouselState {
16    pub(super) items: Rc<[ItemFocus]>,
17    pub(super) requested: f32,
18    pub(super) sampled: f32,
19    pub(super) direct: bool,
20    pub(super) settle: Option<Task<()>>,
21    pub(super) settle_bumped: bool,
22    pub(super) settle_fling: Option<CarouselFling>,
23    pub(super) gesture_start: Option<f32>,
24    pending_index: Option<usize>,
25}
26
27impl CarouselState {
28    /// Starts at the given index when the first items are available.
29    pub fn new(initial_index: usize) -> Self {
30        Self {
31            items: Rc::from([]),
32            requested: 0.,
33            sampled: 0.,
34            direct: true,
35            settle: None,
36            settle_bumped: false,
37            settle_fling: None,
38            gesture_start: None,
39            pending_index: Some(initial_index),
40        }
41    }
42
43    /// Returns the item nearest the keyline, or no index when empty.
44    pub fn current_item(&self) -> Option<usize> {
45        (!self.items.is_empty()).then(|| self.sampled.round() as usize)
46    }
47
48    /// Returns the stable ID of the item nearest the keyline.
49    pub fn current_item_id(&self) -> Option<&SharedString> {
50        self.current_item().map(|index| &self.items[index].id)
51    }
52
53    /// Signed displacement from the nearest keyline in item units.
54    pub fn current_item_offset_fraction(&self) -> f32 {
55        self.sampled - self.sampled.round()
56    }
57
58    /// Immediately positions the carousel at the clamped index.
59    pub fn scroll_to_item(&mut self, index: usize, cx: &mut Context<Self>) {
60        self.navigate(index, true, cx);
61    }
62
63    /// Moves to the clamped index using the window's motion policy.
64    pub fn animate_scroll_to_item(&mut self, index: usize, cx: &mut Context<Self>) {
65        let immediate = cx.reduce_motion();
66        self.navigate(index, immediate, cx);
67    }
68
69    pub(super) fn clear_settle(&mut self) {
70        self.settle = None;
71        self.settle_bumped = false;
72        self.settle_fling = None;
73    }
74
75    fn navigate(&mut self, index: usize, immediate: bool, cx: &mut Context<Self>) {
76        if self.items.is_empty() {
77            self.pending_index = Some(index);
78        } else {
79            let index = index.min(self.items.len() - 1);
80            self.clear_settle();
81            self.gesture_start = None;
82            self.set_requested(index as f32, immediate, cx);
83        }
84    }
85
86    pub(super) fn set_requested(&mut self, position: f32, immediate: bool, cx: &mut Context<Self>) {
87        if !position.is_finite() {
88            return;
89        }
90        let position = position.clamp(0., self.items.len().saturating_sub(1) as f32);
91        if position != self.requested || self.direct != immediate {
92            self.requested = position;
93            self.direct = immediate;
94            cx.notify();
95        }
96        if immediate {
97            self.sample(position, cx);
98        }
99    }
100
101    pub(super) fn cancel_input(&mut self, cx: &mut Context<Self>) {
102        if self.gesture_start.take().is_some() {
103            self.clear_settle();
104            self.set_requested(self.requested, true, cx);
105        }
106    }
107
108    pub(super) fn sample(&mut self, sample: f32, cx: &mut Context<Self>) {
109        if !sample.is_finite() {
110            return;
111        }
112        let sample = sample.clamp(0., self.items.len().saturating_sub(1) as f32);
113        if sample != self.sampled {
114            self.sampled = sample;
115            cx.notify();
116        }
117    }
118
119    pub(super) fn sync(&mut self, items: &[CarouselItem], cx: &mut Context<Self>) {
120        let same_order = items.len() == self.items.len()
121            && items
122                .iter()
123                .zip(self.items.iter())
124                .all(|(item, known)| item.id == known.id);
125        if same_order
126            && items
127                .iter()
128                .zip(self.items.iter())
129                .all(|(item, known)| item.disabled != known.enabled)
130        {
131            return;
132        }
133
134        let previous_index = self.requested.round() as usize;
135        let previous_id = self.items.get(previous_index).map(|item| item.id.clone());
136        let previous: HashMap<_, _> = self
137            .items
138            .iter()
139            .map(|item| (&item.id, &item.focus))
140            .collect();
141        self.items = items
142            .iter()
143            .map(|item| ItemFocus {
144                id: item.id.clone(),
145                enabled: !item.disabled,
146                focus: previous
147                    .get(&item.id)
148                    .map_or_else(|| cx.focus_handle(), |focus| (*focus).clone()),
149            })
150            .collect();
151        if !same_order {
152            let index = if self.items.is_empty() {
153                0
154            } else {
155                self.pending_index
156                    .take()
157                    .unwrap_or_else(|| {
158                        previous_id
159                            .and_then(|id| self.items.iter().position(|item| item.id == id))
160                            .unwrap_or(previous_index)
161                    })
162                    .min(self.items.len() - 1)
163            };
164            self.clear_settle();
165            self.gesture_start = None;
166            self.set_requested(index as f32, true, cx);
167            // A different list can change the current item's ID at the same offset.
168            cx.notify();
169        }
170    }
171}
172
173#[cfg(all(test, feature = "test-support"))]
174mod tests {
175    use gpui::{AppContext as _, TestAppContext, div};
176
177    use super::*;
178
179    #[gpui::test]
180    fn state_rejects_non_finite_requested_and_sampled_values(cx: &mut TestAppContext) {
181        let state = cx.update(|cx| {
182            let state = cx.new(|_| CarouselState::new(1));
183            let items = [
184                CarouselItem::new("a", "A", div()),
185                CarouselItem::new("b", "B", div()),
186                CarouselItem::new("c", "C", div()),
187            ];
188            state.update(cx, |state, cx| {
189                state.sync(&items, cx);
190                assert_eq!(state.requested, 1.);
191                assert_eq!(state.sampled, 1.);
192
193                for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
194                    state.set_requested(bad, true, cx);
195                    assert_eq!(state.requested, 1.);
196                    assert_eq!(state.sampled, 1.);
197
198                    state.sample(bad, cx);
199                    assert_eq!(state.sampled, 1.);
200                }
201            });
202            state
203        });
204        cx.update(|cx| {
205            let s = state.read(cx);
206            assert_eq!(s.current_item(), Some(1));
207            assert_eq!(s.current_item_id().map(AsRef::as_ref), Some("b"));
208            assert_eq!(s.current_item_offset_fraction(), 0.);
209        });
210    }
211}