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