Skip to main content

gpui_material_components/
settings_tiles.rs

1#[cfg(all(feature = "surfaces", feature = "selection"))]
2mod switch_tile {
3    use std::rc::Rc;
4
5    use gpui::{
6        AnyElement, App, ElementId, Entity, FocusHandle, IntoElement, RenderOnce, Role,
7        SharedString, Window,
8    };
9    use gpui_material_foundation::InteractionSource;
10    use gpui_material_theme::CornerRole;
11
12    use crate::{
13        ListItem, ListItemColors, ListItemShapes, ListVariant, Switch, SwitchColors, action::Change,
14    };
15
16    /// Settings convenience row wrapping [`ListItem`] with a synchronized decorative [`Switch`].
17    ///
18    /// Clicking anywhere on the row or pressing Enter or Space toggles once with a single focus
19    /// stop and `Role::Switch` semantics.
20    #[derive(IntoElement)]
21    pub struct SwitchTile {
22        id: ElementId,
23        label: SharedString,
24        checked: bool,
25        supporting: Option<SharedString>,
26        overline: Option<SharedString>,
27        leading: Option<AnyElement>,
28        disabled: bool,
29        variant: ListVariant,
30        colors: ListItemColors,
31        switch_colors: SwitchColors,
32        focus: Option<FocusHandle>,
33        source: Option<Entity<InteractionSource>>,
34        on_change: Option<Change>,
35    }
36
37    impl SwitchTile {
38        /// Creates a switch settings row with an element ID, headline label, and controlled checked state.
39        pub fn new(
40            id: impl Into<ElementId>,
41            label: impl Into<SharedString>,
42            checked: bool,
43        ) -> Self {
44            Self {
45                id: id.into(),
46                label: label.into(),
47                checked,
48                supporting: None,
49                overline: None,
50                leading: None,
51                disabled: false,
52                variant: ListVariant::default(),
53                colors: ListItemColors::default(),
54                switch_colors: SwitchColors::default(),
55                focus: None,
56                source: None,
57                on_change: None,
58            }
59        }
60
61        /// Sets secondary supporting text displayed below the headline.
62        pub fn supporting(mut self, text: impl Into<SharedString>) -> Self {
63            self.supporting = Some(text.into());
64            self
65        }
66
67        /// Sets overline text displayed above the headline.
68        pub fn overline(mut self, text: impl Into<SharedString>) -> Self {
69            self.overline = Some(text.into());
70            self
71        }
72
73        /// Sets an optional leading icon or graphic.
74        pub fn leading(mut self, leading: impl IntoElement) -> Self {
75            self.leading = Some(leading.into_any_element());
76            self
77        }
78
79        /// Disables row interaction and dims the switch when `true`.
80        pub fn disabled(mut self, disabled: bool) -> Self {
81            self.disabled = disabled;
82            self
83        }
84
85        /// Sets standalone row styling (`Standard` or `Segmented`).
86        pub fn variant(mut self, variant: ListVariant) -> Self {
87            self.variant = variant;
88            self
89        }
90
91        /// Overrides container and slot colors on the underlying [`ListItem`].
92        pub fn colors(mut self, colors: ListItemColors) -> Self {
93            self.colors = colors;
94            self
95        }
96
97        /// Overrides track, thumb, border, and content colors on the decorative [`Switch`].
98        pub fn switch_colors(mut self, colors: SwitchColors) -> Self {
99            self.switch_colors = colors;
100            self
101        }
102
103        /// Uses a caller-owned focus handle for this tile.
104        pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
105            self.focus = Some(focus.clone());
106            self
107        }
108
109        /// Reports hover, focus, press, and disabled states through a caller-owned source.
110        pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
111            self.source = Some(source.clone());
112            self
113        }
114
115        /// Invoked with the requested next checked state when the tile is toggled.
116        pub fn on_change(
117            mut self,
118            handler: impl Fn(bool, &mut Window, &mut App) + 'static,
119        ) -> Self {
120            self.on_change = Some(Rc::new(handler));
121            self
122        }
123
124        pub(super) fn into_list_item(self) -> ListItem {
125            let switch = Switch::new(
126                (self.id.clone(), "switch"),
127                self.label.clone(),
128                self.checked,
129            )
130            .disabled(self.disabled)
131            .colors(self.switch_colors)
132            .decorative(true);
133
134            let mut item = ListItem::new(self.id, self.label)
135                .checked(self.checked)
136                .checked_role(Role::Switch)
137                .checked_selects_row(false)
138                .disabled(self.disabled)
139                .colors(self.colors)
140                .trailing(switch);
141
142            if let Some(supporting) = self.supporting {
143                item = item.supporting_text(supporting);
144            }
145            if let Some(overline) = self.overline {
146                item = item.overline(overline);
147            }
148            if let Some(leading) = self.leading {
149                item = item.leading(leading);
150            }
151            if let Some(focus) = self.focus {
152                item = item.track_focus(&focus, true);
153            }
154            if let Some(source) = self.source {
155                item = item.interaction_source(&source);
156            }
157            if let Some(on_change) = self.on_change {
158                item = item.on_checked_change(move |next, window, cx| on_change(next, window, cx));
159            }
160            item
161        }
162    }
163
164    impl RenderOnce for SwitchTile {
165        fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
166            let segmented = self.variant == ListVariant::Segmented;
167            let mut item = self.into_list_item();
168            if segmented {
169                item = item.shapes(ListItemShapes {
170                    resting: Some(CornerRole::Large.shape()),
171                    selected: Some(CornerRole::Large.shape()),
172                    ..Default::default()
173                });
174            }
175            item
176        }
177    }
178}
179
180#[cfg(all(feature = "surfaces", feature = "selection"))]
181pub use switch_tile::SwitchTile;
182
183#[cfg(all(feature = "surfaces", feature = "selection"))]
184mod checkbox_tile {
185    use std::rc::Rc;
186
187    use gpui::{
188        AnyElement, App, ElementId, Entity, FocusHandle, IntoElement, RenderOnce, Role,
189        SharedString, Window, accesskit::Toggled,
190    };
191    use gpui_material_foundation::InteractionSource;
192    use gpui_material_theme::CornerRole;
193
194    use crate::{
195        Checkbox, CheckboxColors, CheckboxState, ListItem, ListItemColors, ListItemShapes,
196        ListVariant,
197    };
198
199    type CheckboxTileChange = Rc<dyn Fn(CheckboxState, &mut Window, &mut App)>;
200
201    /// Settings convenience row wrapping [`ListItem`] with a synchronized decorative [`Checkbox`].
202    ///
203    /// Clicking anywhere on the row or pressing Enter or Space requests the next [`CheckboxState`]
204    /// with a single focus stop and `Role::CheckBox` semantics.
205    #[derive(IntoElement)]
206    pub struct CheckboxTile {
207        id: ElementId,
208        label: SharedString,
209        state: CheckboxState,
210        supporting: Option<SharedString>,
211        overline: Option<SharedString>,
212        leading: Option<AnyElement>,
213        trailing: Option<AnyElement>,
214        trailing_checkbox: bool,
215        error: bool,
216        disabled: bool,
217        variant: ListVariant,
218        colors: ListItemColors,
219        checkbox_colors: CheckboxColors,
220        focus: Option<FocusHandle>,
221        source: Option<Entity<InteractionSource>>,
222        on_change: Option<CheckboxTileChange>,
223    }
224
225    impl CheckboxTile {
226        /// Creates a checkbox settings row with an element ID, headline label, and controlled [`CheckboxState`].
227        pub fn new(
228            id: impl Into<ElementId>,
229            label: impl Into<SharedString>,
230            state: CheckboxState,
231        ) -> Self {
232            Self {
233                id: id.into(),
234                label: label.into(),
235                state,
236                supporting: None,
237                overline: None,
238                leading: None,
239                trailing: None,
240                trailing_checkbox: true,
241                error: false,
242                disabled: false,
243                variant: ListVariant::default(),
244                colors: ListItemColors::default(),
245                checkbox_colors: CheckboxColors::default(),
246                focus: None,
247                source: None,
248                on_change: None,
249            }
250        }
251
252        /// Convenience constructor for a two-state boolean checkbox tile.
253        pub fn bool(
254            id: impl Into<ElementId>,
255            label: impl Into<SharedString>,
256            checked: bool,
257        ) -> Self {
258            Self::new(
259                id,
260                label,
261                if checked {
262                    CheckboxState::Checked
263                } else {
264                    CheckboxState::Unchecked
265                },
266            )
267        }
268
269        /// Sets secondary supporting text displayed below the headline.
270        pub fn supporting(mut self, text: impl Into<SharedString>) -> Self {
271            self.supporting = Some(text.into());
272            self
273        }
274
275        /// Sets overline text displayed above the headline.
276        pub fn overline(mut self, text: impl Into<SharedString>) -> Self {
277            self.overline = Some(text.into());
278            self
279        }
280
281        /// Sets an optional leading icon or graphic when the checkbox is in the trailing slot.
282        pub fn leading(mut self, leading: impl IntoElement) -> Self {
283            self.leading = Some(leading.into_any_element());
284            self
285        }
286
287        /// Trailing decorative content used when `.trailing_checkbox(false)` places the checkbox
288        /// in the leading slot.
289        pub fn trailing(mut self, trailing: impl IntoElement) -> Self {
290            self.trailing = Some(trailing.into_any_element());
291            self
292        }
293
294        /// Places the decorative checkbox in the trailing slot (`true`, default) or leading slot (`false`).
295        pub fn trailing_checkbox(mut self, trailing: bool) -> Self {
296            self.trailing_checkbox = trailing;
297            self
298        }
299
300        /// Marks the checkbox tile as invalid, applying error styling and `aria-invalid` semantics.
301        pub fn error(mut self, error: bool) -> Self {
302            self.error = error;
303            self
304        }
305
306        /// Disables row interaction and dims the checkbox when `true`.
307        pub fn disabled(mut self, disabled: bool) -> Self {
308            self.disabled = disabled;
309            self
310        }
311
312        /// Sets standalone row styling (`Standard` or `Segmented`).
313        pub fn variant(mut self, variant: ListVariant) -> Self {
314            self.variant = variant;
315            self
316        }
317
318        /// Overrides container and slot colors on the underlying [`ListItem`].
319        pub fn colors(mut self, colors: ListItemColors) -> Self {
320            self.colors = colors;
321            self
322        }
323
324        /// Overrides checkmark, box, and border colors on the decorative [`Checkbox`].
325        pub fn checkbox_colors(mut self, colors: CheckboxColors) -> Self {
326            self.checkbox_colors = colors;
327            self
328        }
329
330        /// Uses a caller-owned focus handle for this tile.
331        pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
332            self.focus = Some(focus.clone());
333            self
334        }
335
336        /// Reports hover, focus, press, and disabled states through a caller-owned source.
337        pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
338            self.source = Some(source.clone());
339            self
340        }
341
342        /// Invoked with the requested next [`CheckboxState`] when the tile is toggled.
343        pub fn on_change(
344            mut self,
345            handler: impl Fn(CheckboxState, &mut Window, &mut App) + 'static,
346        ) -> Self {
347            self.on_change = Some(Rc::new(handler));
348            self
349        }
350
351        pub(super) fn into_list_item(self) -> ListItem {
352            let checkbox = Checkbox::new(
353                (self.id.clone(), "checkbox"),
354                self.label.clone(),
355                self.state,
356            )
357            .error(self.error)
358            .disabled(self.disabled)
359            .colors(self.checkbox_colors)
360            .decorative(true);
361
362            let toggled = match self.state {
363                CheckboxState::Unchecked => Toggled::False,
364                CheckboxState::Checked => Toggled::True,
365                CheckboxState::Indeterminate => Toggled::Mixed,
366            };
367
368            let mut item = ListItem::new(self.id, self.label)
369                .checked_toggled(toggled)
370                .checked_role(Role::CheckBox)
371                .checked_selects_row(false)
372                .invalid(self.error)
373                .disabled(self.disabled)
374                .colors(self.colors);
375
376            if self.trailing_checkbox {
377                item = item.trailing(checkbox);
378                if let Some(leading) = self.leading {
379                    item = item.leading(leading);
380                }
381            } else {
382                item = item.leading(checkbox);
383                if let Some(trailing) = self.trailing {
384                    item = item.trailing(trailing);
385                }
386            }
387
388            if let Some(supporting) = self.supporting {
389                item = item.supporting_text(supporting);
390            }
391            if let Some(overline) = self.overline {
392                item = item.overline(overline);
393            }
394            if let Some(focus) = self.focus {
395                item = item.track_focus(&focus, true);
396            }
397            if let Some(source) = self.source {
398                item = item.interaction_source(&source);
399            }
400            if let Some(on_change) = self.on_change {
401                let next = if self.state == CheckboxState::Checked {
402                    CheckboxState::Unchecked
403                } else {
404                    CheckboxState::Checked
405                };
406                item = item.on_activate(move |window, cx| on_change(next, window, cx));
407            }
408            item
409        }
410    }
411
412    impl RenderOnce for CheckboxTile {
413        fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
414            let segmented = self.variant == ListVariant::Segmented;
415            let mut item = self.into_list_item();
416            if segmented {
417                item = item.shapes(ListItemShapes {
418                    resting: Some(CornerRole::Large.shape()),
419                    selected: Some(CornerRole::Large.shape()),
420                    ..Default::default()
421                });
422            }
423            item
424        }
425    }
426}
427
428#[cfg(all(feature = "surfaces", feature = "selection"))]
429pub use checkbox_tile::CheckboxTile;
430
431#[cfg(all(feature = "surfaces", feature = "selection"))]
432mod radio_tile {
433    use std::rc::Rc;
434
435    use gpui::{
436        AnyElement, App, ElementId, Entity, FocusHandle, IntoElement, RenderOnce, Role,
437        SharedString, Window, accesskit::Toggled,
438    };
439    use gpui_material_foundation::InteractionSource;
440    use gpui_material_theme::CornerRole;
441
442    use crate::{
443        ListItem, ListItemColors, ListItemShapes, ListVariant, Radio, RadioColors, action::Activate,
444    };
445
446    /// Settings convenience row wrapping [`ListItem`] with a synchronized decorative [`Radio`].
447    ///
448    /// Clicking anywhere on an unselected row or pressing Enter or Space invokes `.on_select`
449    /// with a single focus stop and `Role::RadioButton` semantics.
450    #[derive(IntoElement)]
451    pub struct RadioTile {
452        id: ElementId,
453        label: SharedString,
454        selected: bool,
455        supporting: Option<SharedString>,
456        overline: Option<SharedString>,
457        leading: Option<AnyElement>,
458        trailing: Option<AnyElement>,
459        trailing_radio: bool,
460        disabled: bool,
461        variant: ListVariant,
462        colors: ListItemColors,
463        radio_colors: RadioColors,
464        focus: Option<FocusHandle>,
465        source: Option<Entity<InteractionSource>>,
466        on_select: Option<Activate>,
467    }
468
469    impl RadioTile {
470        /// Creates a radio settings row with an element ID, headline label, and controlled selected state.
471        pub fn new(
472            id: impl Into<ElementId>,
473            label: impl Into<SharedString>,
474            selected: bool,
475        ) -> Self {
476            Self {
477                id: id.into(),
478                label: label.into(),
479                selected,
480                supporting: None,
481                overline: None,
482                leading: None,
483                trailing: None,
484                trailing_radio: true,
485                disabled: false,
486                variant: ListVariant::default(),
487                colors: ListItemColors::default(),
488                radio_colors: RadioColors::default(),
489                focus: None,
490                source: None,
491                on_select: None,
492            }
493        }
494
495        /// Sets secondary supporting text displayed below the headline.
496        pub fn supporting(mut self, text: impl Into<SharedString>) -> Self {
497            self.supporting = Some(text.into());
498            self
499        }
500
501        /// Sets overline text displayed above the headline.
502        pub fn overline(mut self, text: impl Into<SharedString>) -> Self {
503            self.overline = Some(text.into());
504            self
505        }
506
507        /// Sets an optional leading icon or graphic when the radio indicator is in the trailing slot.
508        pub fn leading(mut self, leading: impl IntoElement) -> Self {
509            self.leading = Some(leading.into_any_element());
510            self
511        }
512
513        /// Trailing decorative content used when `.trailing_radio(false)` places the radio
514        /// in the leading slot.
515        pub fn trailing(mut self, trailing: impl IntoElement) -> Self {
516            self.trailing = Some(trailing.into_any_element());
517            self
518        }
519
520        /// Places the decorative radio indicator in the trailing slot (`true`, default) or leading slot (`false`).
521        pub fn trailing_radio(mut self, trailing: bool) -> Self {
522            self.trailing_radio = trailing;
523            self
524        }
525
526        /// Disables row interaction and dims the radio indicator when `true`.
527        pub fn disabled(mut self, disabled: bool) -> Self {
528            self.disabled = disabled;
529            self
530        }
531
532        /// Sets standalone row styling (`Standard` or `Segmented`).
533        pub fn variant(mut self, variant: ListVariant) -> Self {
534            self.variant = variant;
535            self
536        }
537
538        /// Overrides container and slot colors on the underlying [`ListItem`].
539        pub fn colors(mut self, colors: ListItemColors) -> Self {
540            self.colors = colors;
541            self
542        }
543
544        /// Overrides indicator colors on the decorative [`Radio`].
545        pub fn radio_colors(mut self, colors: RadioColors) -> Self {
546            self.radio_colors = colors;
547            self
548        }
549
550        /// Uses a caller-owned focus handle for this tile.
551        pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
552            self.focus = Some(focus.clone());
553            self
554        }
555
556        /// Reports hover, focus, press, and disabled states through a caller-owned source.
557        pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
558            self.source = Some(source.clone());
559            self
560        }
561
562        /// Invoked when an unselected radio tile is activated.
563        pub fn on_select(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
564            self.on_select = Some(Rc::new(handler));
565            self
566        }
567
568        pub(super) fn into_list_item(self) -> ListItem {
569            let radio = Radio::new((self.id.clone(), "radio"), self.label.clone())
570                .selected(self.selected)
571                .disabled(self.disabled)
572                .colors(self.radio_colors)
573                .decorative(true);
574
575            let toggled = if self.selected {
576                Toggled::True
577            } else {
578                Toggled::False
579            };
580
581            let mut item = ListItem::new(self.id, self.label)
582                .checked_toggled(toggled)
583                .checked_role(Role::RadioButton)
584                .checked_selects_row(false)
585                .disabled(self.disabled)
586                .colors(self.colors);
587
588            if self.trailing_radio {
589                item = item.trailing(radio);
590                if let Some(leading) = self.leading {
591                    item = item.leading(leading);
592                }
593            } else {
594                item = item.leading(radio);
595                if let Some(trailing) = self.trailing {
596                    item = item.trailing(trailing);
597                }
598            }
599
600            if let Some(supporting) = self.supporting {
601                item = item.supporting_text(supporting);
602            }
603            if let Some(overline) = self.overline {
604                item = item.overline(overline);
605            }
606            if let Some(focus) = self.focus {
607                item = item.track_focus(&focus, true);
608            }
609            if let Some(source) = self.source {
610                item = item.interaction_source(&source);
611            }
612            if let Some(on_select) = self.on_select {
613                let already_selected = self.selected;
614                item = item.on_activate(move |window, cx| {
615                    if !already_selected {
616                        on_select(window, cx);
617                    }
618                });
619            }
620            item
621        }
622    }
623
624    impl RenderOnce for RadioTile {
625        fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
626            let segmented = self.variant == ListVariant::Segmented;
627            let mut item = self.into_list_item();
628            if segmented {
629                item = item.shapes(ListItemShapes {
630                    resting: Some(CornerRole::Large.shape()),
631                    selected: Some(CornerRole::Large.shape()),
632                    ..Default::default()
633                });
634            }
635            item
636        }
637    }
638}
639
640#[cfg(all(feature = "surfaces", feature = "selection"))]
641pub use radio_tile::RadioTile;
642
643#[cfg(all(feature = "surfaces", feature = "selection"))]
644mod slider_tile {
645    use std::rc::Rc;
646
647    use gpui::{
648        AnyElement, App, ElementId, Entity, FocusHandle, IntoElement, ParentElement, RenderOnce,
649        SharedString, Styled, Window, div,
650    };
651    use gpui_material_foundation::{InteractionSource, color, current_material_theme};
652    use gpui_material_theme::{ColorRole, CornerRole, TypeRole};
653
654    use crate::{
655        ListItem, ListItemColors, ListItemShapes, ListVariant, RangeThumb, Slider, SliderState,
656        SliderValue, Text,
657    };
658
659    type FormatValue = Rc<dyn Fn(f32) -> SharedString>;
660    type SliderConfig = Box<dyn FnOnce(Slider) -> Slider>;
661
662    pub(super) fn format_slider_scalar(value: f32) -> SharedString {
663        if !value.is_finite() {
664            return "0".into();
665        }
666        let rounded = value.round();
667        if (value - rounded).abs() < 1e-4 {
668            format!("{}", rounded as i64).into()
669        } else {
670            format!("{value:.2}").into()
671        }
672    }
673
674    pub(super) fn format_slider_value(
675        value: SliderValue,
676        formatter: Option<&FormatValue>,
677    ) -> SharedString {
678        let format_one = |v: f32| match formatter {
679            Some(f) => f(v),
680            None => format_slider_scalar(v),
681        };
682        if value.is_range() {
683            format!(
684                "{} – {}",
685                format_one(value.start()),
686                format_one(value.end())
687            )
688            .into()
689        } else {
690            format_one(value.end())
691        }
692    }
693
694    /// Settings convenience row combining a [`ListItem`] header, live formatted value display,
695    /// and an embedded [`Slider`] bound to a caller-owned [`SliderState`].
696    #[derive(IntoElement)]
697    pub struct SliderTile {
698        id: ElementId,
699        label: SharedString,
700        state: Entity<SliderState>,
701        supporting: Option<SharedString>,
702        overline: Option<SharedString>,
703        leading: Option<AnyElement>,
704        disabled: bool,
705        variant: ListVariant,
706        colors: ListItemColors,
707        focus: Option<FocusHandle>,
708        source: Option<Entity<InteractionSource>>,
709        format_value: Option<FormatValue>,
710        configure_slider: Option<SliderConfig>,
711    }
712
713    impl SliderTile {
714        /// Creates a slider settings row with an element ID, headline label, and caller-owned [`SliderState`].
715        pub fn new(
716            id: impl Into<ElementId>,
717            label: impl Into<SharedString>,
718            state: &Entity<SliderState>,
719        ) -> Self {
720            Self {
721                id: id.into(),
722                label: label.into(),
723                state: state.clone(),
724                supporting: None,
725                overline: None,
726                leading: None,
727                disabled: false,
728                variant: ListVariant::default(),
729                colors: ListItemColors::default(),
730                focus: None,
731                source: None,
732                format_value: None,
733                configure_slider: None,
734            }
735        }
736
737        /// Sets secondary supporting text displayed below the headline.
738        pub fn supporting(mut self, text: impl Into<SharedString>) -> Self {
739            self.supporting = Some(text.into());
740            self
741        }
742
743        /// Sets overline text displayed above the headline.
744        pub fn overline(mut self, text: impl Into<SharedString>) -> Self {
745            self.overline = Some(text.into());
746            self
747        }
748
749        /// Sets an optional leading icon or graphic.
750        pub fn leading(mut self, leading: impl IntoElement) -> Self {
751            self.leading = Some(leading.into_any_element());
752            self
753        }
754
755        /// Disables the embedded slider and dims the tile when `true`.
756        pub fn disabled(mut self, disabled: bool) -> Self {
757            self.disabled = disabled;
758            self
759        }
760
761        /// Sets standalone row styling (`Standard` or `Segmented`).
762        pub fn variant(mut self, variant: ListVariant) -> Self {
763            self.variant = variant;
764            self
765        }
766
767        /// Overrides container and slot colors on the underlying [`ListItem`].
768        pub fn colors(mut self, colors: ListItemColors) -> Self {
769            self.colors = colors;
770            self
771        }
772
773        /// Binds a caller-owned focus handle to the embedded slider's primary handle.
774        pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
775            self.focus = Some(focus.clone());
776            self
777        }
778
779        /// Observes the embedded slider's primary handle under the tile's ID (and `(id, "start")` for range sliders).
780        pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
781            self.source = Some(source.clone());
782            self
783        }
784
785        /// Formats the live numeric value displayed on the trailing side of the header row.
786        pub fn format_value(mut self, formatter: impl Fn(f32) -> SharedString + 'static) -> Self {
787            self.format_value = Some(Rc::new(formatter));
788            self
789        }
790
791        /// Customizes the embedded [`Slider`] (colors, tick intervals, size, value indicator, etc.).
792        pub fn slider(mut self, configure: impl FnOnce(Slider) -> Slider + 'static) -> Self {
793            self.configure_slider = Some(Box::new(configure));
794            self
795        }
796
797        pub(super) fn into_list_item(self, window: &Window, cx: &App) -> ListItem {
798            let theme = current_material_theme(window, cx);
799            let value_color = if self.disabled {
800                color(theme.colors.color(ColorRole::OnSurface)).opacity(0.38)
801            } else {
802                color(theme.colors.color(ColorRole::OnSurfaceVariant))
803            };
804            let current = self.state.read(cx).value();
805            let value_text = format_slider_value(current, self.format_value.as_ref());
806
807            let mut slider =
808                Slider::new((self.id.clone(), "slider"), self.label.clone(), &self.state)
809                    .disabled(self.disabled);
810            if let Some(focus) = self.focus {
811                slider = slider.track_focus(RangeThumb::End, &focus);
812            }
813            if let Some(source) = self.source {
814                slider =
815                    slider.interaction_source_with_id(RangeThumb::End, self.id.clone(), &source);
816                if current.is_range() {
817                    slider = slider.interaction_source_with_id(
818                        RangeThumb::Start,
819                        (self.id.clone(), "start").into(),
820                        &source,
821                    );
822                }
823            }
824            if let Some(formatter) = self.format_value {
825                slider = slider.format_value(move |value| formatter(value));
826            }
827            if let Some(configure) = self.configure_slider {
828                slider = configure(slider);
829            }
830
831            let trailing = div().text_color(value_color).child(
832                Text::new(value_text)
833                    .id((self.id.clone(), "slider-value"))
834                    .role(TypeRole::BodyMedium),
835            );
836
837            let mut item = ListItem::new(self.id, self.label)
838                .disabled(self.disabled)
839                .colors(self.colors)
840                .trailing(trailing)
841                .footer(slider);
842
843            if let Some(supporting) = self.supporting {
844                item = item.supporting_text(supporting);
845            }
846            if let Some(overline) = self.overline {
847                item = item.overline(overline);
848            }
849            if let Some(leading) = self.leading {
850                item = item.leading(leading);
851            }
852            item
853        }
854    }
855
856    impl RenderOnce for SliderTile {
857        fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
858            let segmented = self.variant == ListVariant::Segmented;
859            let mut item = self.into_list_item(window, cx);
860            if segmented {
861                item = item.shapes(ListItemShapes {
862                    resting: Some(CornerRole::Large.shape()),
863                    selected: Some(CornerRole::Large.shape()),
864                    ..Default::default()
865                });
866            }
867            item
868        }
869    }
870}
871
872#[cfg(all(feature = "surfaces", feature = "selection"))]
873pub use slider_tile::SliderTile;
874
875#[cfg(all(feature = "surfaces", feature = "feedback"))]
876mod choice_tile {
877    use std::rc::Rc;
878
879    use gpui::{
880        Anchor, AnyElement, App, ElementId, Entity, FocusHandle, IntoElement, ParentElement,
881        RenderOnce, SharedString, Styled, Window, div, prelude::FluentBuilder, px,
882    };
883    use gpui_material_foundation::{InteractionSource, color, current_material_theme};
884    use gpui_material_theme::{ColorRole, CornerRole, CornerShape, Direction, TypeRole};
885
886    use crate::{
887        DialogState, Icon, IconName, ListItem, ListItemColors, ListItemShapes, ListVariant, Menu,
888        MenuItem, Text,
889    };
890
891    type LeadingFactory = Rc<dyn Fn() -> AnyElement>;
892    type SelectChoice = Rc<dyn Fn(SharedString, &mut Window, &mut App)>;
893
894    /// One selectable option in a [`ChoiceTile`] anchored menu.
895    pub struct ChoiceOption {
896        id: SharedString,
897        label: SharedString,
898        supporting: Option<SharedString>,
899        leading: Option<LeadingFactory>,
900        disabled: bool,
901    }
902
903    impl ChoiceOption {
904        /// Creates a selectable choice option with a stable identifier and visible label.
905        pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
906            Self {
907                id: id.into(),
908                label: label.into(),
909                supporting: None,
910                leading: None,
911                disabled: false,
912            }
913        }
914
915        /// Sets optional supporting text shown below the option label in the popup menu.
916        pub fn supporting(mut self, text: impl Into<SharedString>) -> Self {
917            self.supporting = Some(text.into());
918            self
919        }
920
921        /// Supplies a repeatable leading icon or graphic for the option row in the popup menu.
922        pub fn leading<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
923            self.leading = Some(Rc::new(move || build().into_any_element()));
924            self
925        }
926
927        /// Disables selecting this option in the popup menu when `true`.
928        pub fn disabled(mut self, disabled: bool) -> Self {
929            self.disabled = disabled;
930            self
931        }
932    }
933
934    /// Settings convenience row combining [`ListItem`] with an anchored Material [`Menu`] of
935    /// [`ChoiceOption`]s.
936    #[derive(IntoElement)]
937    pub struct ChoiceTile {
938        id: ElementId,
939        label: SharedString,
940        options: Vec<ChoiceOption>,
941        selected: SharedString,
942        supporting: Option<SharedString>,
943        overline: Option<SharedString>,
944        leading: Option<AnyElement>,
945        placeholder: Option<SharedString>,
946        disabled: bool,
947        variant: ListVariant,
948        colors: ListItemColors,
949        focus: Option<FocusHandle>,
950        source: Option<Entity<InteractionSource>>,
951        menu_state: Option<Entity<DialogState>>,
952        on_select: Option<SelectChoice>,
953    }
954
955    impl ChoiceTile {
956        /// Creates a choice settings row with an element ID, headline label, available options, and currently selected option ID.
957        pub fn new(
958            id: impl Into<ElementId>,
959            label: impl Into<SharedString>,
960            options: impl IntoIterator<Item = ChoiceOption>,
961            selected: impl Into<SharedString>,
962        ) -> Self {
963            Self {
964                id: id.into(),
965                label: label.into(),
966                options: options.into_iter().collect(),
967                selected: selected.into(),
968                supporting: None,
969                overline: None,
970                leading: None,
971                placeholder: None,
972                disabled: false,
973                variant: ListVariant::default(),
974                colors: ListItemColors::default(),
975                focus: None,
976                source: None,
977                menu_state: None,
978                on_select: None,
979            }
980        }
981
982        /// Sets secondary supporting text displayed below the headline.
983        pub fn supporting(mut self, text: impl Into<SharedString>) -> Self {
984            self.supporting = Some(text.into());
985            self
986        }
987
988        /// Sets overline text displayed above the headline.
989        pub fn overline(mut self, text: impl Into<SharedString>) -> Self {
990            self.overline = Some(text.into());
991            self
992        }
993
994        /// Sets an optional leading icon or graphic.
995        pub fn leading(mut self, leading: impl IntoElement) -> Self {
996            self.leading = Some(leading.into_any_element());
997            self
998        }
999
1000        /// Sets fallback text shown on the trailing side when `selected` matches no option.
1001        pub fn placeholder(mut self, text: impl Into<SharedString>) -> Self {
1002            self.placeholder = Some(text.into());
1003            self
1004        }
1005
1006        /// Disables opening the menu and dims the tile when `true`.
1007        pub fn disabled(mut self, disabled: bool) -> Self {
1008            self.disabled = disabled;
1009            self
1010        }
1011
1012        /// Sets standalone row styling (`Standard` or `Segmented`).
1013        pub fn variant(mut self, variant: ListVariant) -> Self {
1014            self.variant = variant;
1015            self
1016        }
1017
1018        /// Overrides container and slot colors on the underlying [`ListItem`].
1019        pub fn colors(mut self, colors: ListItemColors) -> Self {
1020            self.colors = colors;
1021            self
1022        }
1023
1024        /// Uses a caller-owned focus handle for this tile.
1025        pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
1026            self.focus = Some(focus.clone());
1027            self
1028        }
1029
1030        /// Reports hover, focus, press, and disabled states through a caller-owned source.
1031        pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
1032            self.source = Some(source.clone());
1033            self
1034        }
1035
1036        /// Supplies an external `Entity<DialogState>` to observe or control popup menu visibility.
1037        pub fn menu_state(mut self, state: &Entity<DialogState>) -> Self {
1038            self.menu_state = Some(state.clone());
1039            self
1040        }
1041
1042        /// Invoked with the selected option's ID when the user picks an option from the menu.
1043        pub fn on_select(
1044            mut self,
1045            handler: impl Fn(SharedString, &mut Window, &mut App) + 'static,
1046        ) -> Self {
1047            self.on_select = Some(Rc::new(handler));
1048            self
1049        }
1050
1051        pub(super) fn id(&self) -> &ElementId {
1052            &self.id
1053        }
1054
1055        pub(super) fn custom_focus(&self) -> Option<FocusHandle> {
1056            self.focus.clone()
1057        }
1058
1059        pub(super) fn takes_focus(&self) -> bool {
1060            !self.disabled
1061        }
1062
1063        pub(super) fn render_in_section(
1064            self,
1065            resting: CornerShape,
1066            selected_shape: CornerShape,
1067            focus: Option<(FocusHandle, bool)>,
1068            window: &mut Window,
1069            cx: &mut App,
1070        ) -> AnyElement {
1071            let theme = current_material_theme(window, cx);
1072            let rtl = theme.layout.direction == Direction::Rtl;
1073            let value_color = if self.disabled {
1074                color(theme.colors.color(ColorRole::OnSurface)).opacity(0.38)
1075            } else {
1076                color(theme.colors.color(ColorRole::OnSurfaceVariant))
1077            };
1078
1079            let current_text = self
1080                .options
1081                .iter()
1082                .find(|option| option.id == self.selected)
1083                .map(|option| option.label.clone())
1084                .or(self.placeholder)
1085                .unwrap_or_default();
1086            let value_description = (!current_text.is_empty()).then(|| current_text.clone());
1087
1088            let trailing = div()
1089                .flex()
1090                .items_center()
1091                .gap(px(4.))
1092                .text_color(value_color)
1093                .when(rtl, Styled::flex_row_reverse)
1094                .when(!current_text.is_empty(), |row| {
1095                    row.child(
1096                        Text::new(current_text)
1097                            .id((self.id.clone(), "choice-value"))
1098                            .role(TypeRole::BodyMedium),
1099                    )
1100                })
1101                .child(Icon::new(IconName::ArrowDropDown).size(px(20.)));
1102
1103            let shapes = ListItemShapes {
1104                resting: Some(resting),
1105                selected: Some(selected_shape),
1106                ..Default::default()
1107            };
1108
1109            let source = self.source;
1110            let build_row = move |id: ElementId,
1111                                  label: SharedString,
1112                                  supporting: Option<SharedString>,
1113                                  overline: Option<SharedString>,
1114                                  leading: Option<AnyElement>,
1115                                  disabled: bool,
1116                                  colors: ListItemColors| {
1117                let mut item = ListItem::new(id, label)
1118                    .disabled(disabled)
1119                    .colors(colors)
1120                    .shapes(shapes)
1121                    .trailing(trailing);
1122                if let Some(description) = value_description {
1123                    item = item.aria_description(description);
1124                }
1125                if let Some(supporting) = supporting {
1126                    item = item.supporting_text(supporting);
1127                }
1128                if let Some(overline) = overline {
1129                    item = item.overline(overline);
1130                }
1131                if let Some(leading) = leading {
1132                    item = item.leading(leading);
1133                }
1134                if let Some(source) = source {
1135                    item = item.interaction_source(&source);
1136                }
1137                item
1138            };
1139
1140            if self.disabled {
1141                return build_row(
1142                    self.id,
1143                    self.label,
1144                    self.supporting,
1145                    self.overline,
1146                    self.leading,
1147                    true,
1148                    self.colors,
1149                )
1150                .row(resting, selected_shape, None, window, cx);
1151            }
1152
1153            let state = self.menu_state.unwrap_or_else(|| {
1154                window.use_keyed_state((self.id.clone(), "choice-tile-menu-state"), cx, |_, cx| {
1155                    DialogState::new(cx)
1156                })
1157            });
1158            let open = state.read(cx).is_open();
1159            let view = window.current_view();
1160            let (trigger_focus, tab_stop) = focus
1161                .or_else(|| self.focus.map(|handle| (handle, true)))
1162                .unwrap_or_else(|| {
1163                    let handle = window
1164                        .use_keyed_state((self.id.clone(), "choice-tile-focus"), cx, |_, cx| {
1165                            cx.focus_handle()
1166                        })
1167                        .read(cx)
1168                        .clone();
1169                    (handle, true)
1170                });
1171
1172            let tile_id = self.id.clone();
1173            let selected_id = self.selected;
1174            let on_select = self.on_select;
1175            let menu_items: Vec<MenuItem> = self
1176                .options
1177                .into_iter()
1178                .map(|option| {
1179                    let is_selected = option.id == selected_id;
1180                    let option_id = option.id.clone();
1181                    let mut entry = MenuItem::new((tile_id.clone(), option.id), option.label)
1182                        .selected(is_selected)
1183                        .disabled(option.disabled);
1184                    if let Some(supporting) = option.supporting {
1185                        entry = entry.supporting(move || supporting.clone());
1186                    }
1187                    if let Some(leading) = option.leading {
1188                        entry = entry.leading(move || leading());
1189                    }
1190                    if let Some(callback) = on_select.clone() {
1191                        entry = entry.on_activate(move |window, cx| {
1192                            callback(option_id.clone(), window, cx);
1193                        });
1194                    }
1195                    entry
1196                })
1197                .collect();
1198
1199            let row_id = self.id.clone();
1200            let label = self.label;
1201            let supporting = self.supporting;
1202            let overline = self.overline;
1203            let leading = self.leading;
1204            let colors = self.colors;
1205            let row_focus = trigger_focus.clone();
1206
1207            Menu::composed(
1208                (self.id.clone(), "menu"),
1209                menu_items,
1210                move |is_open, toggle| {
1211                    build_row(row_id, label, supporting, overline, leading, false, colors)
1212                        .track_focus(&row_focus, tab_stop)
1213                        .menu_trigger(is_open, toggle)
1214                        .into_any_element()
1215                },
1216            )
1217            .anchor(Anchor::TopRight)
1218            .open(open)
1219            .on_open_change(move |requested, window, cx| {
1220                state.update(cx, |dialog, cx| {
1221                    if requested {
1222                        dialog.open(window, cx);
1223                    } else {
1224                        dialog.close(window, cx);
1225                    }
1226                });
1227                if requested {
1228                    trigger_focus.focus(window, cx);
1229                }
1230                cx.notify(view);
1231            })
1232            .into_any_element()
1233        }
1234    }
1235
1236    impl RenderOnce for ChoiceTile {
1237        fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
1238            let (resting, selected_shape) = if self.variant == ListVariant::Segmented {
1239                (CornerRole::Large.shape(), CornerRole::Large.shape())
1240            } else {
1241                (CornerRole::None.shape(), CornerRole::None.shape())
1242            };
1243            self.render_in_section(resting, selected_shape, None, window, cx)
1244        }
1245    }
1246}
1247
1248#[cfg(all(feature = "surfaces", feature = "feedback"))]
1249pub use choice_tile::{ChoiceOption, ChoiceTile};
1250
1251#[cfg(feature = "surfaces")]
1252mod list_section {
1253    use gpui::{
1254        AnyElement, App, Axis, ElementId, FocusHandle, InteractiveElement, IntoElement,
1255        ParentElement, RenderOnce, Role, SharedString, StatefulInteractiveElement, Styled, Window,
1256        div, prelude::FluentBuilder, px,
1257    };
1258    use gpui_base::TestSupportExt;
1259    use gpui_material_foundation::{current_material_theme, move_roving_focus};
1260    use gpui_material_theme::{ColorRole, CornerRole, CornerShape, Direction, TypeRole};
1261
1262    use crate::{ListItem, ListVariant, Text};
1263
1264    #[cfg(feature = "feedback")]
1265    use super::ChoiceTile;
1266    #[cfg(feature = "selection")]
1267    use super::{CheckboxTile, RadioTile, SliderTile, SwitchTile};
1268
1269    /// Any list row or settings tile that can participate in a [`ListSection`].
1270    pub enum ListSectionItem {
1271        /// A standard [`ListItem`] row.
1272        Row(ListItem),
1273        /// A [`SwitchTile`] settings row.
1274        #[cfg(feature = "selection")]
1275        Switch(SwitchTile),
1276        /// A [`CheckboxTile`] settings row.
1277        #[cfg(feature = "selection")]
1278        Checkbox(CheckboxTile),
1279        /// A [`RadioTile`] settings row.
1280        #[cfg(feature = "selection")]
1281        Radio(RadioTile),
1282        /// A [`SliderTile`] settings row.
1283        #[cfg(feature = "selection")]
1284        Slider(SliderTile),
1285        /// A [`ChoiceTile`] settings row.
1286        #[cfg(feature = "feedback")]
1287        Choice(ChoiceTile),
1288    }
1289
1290    impl From<ListItem> for ListSectionItem {
1291        fn from(value: ListItem) -> Self {
1292            Self::Row(value)
1293        }
1294    }
1295
1296    #[cfg(feature = "selection")]
1297    impl From<SwitchTile> for ListSectionItem {
1298        fn from(value: SwitchTile) -> Self {
1299            Self::Switch(value)
1300        }
1301    }
1302
1303    #[cfg(feature = "selection")]
1304    impl From<CheckboxTile> for ListSectionItem {
1305        fn from(value: CheckboxTile) -> Self {
1306            Self::Checkbox(value)
1307        }
1308    }
1309
1310    #[cfg(feature = "selection")]
1311    impl From<RadioTile> for ListSectionItem {
1312        fn from(value: RadioTile) -> Self {
1313            Self::Radio(value)
1314        }
1315    }
1316
1317    #[cfg(feature = "selection")]
1318    impl From<SliderTile> for ListSectionItem {
1319        fn from(value: SliderTile) -> Self {
1320            Self::Slider(value)
1321        }
1322    }
1323
1324    #[cfg(feature = "feedback")]
1325    impl From<ChoiceTile> for ListSectionItem {
1326        fn from(value: ChoiceTile) -> Self {
1327            Self::Choice(value)
1328        }
1329    }
1330
1331    enum PreparedItem {
1332        Row(Box<ListItem>),
1333        #[cfg(feature = "feedback")]
1334        Choice(Box<ChoiceTile>),
1335    }
1336
1337    impl PreparedItem {
1338        fn from_section_item(item: ListSectionItem, window: &Window, cx: &App) -> Self {
1339            #[cfg(not(feature = "selection"))]
1340            let _ = (window, cx);
1341            match item {
1342                ListSectionItem::Row(row) => Self::Row(Box::new(row)),
1343                #[cfg(feature = "selection")]
1344                ListSectionItem::Switch(tile) => Self::Row(Box::new(tile.into_list_item())),
1345                #[cfg(feature = "selection")]
1346                ListSectionItem::Checkbox(tile) => Self::Row(Box::new(tile.into_list_item())),
1347                #[cfg(feature = "selection")]
1348                ListSectionItem::Radio(tile) => Self::Row(Box::new(tile.into_list_item())),
1349                #[cfg(feature = "selection")]
1350                ListSectionItem::Slider(tile) => {
1351                    Self::Row(Box::new(tile.into_list_item(window, cx)))
1352                }
1353                #[cfg(feature = "feedback")]
1354                ListSectionItem::Choice(tile) => Self::Choice(Box::new(tile)),
1355            }
1356        }
1357
1358        fn id(&self) -> &ElementId {
1359            match self {
1360                Self::Row(row) => row.id(),
1361                #[cfg(feature = "feedback")]
1362                Self::Choice(tile) => tile.id(),
1363            }
1364        }
1365
1366        fn custom_focus(&self) -> Option<FocusHandle> {
1367            match self {
1368                Self::Row(row) => row.custom_focus(),
1369                #[cfg(feature = "feedback")]
1370                Self::Choice(tile) => tile.custom_focus(),
1371            }
1372        }
1373
1374        fn takes_focus(&self, cx: &App) -> bool {
1375            match self {
1376                Self::Row(row) => row.takes_focus(cx),
1377                #[cfg(feature = "feedback")]
1378                Self::Choice(tile) => tile.takes_focus(),
1379            }
1380        }
1381
1382        fn is_selected(&self) -> bool {
1383            match self {
1384                Self::Row(row) => row.is_selected(),
1385                #[cfg(feature = "feedback")]
1386                Self::Choice(_) => false,
1387            }
1388        }
1389
1390        fn render(
1391            self,
1392            resting: CornerShape,
1393            selected_shape: CornerShape,
1394            focus: Option<(FocusHandle, bool)>,
1395            window: &mut Window,
1396            cx: &mut App,
1397        ) -> AnyElement {
1398            match self {
1399                Self::Row(row) => (*row).row(resting, selected_shape, focus, window, cx),
1400                #[cfg(feature = "feedback")]
1401                Self::Choice(tile) => {
1402                    (*tile).render_in_section(resting, selected_shape, focus, window, cx)
1403                }
1404            }
1405        }
1406    }
1407
1408    pub(super) fn section_corners(
1409        variant: ListVariant,
1410        ix: usize,
1411        last: usize,
1412    ) -> (CornerShape, CornerShape) {
1413        match variant {
1414            ListVariant::Standard => (CornerRole::None.shape(), CornerRole::None.shape()),
1415            ListVariant::Segmented => {
1416                let top = if ix == 0 { 16. } else { 4. };
1417                let bottom = if ix == last { 16. } else { 4. };
1418                (
1419                    CornerShape::Radii([top, top, bottom, bottom]),
1420                    CornerRole::Large.shape(),
1421                )
1422            }
1423        }
1424    }
1425
1426    /// Titled list section supporting [`ListVariant::Standard`] and Material 3 Expressive
1427    /// [`ListVariant::Segmented`] grouped corner geometry and unified vertical roving focus across
1428    /// [`ListItem`] and settings tiles.
1429    #[derive(IntoElement)]
1430    pub struct ListSection {
1431        id: ElementId,
1432        title: Option<SharedString>,
1433        variant: ListVariant,
1434        items: Vec<ListSectionItem>,
1435    }
1436
1437    impl ListSection {
1438        /// Creates an empty [`ListVariant::Standard`] list section with the given element ID.
1439        pub fn new(id: impl Into<ElementId>) -> Self {
1440            Self {
1441                id: id.into(),
1442                title: None,
1443                variant: ListVariant::default(),
1444                items: Vec::new(),
1445            }
1446        }
1447
1448        /// Shorthand for a Material 3 Expressive [`ListVariant::Segmented`] section.
1449        pub fn segmented(id: impl Into<ElementId>) -> Self {
1450            Self::new(id).variant(ListVariant::Segmented)
1451        }
1452
1453        /// Sets an optional section heading displayed above the list and used as the list's accessible name.
1454        pub fn title(mut self, title: impl Into<SharedString>) -> Self {
1455            self.title = Some(title.into());
1456            self
1457        }
1458
1459        /// Sets the section layout variant (`Standard` or `Segmented`).
1460        pub fn variant(mut self, variant: ListVariant) -> Self {
1461            self.variant = variant;
1462            self
1463        }
1464
1465        /// Appends a single [`ListItem`] or settings tile to the section.
1466        pub fn item(mut self, item: impl Into<ListSectionItem>) -> Self {
1467            self.items.push(item.into());
1468            self
1469        }
1470
1471        /// Appends multiple rows or settings tiles from an iterator.
1472        pub fn items<I>(mut self, items: impl IntoIterator<Item = I>) -> Self
1473        where
1474            I: Into<ListSectionItem>,
1475        {
1476            self.items.extend(items.into_iter().map(Into::into));
1477            self
1478        }
1479    }
1480
1481    impl RenderOnce for ListSection {
1482        fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
1483            window.with_element_namespace((self.id.clone(), "material-list-section"), |window| {
1484                let direction = current_material_theme(window, cx).layout.direction;
1485                let rtl = direction == Direction::Rtl;
1486                let prepared: Vec<_> = self
1487                    .items
1488                    .into_iter()
1489                    .map(|item| PreparedItem::from_section_item(item, window, cx))
1490                    .collect();
1491                let last = prepared.len().saturating_sub(1);
1492                let focus: Vec<_> = prepared
1493                    .iter()
1494                    .map(|item| {
1495                        item.custom_focus().unwrap_or_else(|| {
1496                            window
1497                                .use_keyed_state((item.id().clone(), "focus"), cx, |_, cx| {
1498                                    cx.focus_handle()
1499                                })
1500                                .read(cx)
1501                                .clone()
1502                        })
1503                    })
1504                    .collect();
1505                let enabled: Vec<_> = prepared.iter().map(|item| item.takes_focus(cx)).collect();
1506                let tab_stop = focus
1507                    .iter()
1508                    .enumerate()
1509                    .position(|(ix, focus)| enabled[ix] && focus.is_focused(window))
1510                    .or_else(|| {
1511                        prepared
1512                            .iter()
1513                            .enumerate()
1514                            .position(|(ix, item)| enabled[ix] && item.is_selected())
1515                    })
1516                    .or_else(|| enabled.iter().position(|enabled| *enabled));
1517                let navigation = focus.clone();
1518                let list_label = self.title.clone();
1519                let heading = self.title.map(|title| {
1520                    div()
1521                        .id((self.id.clone(), "section-heading"))
1522                        .test_support()
1523                        .w_full()
1524                        .flex()
1525                        .when(rtl, Styled::justify_end)
1526                        .px(px(16.))
1527                        .pt(px(8.))
1528                        .pb(px(6.))
1529                        .child(
1530                            Text::new(title)
1531                                .id((self.id.clone(), "section-title"))
1532                                .role(TypeRole::LabelMedium)
1533                                .color(ColorRole::OnSurfaceVariant),
1534                        )
1535                });
1536                let list = div()
1537                    .id((self.id.clone(), "list"))
1538                    .role(Role::List)
1539                    .when_some(list_label, |list, label| list.aria_label(label))
1540                    .test_support()
1541                    .flex()
1542                    .flex_col()
1543                    .w_full()
1544                    .on_key_down(move |event, window, cx| {
1545                        // Nested controls (e.g. SliderTile slider or open ChoiceTile menu)
1546                        // keep their own arrow-key behavior.
1547                        if !navigation.iter().any(|focus| focus.is_focused(window)) {
1548                            return;
1549                        }
1550                        let key = event.keystroke.key.as_str();
1551                        let moved = if key == "home" {
1552                            enabled.iter().position(|enabled| *enabled).inspect(|&ix| {
1553                                navigation[ix].focus(window, cx);
1554                            })
1555                        } else if key == "end" {
1556                            enabled.iter().rposition(|enabled| *enabled).inspect(|&ix| {
1557                                navigation[ix].focus(window, cx);
1558                            })
1559                        } else {
1560                            let items: Vec<_> = navigation
1561                                .iter()
1562                                .zip(&enabled)
1563                                .map(|(focus, enabled)| (focus, *enabled))
1564                                .collect();
1565                            move_roving_focus(&items, key, Axis::Vertical, direction, window, cx)
1566                        };
1567                        if moved.is_some() {
1568                            cx.stop_propagation();
1569                            window.refresh();
1570                        }
1571                    })
1572                    .when(self.variant == ListVariant::Segmented, |list| {
1573                        list.gap(px(2.))
1574                    })
1575                    .children(prepared.into_iter().zip(focus).enumerate().map(
1576                        |(ix, (item, focus))| {
1577                            let (resting, selected_shape) = section_corners(self.variant, ix, last);
1578                            item.render(
1579                                resting,
1580                                selected_shape,
1581                                Some((focus, Some(ix) == tab_stop)),
1582                                window,
1583                                cx,
1584                            )
1585                        },
1586                    ));
1587                div()
1588                    .id(self.id)
1589                    .test_support()
1590                    .flex()
1591                    .flex_col()
1592                    .w_full()
1593                    .children(heading)
1594                    .child(list)
1595            })
1596        }
1597    }
1598}
1599
1600#[cfg(feature = "surfaces")]
1601pub use list_section::{ListSection, ListSectionItem};
1602
1603#[cfg(test)]
1604mod tests {
1605    use super::list_section::section_corners;
1606    use crate::ListVariant;
1607    use gpui_material_theme::{CornerRole, CornerShape};
1608
1609    #[test]
1610    fn list_section_computes_m3e_segmented_and_standard_corners() {
1611        assert_eq!(
1612            section_corners(ListVariant::Standard, 0, 2),
1613            (CornerRole::None.shape(), CornerRole::None.shape())
1614        );
1615        // Single item gets 16 dp all around.
1616        assert_eq!(
1617            section_corners(ListVariant::Segmented, 0, 0),
1618            (
1619                CornerShape::Radii([16., 16., 16., 16.]),
1620                CornerRole::Large.shape()
1621            )
1622        );
1623        // Multi-item segmented list: first [16,16,4,4], middle [4,4,4,4], last [4,4,16,16].
1624        assert_eq!(
1625            section_corners(ListVariant::Segmented, 0, 2),
1626            (
1627                CornerShape::Radii([16., 16., 4., 4.]),
1628                CornerRole::Large.shape()
1629            )
1630        );
1631        assert_eq!(
1632            section_corners(ListVariant::Segmented, 1, 2),
1633            (
1634                CornerShape::Radii([4., 4., 4., 4.]),
1635                CornerRole::Large.shape()
1636            )
1637        );
1638        assert_eq!(
1639            section_corners(ListVariant::Segmented, 2, 2),
1640            (
1641                CornerShape::Radii([4., 4., 16., 16.]),
1642                CornerRole::Large.shape()
1643            )
1644        );
1645    }
1646
1647    #[cfg(feature = "selection")]
1648    #[test]
1649    fn slider_tile_formats_integers_decimals_and_ranges_cleanly() {
1650        use super::slider_tile::{format_slider_scalar, format_slider_value};
1651        use crate::SliderValue;
1652
1653        assert_eq!(format_slider_scalar(42.0), "42");
1654        assert_eq!(format_slider_scalar(3.25), "3.25");
1655        assert_eq!(format_slider_scalar(f32::NAN), "0");
1656        assert_eq!(format_slider_value(SliderValue::Single(75.0), None), "75");
1657        assert_eq!(
1658            format_slider_value(SliderValue::Range(10.0, 80.5), None),
1659            "10 – 80.50"
1660        );
1661    }
1662}