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::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) gesture_start: Option<f32>,
22    pending_index: Option<usize>,
23}
24
25impl CarouselState {
26    /// Starts at the given index when the first items are available.
27    pub fn new(initial_index: usize) -> Self {
28        Self {
29            items: Rc::from([]),
30            requested: 0.,
31            sampled: 0.,
32            direct: true,
33            settle: None,
34            gesture_start: None,
35            pending_index: Some(initial_index),
36        }
37    }
38
39    /// Returns the item nearest the keyline, or no index when empty.
40    pub fn current_item(&self) -> Option<usize> {
41        (!self.items.is_empty()).then(|| self.sampled.round() as usize)
42    }
43
44    /// Returns the stable ID of the item nearest the keyline.
45    pub fn current_item_id(&self) -> Option<&SharedString> {
46        self.current_item().map(|index| &self.items[index].id)
47    }
48
49    /// Signed displacement from the nearest keyline in item units.
50    pub fn current_item_offset_fraction(&self) -> f32 {
51        self.sampled - self.sampled.round()
52    }
53
54    /// Immediately positions the carousel at the clamped index.
55    pub fn scroll_to_item(&mut self, index: usize, cx: &mut Context<Self>) {
56        self.navigate(index, true, cx);
57    }
58
59    /// Moves to the clamped index using the window's motion policy.
60    pub fn animate_scroll_to_item(&mut self, index: usize, cx: &mut Context<Self>) {
61        let immediate = cx.reduce_motion();
62        self.navigate(index, immediate, cx);
63    }
64
65    fn navigate(&mut self, index: usize, immediate: bool, cx: &mut Context<Self>) {
66        if self.items.is_empty() {
67            self.pending_index = Some(index);
68        } else {
69            let index = index.min(self.items.len() - 1);
70            self.settle = None;
71            self.gesture_start = None;
72            self.set_requested(index as f32, immediate, cx);
73        }
74    }
75
76    pub(super) fn set_requested(&mut self, position: f32, immediate: bool, cx: &mut Context<Self>) {
77        if position != self.requested || self.direct != immediate {
78            self.requested = position;
79            self.direct = immediate;
80            cx.notify();
81        }
82        if immediate {
83            self.sample(position, cx);
84        }
85    }
86
87    pub(super) fn cancel_input(&mut self, cx: &mut Context<Self>) {
88        if self.gesture_start.take().is_some() {
89            self.settle = None;
90            self.set_requested(self.requested, true, cx);
91        }
92    }
93
94    pub(super) fn sample(&mut self, sample: f32, cx: &mut Context<Self>) {
95        let sample = sample.clamp(0., self.items.len().saturating_sub(1) as f32);
96        if sample != self.sampled {
97            self.sampled = sample;
98            cx.notify();
99        }
100    }
101
102    pub(super) fn sync(&mut self, items: &[CarouselItem], cx: &mut Context<Self>) {
103        let same_order = items.len() == self.items.len()
104            && items
105                .iter()
106                .zip(self.items.iter())
107                .all(|(item, known)| item.id == known.id);
108        if same_order
109            && items
110                .iter()
111                .zip(self.items.iter())
112                .all(|(item, known)| item.disabled != known.enabled)
113        {
114            return;
115        }
116
117        let previous_index = self.requested.round() as usize;
118        let previous_id = self.items.get(previous_index).map(|item| item.id.clone());
119        let previous: HashMap<_, _> = self
120            .items
121            .iter()
122            .map(|item| (&item.id, &item.focus))
123            .collect();
124        self.items = items
125            .iter()
126            .map(|item| ItemFocus {
127                id: item.id.clone(),
128                enabled: !item.disabled,
129                focus: previous
130                    .get(&item.id)
131                    .map_or_else(|| cx.focus_handle(), |focus| (*focus).clone()),
132            })
133            .collect();
134        if !same_order {
135            let index = if self.items.is_empty() {
136                0
137            } else {
138                self.pending_index
139                    .take()
140                    .unwrap_or_else(|| {
141                        previous_id
142                            .and_then(|id| self.items.iter().position(|item| item.id == id))
143                            .unwrap_or(previous_index)
144                    })
145                    .min(self.items.len() - 1)
146            };
147            self.settle = None;
148            self.gesture_start = None;
149            self.set_requested(index as f32, true, cx);
150            // A different list can change the current item's ID at the same offset.
151            cx.notify();
152        }
153    }
154}