Skip to main content

gpui_material_extras/date_time/scroll_field/
render.rs

1use std::{cell::Cell, rc::Rc};
2
3use gpui::{
4    AccessibleAction, AnyElement, App, Div, ElementId, Entity, Hsla, InteractiveElement,
5    IntoElement, MouseButton, ParentElement, RenderOnce, Role, SharedString, Stateful,
6    StatefulInteractiveElement, Styled, Window,
7    accesskit::{ActionData, Orientation},
8    canvas, div,
9    prelude::FluentBuilder as _,
10    px,
11};
12use gpui_base::TestSupportExt;
13use gpui_material_components::Text;
14use gpui_material_foundation::{
15    InteractionFeedback, InteractionSource, InteractionState, InteractionTracker, Shape, animate,
16    color, current_material_theme,
17};
18use gpui_material_theme::{
19    ColorRole, CornerRole, CornerShape, MaterialTheme, MotionKind, MotionSpec, MotionSpeed,
20    TypeRole,
21};
22
23use super::state::{HEIGHT, ROW_HEIGHT, ScrollFieldState, ScrollOrigin, wrap};
24
25/// Optional overrides for the window theme's scroll field colors.
26#[derive(Clone, Copy, Debug, Default, PartialEq)]
27pub struct ScrollFieldColors {
28    /// Background fill color when enabled.
29    pub container: Option<Hsla>,
30    /// Text color of non-selected rows when enabled.
31    pub content: Option<Hsla>,
32    /// Text color of the centered selected row when enabled.
33    pub selected_content: Option<Hsla>,
34    /// Background fill color when disabled.
35    pub disabled_container: Option<Hsla>,
36    /// Text color of non-selected rows when disabled.
37    pub disabled_content: Option<Hsla>,
38    /// Text color of the centered selected row when disabled.
39    pub disabled_selected_content: Option<Hsla>,
40}
41
42impl ScrollFieldColors {
43    fn resolve(self, enabled: bool, theme: &MaterialTheme) -> (Hsla, Hsla, Hsla) {
44        let container = color(theme.colors.color(ColorRole::SurfaceContainerLowest));
45        let selected = color(theme.colors.color(ColorRole::OnSurface));
46        if enabled {
47            (
48                self.container.unwrap_or(container),
49                self.content
50                    .unwrap_or_else(|| color(theme.colors.color(ColorRole::Outline))),
51                self.selected_content.unwrap_or(selected),
52            )
53        } else {
54            (
55                self.disabled_container
56                    .unwrap_or_else(|| container.opacity(0.38)),
57                self.disabled_content
58                    .unwrap_or_else(|| selected.opacity(0.38)),
59                self.disabled_selected_content
60                    .unwrap_or_else(|| selected.opacity(0.38)),
61            )
62        }
63    }
64}
65
66type ItemContent = Box<dyn Fn(usize, bool, bool) -> AnyElement>;
67type ValueDescription = Box<dyn Fn(usize) -> SharedString>;
68
69/// A vertically scrolling selection wheel with a single accessible focus stop.
70/// The field fills its parent's width and displays three rows at a time.
71#[derive(IntoElement)]
72pub struct ScrollField {
73    id: ElementId,
74    name: SharedString,
75    state: Entity<ScrollFieldState>,
76    disabled: bool,
77    colors: ScrollFieldColors,
78    time_field_shape: Option<CornerShape>,
79    numeric_offset: usize,
80    source: Option<Entity<InteractionSource>>,
81    item: Option<ItemContent>,
82    description: Option<ValueDescription>,
83}
84
85impl ScrollField {
86    /// Creates a scroll field with an element `id`, accessible `name`, and caller-owned `state`.
87    pub fn new(
88        id: impl Into<ElementId>,
89        name: impl Into<SharedString>,
90        state: &Entity<ScrollFieldState>,
91    ) -> Self {
92        Self {
93            id: id.into(),
94            name: name.into(),
95            state: state.clone(),
96            disabled: false,
97            colors: ScrollFieldColors::default(),
98            time_field_shape: None,
99            numeric_offset: 0,
100            source: None,
101            item: None,
102            description: None,
103        }
104    }
105
106    /// Disables pointer, scroll, keyboard, and accessibility interaction when `true`.
107    pub fn disabled(mut self, disabled: bool) -> Self {
108        self.disabled = disabled;
109        self
110    }
111
112    /// Overrides the scroll field's local colors.
113    pub fn colors(mut self, colors: ScrollFieldColors) -> Self {
114        self.colors = colors;
115        self
116    }
117
118    pub(in crate::date_time) fn time_field(
119        mut self,
120        shape: Option<CornerShape>,
121        numeric_offset: usize,
122    ) -> Self {
123        self.time_field_shape = shape;
124        self.numeric_offset = numeric_offset;
125        self
126    }
127
128    /// Connects an [`InteractionSource`] to observe hover, press, drag, and focus states.
129    pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
130        self.source = Some(source.clone());
131        self
132    }
133
134    /// Renders a decorative row with its index, selected state and enabled state.
135    pub fn item_content<E: IntoElement>(
136        mut self,
137        item: impl Fn(usize, bool, bool) -> E + 'static,
138    ) -> Self {
139        self.item = Some(Box::new(move |index, selected, enabled| {
140            item(index, selected, enabled).into_any_element()
141        }));
142        self
143    }
144
145    /// Describes an option to assistive technology. By default, uses its index.
146    pub fn value_description<S: Into<SharedString>>(
147        mut self,
148        description: impl Fn(usize) -> S + 'static,
149    ) -> Self {
150        self.description = Some(Box::new(move |index| description(index).into()));
151        self
152    }
153}
154
155impl RenderOnce for ScrollField {
156    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
157        let theme = current_material_theme(window, cx);
158        let corner = self
159            .time_field_shape
160            .unwrap_or_else(|| CornerRole::Large.shape());
161        let direction = theme.layout.direction;
162        let [tl, tr, br, bl] = corner.radii(HEIGHT, HEIGHT, direction).map(px);
163        let ring = color(theme.colors.color(ColorRole::Secondary));
164        let motion_spec =
165            theme
166                .motion
167                .spec(MotionKind::Spatial, MotionSpeed::Fast, cx.reduce_motion());
168        if self.disabled && self.state.read(cx).has_pending_interaction() {
169            self.state
170                .update(cx, |state, cx| state.scroll_to_option(state.target, cx));
171        }
172        let motion = self.state.read(cx).motion;
173        if let Some(motion) = motion {
174            let key = (self.id.clone(), "scroll-position");
175            if motion.restart {
176                animate(key.clone(), motion.start, MotionSpec::Instant, window, cx);
177            }
178            let offset = animate(key, 0., motion_spec, window, cx);
179            self.state.update(cx, |state, cx| state.sample(offset, cx));
180        }
181        let state = self.state.read(cx);
182        let count = state.item_count;
183        let position = state.position;
184        let target = state.target;
185        let focus = state.focus.clone();
186        let enabled = !self.disabled && count > 0;
187        let (container, content, selected_content) = self.colors.resolve(enabled, &theme);
188        let feedback = window
189            .use_keyed_state((self.id.clone(), "scroll-field-feedback"), cx, |_, _| {
190                Rc::new(Cell::new(InteractionState::default()))
191            })
192            .read(cx)
193            .clone();
194        let input = Input {
195            tracker: self
196                .source
197                .as_ref()
198                .map(|source| InteractionSource::track(source, &self.id, window, cx)),
199            state: self.state,
200            feedback,
201            numeric_offset: self.numeric_offset,
202        };
203        let mut interaction = input.feedback.get();
204        if !enabled || !window.is_window_active() {
205            interaction = InteractionState::default();
206        }
207        interaction.disabled = !enabled;
208        input.update_feedback(interaction, window, cx);
209        let feedback = InteractionFeedback::new(input.feedback.get(), selected_content, ring);
210        let label = (count > 0).then(|| {
211            self.description
212                .as_ref()
213                .map_or_else(|| target.to_string().into(), |describe| describe(target))
214        });
215        let rows = (-2_isize..=2)
216            .filter(|row| count > 1 || (count == 1 && *row == 0))
217            .map(|row| {
218                let index = wrap(position.index, row, count);
219                let selected = row == 0;
220                let visual = self.item.as_ref().map_or_else(
221                    || {
222                        Text::new(crate::date_time::format_two_digits(index))
223                            .role(if selected {
224                                TypeRole::DisplayLarge
225                            } else {
226                                TypeRole::DisplayMedium
227                            })
228                            .emphasized(selected)
229                            .into_any_element()
230                    },
231                    |item| item(index, selected, enabled),
232                );
233                let input = input.state.clone();
234                div()
235                    .absolute()
236                    .top(px((1. + row as f32 - position.fraction) * ROW_HEIGHT))
237                    .h(px(ROW_HEIGHT))
238                    .w_full()
239                    .flex()
240                    .items_center()
241                    .justify_center()
242                    .text_color(if selected { selected_content } else { content })
243                    .id(("scroll-field-row", (row + 2) as usize))
244                    .role(Role::Group)
245                    .a11y_synthetic_children(|tree| tree.parent_node().set_hidden())
246                    .when(enabled, |row_element| {
247                        row_element.on_click(move |_, window, cx| {
248                            input.update(cx, |state, cx| {
249                                state.focus.focus(window, cx);
250                                state.select_row(row, cx);
251                            });
252                        })
253                    })
254                    .child(visual)
255                    .test_support()
256            });
257        let field = div()
258            .id(self.id)
259            .relative()
260            .w_full()
261            .min_w_0()
262            .h(px(HEIGHT))
263            .flex_none()
264            .overflow_hidden()
265            .rounded_tl(tl)
266            .rounded_tr(tr)
267            .rounded_br(br)
268            .rounded_bl(bl)
269            .bg(container)
270            .role(Role::Slider)
271            .aria_label(self.name)
272            .aria_orientation(Orientation::Vertical)
273            .when_some(label, |field, label| {
274                field
275                    .aria_value(label)
276                    .aria_numeric_value(target as f64 + self.numeric_offset as f64)
277                    .aria_min_numeric_value(self.numeric_offset as f64)
278                    .aria_max_numeric_value((count - 1) as f64 + self.numeric_offset as f64)
279                    .aria_numeric_value_step(1.)
280            })
281            .when(!enabled, |field| {
282                field.a11y_synthetic_children(|tree| tree.parent_node().set_disabled())
283            })
284            .children(rows)
285            .child(
286                canvas(
287                    |_, _, _| (),
288                    move |bounds, _, window, cx| {
289                        if let Some(shape) = Shape::rounded(bounds, corner, direction) {
290                            feedback.paint(
291                                &shape,
292                                None,
293                                cx.background_executor().now(),
294                                cx.reduce_motion(),
295                                window,
296                            );
297                        }
298                    },
299                )
300                .absolute()
301                .inset_0(),
302            );
303        field
304            .when(enabled, |field| input.bind(field))
305            .test_support()
306            .when(enabled || focus.is_focused(window), |field| {
307                field.track_focus(&focus.tab_stop(enabled))
308            })
309    }
310}
311
312#[derive(Clone)]
313struct Input {
314    state: Entity<ScrollFieldState>,
315    feedback: Rc<Cell<InteractionState>>,
316    numeric_offset: usize,
317    tracker: Option<InteractionTracker>,
318}
319
320impl Input {
321    fn update_feedback(&self, mut feedback: InteractionState, window: &mut Window, cx: &mut App) {
322        let state = self.state.read(cx);
323        feedback.focus_visible = !feedback.disabled
324            && state.focus.is_focused(window)
325            && window.last_input_was_keyboard();
326        feedback.dragged = !feedback.disabled && state.gesture_start.is_some();
327        if self.feedback.replace(feedback) != feedback {
328            window.refresh();
329        }
330        if let Some(tracker) = &self.tracker {
331            tracker.record(feedback, cx);
332        }
333    }
334
335    fn bind(&self, field: Stateful<Div>) -> Stateful<Div> {
336        let scroll = self.clone();
337        let hover = self.clone();
338        let press = self.clone();
339        let release = self.clone();
340        let release_out = self.clone();
341        let keyboard = self.state.clone();
342        let increment = self.state.clone();
343        let decrement = self.state.clone();
344        let set_value = self.state.clone();
345        let numeric_offset = self.numeric_offset as f64;
346        field
347            .on_scroll(move |event, window, cx| {
348                if scroll
349                    .state
350                    .update(cx, |state, cx| state.scroll(event, window, cx))
351                {
352                    scroll.update_feedback(scroll.feedback.get(), window, cx);
353                    cx.stop_propagation();
354                }
355            })
356            .on_hover(move |hovered, window, cx| {
357                let mut feedback = hover.feedback.get();
358                feedback.hovered = *hovered;
359                hover.update_feedback(feedback, window, cx);
360            })
361            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
362                press.pointer(true, window, cx)
363            })
364            .on_mouse_up(MouseButton::Left, move |_, window, cx| {
365                release.pointer(false, window, cx)
366            })
367            .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
368                release_out.pointer(false, window, cx)
369            })
370            .on_key_down(move |event, _, cx| {
371                if event.keystroke.modifiers.modified() {
372                    return;
373                }
374                match event.keystroke.key.as_str() {
375                    "up" => keyboard.update(cx, |state, cx| state.step(-1, cx)),
376                    "down" => keyboard.update(cx, |state, cx| state.step(1, cx)),
377                    "home" => keyboard.update(cx, |state, cx| {
378                        state.animate_to(0, ScrollOrigin::Interaction, cx)
379                    }),
380                    "end" => keyboard.update(cx, |state, cx| {
381                        state.animate_to(
382                            state.item_count.saturating_sub(1),
383                            ScrollOrigin::Interaction,
384                            cx,
385                        )
386                    }),
387                    _ => return,
388                }
389                cx.stop_propagation();
390            })
391            .on_a11y_action(AccessibleAction::Increment, move |_, _, cx| {
392                increment.update(cx, |state, cx| state.step(1, cx))
393            })
394            .on_a11y_action(AccessibleAction::Decrement, move |_, _, cx| {
395                decrement.update(cx, |state, cx| state.step(-1, cx))
396            })
397            .on_a11y_action(AccessibleAction::SetValue, move |data, _, cx| {
398                let value = match data {
399                    Some(ActionData::NumericValue(value)) => Some(*value),
400                    Some(ActionData::Value(value)) => value.trim().parse::<f64>().ok(),
401                    _ => None,
402                };
403                if let Some(value) = value.filter(|value| value.is_finite()) {
404                    set_value.update(cx, |state, cx| {
405                        state.animate_to(
406                            (value - numeric_offset).round() as usize,
407                            ScrollOrigin::Interaction,
408                            cx,
409                        )
410                    });
411                }
412            })
413    }
414
415    fn pointer(&self, pressed: bool, window: &mut Window, cx: &mut App) {
416        let mut feedback = self.feedback.get();
417        feedback.pressed = pressed;
418        self.update_feedback(feedback, window, cx);
419    }
420}