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