toggle.rs

  1use gpui::{
  2    div, hsla, prelude::*, AnyElement, AnyView, CursorStyle, ElementId, Hsla, IntoElement, Styled,
  3    Window,
  4};
  5use std::sync::Arc;
  6
  7use crate::utils::is_light;
  8use crate::{prelude::*, ElevationIndex, KeyBinding};
  9use crate::{Color, Icon, IconName, ToggleState};
 10
 11// TODO: Checkbox, CheckboxWithLabel, and Switch could all be
 12// restructured to use a ToggleLike, similar to Button/Buttonlike, Label/Labellike
 13
 14/// Creates a new checkbox.
 15pub fn checkbox(id: impl Into<ElementId>, toggle_state: ToggleState) -> Checkbox {
 16    Checkbox::new(id, toggle_state)
 17}
 18
 19/// Creates a new switch.
 20pub fn switch(id: impl Into<ElementId>, toggle_state: ToggleState) -> Switch {
 21    Switch::new(id, toggle_state)
 22}
 23
 24/// The visual style of a toggle.
 25#[derive(Debug, Default, Clone, PartialEq, Eq)]
 26pub enum ToggleStyle {
 27    /// Toggle has a transparent background
 28    #[default]
 29    Ghost,
 30    /// Toggle has a filled background based on the
 31    /// elevation index of the parent container
 32    ElevationBased(ElevationIndex),
 33    /// A custom style using a color to tint the toggle
 34    Custom(Hsla),
 35}
 36
 37/// # Checkbox
 38///
 39/// Checkboxes are used for multiple choices, not for mutually exclusive choices.
 40/// Each checkbox works independently from other checkboxes in the list,
 41/// therefore checking an additional box does not affect any other selections.
 42#[derive(IntoElement, IntoComponent)]
 43#[component(scope = "input")]
 44pub struct Checkbox {
 45    id: ElementId,
 46    toggle_state: ToggleState,
 47    disabled: bool,
 48    placeholder: bool,
 49    on_click: Option<Box<dyn Fn(&ToggleState, &mut Window, &mut App) + 'static>>,
 50    filled: bool,
 51    style: ToggleStyle,
 52    tooltip: Option<Box<dyn Fn(&mut Window, &mut App) -> AnyView>>,
 53    label: Option<SharedString>,
 54}
 55
 56impl Checkbox {
 57    /// Creates a new [`Checkbox`].
 58    pub fn new(id: impl Into<ElementId>, checked: ToggleState) -> Self {
 59        Self {
 60            id: id.into(),
 61            toggle_state: checked,
 62            disabled: false,
 63            on_click: None,
 64            filled: false,
 65            style: ToggleStyle::default(),
 66            tooltip: None,
 67            label: None,
 68            placeholder: false,
 69        }
 70    }
 71
 72    /// Sets the disabled state of the [`Checkbox`].
 73    pub fn disabled(mut self, disabled: bool) -> Self {
 74        self.disabled = disabled;
 75        self
 76    }
 77
 78    /// Sets the disabled state of the [`Checkbox`].
 79    pub fn placeholder(mut self, placeholder: bool) -> Self {
 80        self.placeholder = placeholder;
 81        self
 82    }
 83
 84    /// Binds a handler to the [`Checkbox`] that will be called when clicked.
 85    pub fn on_click(
 86        mut self,
 87        handler: impl Fn(&ToggleState, &mut Window, &mut App) + 'static,
 88    ) -> Self {
 89        self.on_click = Some(Box::new(handler));
 90        self
 91    }
 92
 93    /// Sets the `fill` setting of the checkbox, indicating whether it should be filled.
 94    pub fn fill(mut self) -> Self {
 95        self.filled = true;
 96        self
 97    }
 98
 99    /// Sets the style of the checkbox using the specified [`ToggleStyle`].
100    pub fn style(mut self, style: ToggleStyle) -> Self {
101        self.style = style;
102        self
103    }
104
105    /// Match the style of the checkbox to the current elevation using [`ToggleStyle::ElevationBased`].
106    pub fn elevation(mut self, elevation: ElevationIndex) -> Self {
107        self.style = ToggleStyle::ElevationBased(elevation);
108        self
109    }
110
111    /// Sets the tooltip for the checkbox.
112    pub fn tooltip(mut self, tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static) -> Self {
113        self.tooltip = Some(Box::new(tooltip));
114        self
115    }
116
117    /// Set the label for the checkbox.
118    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
119        self.label = Some(label.into());
120        self
121    }
122}
123
124impl Checkbox {
125    fn bg_color(&self, cx: &App) -> Hsla {
126        let style = self.style.clone();
127        match (style, self.filled) {
128            (ToggleStyle::Ghost, false) => cx.theme().colors().ghost_element_background,
129            (ToggleStyle::Ghost, true) => cx.theme().colors().element_background,
130            (ToggleStyle::ElevationBased(_), false) => gpui::transparent_black(),
131            (ToggleStyle::ElevationBased(elevation), true) => elevation.darker_bg(cx),
132            (ToggleStyle::Custom(_), false) => gpui::transparent_black(),
133            (ToggleStyle::Custom(color), true) => color.opacity(0.2),
134        }
135    }
136
137    fn border_color(&self, cx: &App) -> Hsla {
138        if self.disabled {
139            return cx.theme().colors().border_variant;
140        }
141
142        match self.style.clone() {
143            ToggleStyle::Ghost => cx.theme().colors().border,
144            ToggleStyle::ElevationBased(elevation) => elevation.on_elevation_bg(cx),
145            ToggleStyle::Custom(color) => color.opacity(0.3),
146        }
147    }
148
149    /// container size
150    pub fn container_size(cx: &App) -> Rems {
151        DynamicSpacing::Base20.rems(cx)
152    }
153}
154
155impl RenderOnce for Checkbox {
156    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
157        let group_id = format!("checkbox_group_{:?}", self.id);
158        let color = if self.disabled {
159            Color::Disabled
160        } else if self.placeholder {
161            Color::Placeholder
162        } else {
163            Color::Selected
164        };
165        let icon = match self.toggle_state {
166            ToggleState::Selected => Some(if self.placeholder {
167                Icon::new(IconName::Circle)
168                    .size(IconSize::XSmall)
169                    .color(color)
170            } else {
171                Icon::new(IconName::Check)
172                    .size(IconSize::Small)
173                    .color(color)
174            }),
175            ToggleState::Indeterminate => {
176                Some(Icon::new(IconName::Dash).size(IconSize::Small).color(color))
177            }
178            ToggleState::Unselected => None,
179        };
180
181        let bg_color = self.bg_color(cx);
182        let border_color = self.border_color(cx);
183
184        let size = Self::container_size(cx);
185
186        let checkbox = h_flex()
187            .id(self.id.clone())
188            .justify_center()
189            .items_center()
190            .size(size)
191            .group(group_id.clone())
192            .child(
193                div()
194                    .flex()
195                    .flex_none()
196                    .justify_center()
197                    .items_center()
198                    .m(DynamicSpacing::Base04.px(cx))
199                    .size(DynamicSpacing::Base16.rems(cx))
200                    .rounded_sm()
201                    .bg(bg_color)
202                    .border_1()
203                    .border_color(border_color)
204                    .when(self.disabled, |this| {
205                        this.cursor(CursorStyle::OperationNotAllowed)
206                    })
207                    .when(self.disabled, |this| {
208                        this.bg(cx.theme().colors().element_disabled.opacity(0.6))
209                    })
210                    .when(!self.disabled, |this| {
211                        this.group_hover(group_id.clone(), |el| {
212                            el.bg(cx.theme().colors().element_hover)
213                        })
214                    })
215                    .children(icon),
216            );
217
218        h_flex()
219            .id(self.id)
220            .gap(DynamicSpacing::Base06.rems(cx))
221            .child(checkbox)
222            .when_some(
223                self.on_click.filter(|_| !self.disabled),
224                |this, on_click| {
225                    this.on_click(move |_, window, cx| {
226                        on_click(&self.toggle_state.inverse(), window, cx)
227                    })
228                },
229            )
230            // TODO: Allow label size to be different from default.
231            // TODO: Allow label color to be different from muted.
232            .when_some(self.label, |this, label| {
233                this.child(Label::new(label).color(Color::Muted))
234            })
235            .when_some(self.tooltip, |this, tooltip| {
236                this.tooltip(move |window, cx| tooltip(window, cx))
237            })
238    }
239}
240
241/// A [`Checkbox`] that has a [`Label`].
242#[derive(IntoElement, IntoComponent)]
243#[component(scope = "input")]
244pub struct CheckboxWithLabel {
245    id: ElementId,
246    label: Label,
247    checked: ToggleState,
248    on_click: Arc<dyn Fn(&ToggleState, &mut Window, &mut App) + 'static>,
249    filled: bool,
250    style: ToggleStyle,
251}
252
253// TODO: Remove `CheckboxWithLabel` now that `label` is a method of `Checkbox`.
254impl CheckboxWithLabel {
255    /// Creates a checkbox with an attached label.
256    pub fn new(
257        id: impl Into<ElementId>,
258        label: Label,
259        checked: ToggleState,
260        on_click: impl Fn(&ToggleState, &mut Window, &mut App) + 'static,
261    ) -> Self {
262        Self {
263            id: id.into(),
264            label,
265            checked,
266            on_click: Arc::new(on_click),
267            filled: false,
268            style: ToggleStyle::default(),
269        }
270    }
271
272    /// Sets the style of the checkbox using the specified [`ToggleStyle`].
273    pub fn style(mut self, style: ToggleStyle) -> Self {
274        self.style = style;
275        self
276    }
277
278    /// Match the style of the checkbox to the current elevation using [`ToggleStyle::ElevationBased`].
279    pub fn elevation(mut self, elevation: ElevationIndex) -> Self {
280        self.style = ToggleStyle::ElevationBased(elevation);
281        self
282    }
283
284    /// Sets the `fill` setting of the checkbox, indicating whether it should be filled.
285    pub fn fill(mut self) -> Self {
286        self.filled = true;
287        self
288    }
289}
290
291impl RenderOnce for CheckboxWithLabel {
292    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
293        h_flex()
294            .gap(DynamicSpacing::Base08.rems(cx))
295            .child(
296                Checkbox::new(self.id.clone(), self.checked)
297                    .style(self.style)
298                    .when(self.filled, Checkbox::fill)
299                    .on_click({
300                        let on_click = self.on_click.clone();
301                        move |checked, window, cx| {
302                            (on_click)(checked, window, cx);
303                        }
304                    }),
305            )
306            .child(
307                div()
308                    .id(SharedString::from(format!("{}-label", self.id)))
309                    .on_click(move |_event, window, cx| {
310                        (self.on_click)(&self.checked.inverse(), window, cx);
311                    })
312                    .child(self.label),
313            )
314    }
315}
316
317/// # Switch
318///
319/// Switches are used to represent opposite states, such as enabled or disabled.
320#[derive(IntoElement, IntoComponent)]
321#[component(scope = "input")]
322pub struct Switch {
323    id: ElementId,
324    toggle_state: ToggleState,
325    disabled: bool,
326    on_click: Option<Box<dyn Fn(&ToggleState, &mut Window, &mut App) + 'static>>,
327    label: Option<SharedString>,
328    key_binding: Option<KeyBinding>,
329}
330
331impl Switch {
332    /// Creates a new [`Switch`].
333    pub fn new(id: impl Into<ElementId>, state: ToggleState) -> Self {
334        Self {
335            id: id.into(),
336            toggle_state: state,
337            disabled: false,
338            on_click: None,
339            label: None,
340            key_binding: None,
341        }
342    }
343
344    /// Sets the disabled state of the [`Switch`].
345    pub fn disabled(mut self, disabled: bool) -> Self {
346        self.disabled = disabled;
347        self
348    }
349
350    /// Binds a handler to the [`Switch`] that will be called when clicked.
351    pub fn on_click(
352        mut self,
353        handler: impl Fn(&ToggleState, &mut Window, &mut App) + 'static,
354    ) -> Self {
355        self.on_click = Some(Box::new(handler));
356        self
357    }
358
359    /// Sets the label of the [`Switch`].
360    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
361        self.label = Some(label.into());
362        self
363    }
364
365    /// Display the keybinding that triggers the switch action.
366    pub fn key_binding(mut self, key_binding: impl Into<Option<KeyBinding>>) -> Self {
367        self.key_binding = key_binding.into();
368        self
369    }
370}
371
372impl RenderOnce for Switch {
373    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
374        let is_on = self.toggle_state == ToggleState::Selected;
375        let adjust_ratio = if is_light(cx) { 1.5 } else { 1.0 };
376        let base_color = cx.theme().colors().text;
377
378        let bg_color = if is_on {
379            cx.theme()
380                .colors()
381                .element_background
382                .blend(base_color.opacity(0.08))
383        } else {
384            cx.theme().colors().element_background
385        };
386        let thumb_color = base_color.opacity(0.8);
387        let thumb_hover_color = base_color;
388        let border_color = cx.theme().colors().border_variant;
389        // Lighter themes need higher contrast borders
390        let border_hover_color = if is_on {
391            border_color.blend(base_color.opacity(0.16 * adjust_ratio))
392        } else {
393            border_color.blend(base_color.opacity(0.05 * adjust_ratio))
394        };
395        let thumb_opacity = match (is_on, self.disabled) {
396            (_, true) => 0.2,
397            (true, false) => 1.0,
398            (false, false) => 0.5,
399        };
400
401        let group_id = format!("switch_group_{:?}", self.id);
402
403        let switch = h_flex()
404            .w(DynamicSpacing::Base32.rems(cx))
405            .h(DynamicSpacing::Base20.rems(cx))
406            .group(group_id.clone())
407            .child(
408                h_flex()
409                    .when(is_on, |on| on.justify_end())
410                    .when(!is_on, |off| off.justify_start())
411                    .items_center()
412                    .size_full()
413                    .rounded_full()
414                    .px(DynamicSpacing::Base02.px(cx))
415                    .bg(bg_color)
416                    .border_1()
417                    .border_color(border_color)
418                    .when(!self.disabled, |this| {
419                        this.group_hover(group_id.clone(), |el| el.border_color(border_hover_color))
420                    })
421                    .child(
422                        div()
423                            .size(DynamicSpacing::Base12.rems(cx))
424                            .rounded_full()
425                            .bg(thumb_color)
426                            .when(!self.disabled, |this| {
427                                this.group_hover(group_id.clone(), |el| el.bg(thumb_hover_color))
428                            })
429                            .opacity(thumb_opacity),
430                    ),
431            );
432
433        h_flex()
434            .id(self.id)
435            .gap(DynamicSpacing::Base06.rems(cx))
436            .cursor_pointer()
437            .child(switch)
438            .when_some(
439                self.on_click.filter(|_| !self.disabled),
440                |this, on_click| {
441                    this.on_click(move |_, window, cx| {
442                        on_click(&self.toggle_state.inverse(), window, cx)
443                    })
444                },
445            )
446            .when_some(self.label, |this, label| {
447                this.child(Label::new(label).size(LabelSize::Small))
448            })
449            .children(self.key_binding)
450    }
451}
452
453/// A [`Switch`] that has a [`Label`].
454#[derive(IntoElement)]
455// #[component(scope = "input")]
456pub struct SwitchWithLabel {
457    id: ElementId,
458    label: Label,
459    toggle_state: ToggleState,
460    on_click: Arc<dyn Fn(&ToggleState, &mut Window, &mut App) + 'static>,
461    disabled: bool,
462}
463
464impl SwitchWithLabel {
465    /// Creates a switch with an attached label.
466    pub fn new(
467        id: impl Into<ElementId>,
468        label: Label,
469        toggle_state: impl Into<ToggleState>,
470        on_click: impl Fn(&ToggleState, &mut Window, &mut App) + 'static,
471    ) -> Self {
472        Self {
473            id: id.into(),
474            label,
475            toggle_state: toggle_state.into(),
476            on_click: Arc::new(on_click),
477            disabled: false,
478        }
479    }
480
481    /// Sets the disabled state of the [`SwitchWithLabel`].
482    pub fn disabled(mut self, disabled: bool) -> Self {
483        self.disabled = disabled;
484        self
485    }
486}
487
488impl RenderOnce for SwitchWithLabel {
489    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
490        h_flex()
491            .id(SharedString::from(format!("{}-container", self.id)))
492            .gap(DynamicSpacing::Base08.rems(cx))
493            .child(
494                Switch::new(self.id.clone(), self.toggle_state)
495                    .disabled(self.disabled)
496                    .on_click({
497                        let on_click = self.on_click.clone();
498                        move |checked, window, cx| {
499                            (on_click)(checked, window, cx);
500                        }
501                    }),
502            )
503            .child(
504                div()
505                    .id(SharedString::from(format!("{}-label", self.id)))
506                    .child(self.label),
507            )
508    }
509}
510
511impl ComponentPreview for Checkbox {
512    fn preview(_window: &mut Window, _cx: &App) -> AnyElement {
513        v_flex()
514            .gap_6()
515            .children(vec![
516                example_group_with_title(
517                    "States",
518                    vec![
519                        single_example(
520                            "Unselected",
521                            Checkbox::new("checkbox_unselected", ToggleState::Unselected)
522                                .into_any_element(),
523                        ),
524                        single_example(
525                            "Indeterminate",
526                            Checkbox::new("checkbox_indeterminate", ToggleState::Indeterminate)
527                                .into_any_element(),
528                        ),
529                        single_example(
530                            "Selected",
531                            Checkbox::new("checkbox_selected", ToggleState::Selected)
532                                .into_any_element(),
533                        ),
534                    ],
535                ),
536                example_group_with_title(
537                    "Styles",
538                    vec![
539                        single_example(
540                            "Default",
541                            Checkbox::new("checkbox_default", ToggleState::Selected)
542                                .into_any_element(),
543                        ),
544                        single_example(
545                            "Filled",
546                            Checkbox::new("checkbox_filled", ToggleState::Selected)
547                                .fill()
548                                .into_any_element(),
549                        ),
550                        single_example(
551                            "ElevationBased",
552                            Checkbox::new("checkbox_elevation", ToggleState::Selected)
553                                .style(ToggleStyle::ElevationBased(ElevationIndex::EditorSurface))
554                                .into_any_element(),
555                        ),
556                        single_example(
557                            "Custom Color",
558                            Checkbox::new("checkbox_custom", ToggleState::Selected)
559                                .style(ToggleStyle::Custom(hsla(142.0 / 360., 0.68, 0.45, 0.7)))
560                                .into_any_element(),
561                        ),
562                    ],
563                ),
564                example_group_with_title(
565                    "Disabled",
566                    vec![
567                        single_example(
568                            "Unselected",
569                            Checkbox::new("checkbox_disabled_unselected", ToggleState::Unselected)
570                                .disabled(true)
571                                .into_any_element(),
572                        ),
573                        single_example(
574                            "Selected",
575                            Checkbox::new("checkbox_disabled_selected", ToggleState::Selected)
576                                .disabled(true)
577                                .into_any_element(),
578                        ),
579                    ],
580                ),
581                example_group_with_title(
582                    "With Label",
583                    vec![single_example(
584                        "Default",
585                        Checkbox::new("checkbox_with_label", ToggleState::Selected)
586                            .label("Always save on quit")
587                            .into_any_element(),
588                    )],
589                ),
590            ])
591            .into_any_element()
592    }
593}
594
595impl ComponentPreview for Switch {
596    fn preview(_window: &mut Window, _cx: &App) -> AnyElement {
597        v_flex()
598            .gap_6()
599            .children(vec![
600                example_group_with_title(
601                    "States",
602                    vec![
603                        single_example(
604                            "Off",
605                            Switch::new("switch_off", ToggleState::Unselected)
606                                .on_click(|_, _, _cx| {})
607                                .into_any_element(),
608                        ),
609                        single_example(
610                            "On",
611                            Switch::new("switch_on", ToggleState::Selected)
612                                .on_click(|_, _, _cx| {})
613                                .into_any_element(),
614                        ),
615                    ],
616                ),
617                example_group_with_title(
618                    "Disabled",
619                    vec![
620                        single_example(
621                            "Off",
622                            Switch::new("switch_disabled_off", ToggleState::Unselected)
623                                .disabled(true)
624                                .into_any_element(),
625                        ),
626                        single_example(
627                            "On",
628                            Switch::new("switch_disabled_on", ToggleState::Selected)
629                                .disabled(true)
630                                .into_any_element(),
631                        ),
632                    ],
633                ),
634                example_group_with_title(
635                    "With Label",
636                    vec![
637                        single_example(
638                            "Label",
639                            Switch::new("switch_with_label", ToggleState::Selected)
640                                .label("Always save on quit")
641                                .into_any_element(),
642                        ),
643                        // TODO: Where did theme_preview_keybinding go?
644                        // single_example(
645                        //     "Keybinding",
646                        //     Switch::new("switch_with_keybinding", ToggleState::Selected)
647                        //         .key_binding(theme_preview_keybinding("cmd-shift-e"))
648                        //         .into_any_element(),
649                        // ),
650                    ],
651                ),
652            ])
653            .into_any_element()
654    }
655}
656
657impl ComponentPreview for CheckboxWithLabel {
658    fn preview(_window: &mut Window, _cx: &App) -> AnyElement {
659        v_flex()
660            .gap_6()
661            .children(vec![example_group_with_title(
662                "States",
663                vec![
664                    single_example(
665                        "Unselected",
666                        CheckboxWithLabel::new(
667                            "checkbox_with_label_unselected",
668                            Label::new("Always save on quit"),
669                            ToggleState::Unselected,
670                            |_, _, _| {},
671                        )
672                        .into_any_element(),
673                    ),
674                    single_example(
675                        "Indeterminate",
676                        CheckboxWithLabel::new(
677                            "checkbox_with_label_indeterminate",
678                            Label::new("Always save on quit"),
679                            ToggleState::Indeterminate,
680                            |_, _, _| {},
681                        )
682                        .into_any_element(),
683                    ),
684                    single_example(
685                        "Selected",
686                        CheckboxWithLabel::new(
687                            "checkbox_with_label_selected",
688                            Label::new("Always save on quit"),
689                            ToggleState::Selected,
690                            |_, _, _| {},
691                        )
692                        .into_any_element(),
693                    ),
694                ],
695            )])
696            .into_any_element()
697    }
698}