toggle.rs

   1use gpui::{
   2    AnyElement, AnyView, ClickEvent, ElementId, Hsla, IntoElement, Styled, Window, div, hsla,
   3    prelude::*,
   4};
   5use std::{rc::Rc, sync::Arc};
   6
   7use crate::utils::is_light;
   8use crate::{Color, Icon, IconName, ToggleState, Tooltip};
   9use crate::{ElevationIndex, KeyBinding, prelude::*};
  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, RegisterComponent)]
  43pub struct Checkbox {
  44    id: ElementId,
  45    toggle_state: ToggleState,
  46    disabled: bool,
  47    placeholder: bool,
  48    on_click: Option<Box<dyn Fn(&ToggleState, &ClickEvent, &mut Window, &mut App) + 'static>>,
  49    filled: bool,
  50    style: ToggleStyle,
  51    tooltip: Option<Box<dyn Fn(&mut Window, &mut App) -> AnyView>>,
  52    label: Option<SharedString>,
  53}
  54
  55impl Checkbox {
  56    /// Creates a new [`Checkbox`].
  57    pub fn new(id: impl Into<ElementId>, checked: ToggleState) -> Self {
  58        Self {
  59            id: id.into(),
  60            toggle_state: checked,
  61            disabled: false,
  62            on_click: None,
  63            filled: false,
  64            style: ToggleStyle::default(),
  65            tooltip: None,
  66            label: None,
  67            placeholder: false,
  68        }
  69    }
  70
  71    /// Sets the disabled state of the [`Checkbox`].
  72    pub fn disabled(mut self, disabled: bool) -> Self {
  73        self.disabled = disabled;
  74        self
  75    }
  76
  77    /// Sets the disabled state of the [`Checkbox`].
  78    pub fn placeholder(mut self, placeholder: bool) -> Self {
  79        self.placeholder = placeholder;
  80        self
  81    }
  82
  83    /// Binds a handler to the [`Checkbox`] that will be called when clicked.
  84    pub fn on_click(
  85        mut self,
  86        handler: impl Fn(&ToggleState, &mut Window, &mut App) + 'static,
  87    ) -> Self {
  88        self.on_click = Some(Box::new(move |state, _, window, cx| {
  89            handler(state, window, cx)
  90        }));
  91        self
  92    }
  93
  94    pub fn on_click_ext(
  95        mut self,
  96        handler: impl Fn(&ToggleState, &ClickEvent, &mut Window, &mut App) + 'static,
  97    ) -> Self {
  98        self.on_click = Some(Box::new(handler));
  99        self
 100    }
 101
 102    /// Sets the `fill` setting of the checkbox, indicating whether it should be filled.
 103    pub fn fill(mut self) -> Self {
 104        self.filled = true;
 105        self
 106    }
 107
 108    /// Sets the style of the checkbox using the specified [`ToggleStyle`].
 109    pub fn style(mut self, style: ToggleStyle) -> Self {
 110        self.style = style;
 111        self
 112    }
 113
 114    /// Match the style of the checkbox to the current elevation using [`ToggleStyle::ElevationBased`].
 115    pub fn elevation(mut self, elevation: ElevationIndex) -> Self {
 116        self.style = ToggleStyle::ElevationBased(elevation);
 117        self
 118    }
 119
 120    /// Sets the tooltip for the checkbox.
 121    pub fn tooltip(mut self, tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static) -> Self {
 122        self.tooltip = Some(Box::new(tooltip));
 123        self
 124    }
 125
 126    /// Set the label for the checkbox.
 127    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
 128        self.label = Some(label.into());
 129        self
 130    }
 131}
 132
 133impl Checkbox {
 134    fn bg_color(&self, cx: &App) -> Hsla {
 135        let style = self.style.clone();
 136        match (style, self.filled) {
 137            (ToggleStyle::Ghost, false) => cx.theme().colors().ghost_element_background,
 138            (ToggleStyle::Ghost, true) => cx.theme().colors().element_background,
 139            (ToggleStyle::ElevationBased(_), false) => gpui::transparent_black(),
 140            (ToggleStyle::ElevationBased(elevation), true) => elevation.darker_bg(cx),
 141            (ToggleStyle::Custom(_), false) => gpui::transparent_black(),
 142            (ToggleStyle::Custom(color), true) => color.opacity(0.2),
 143        }
 144    }
 145
 146    fn border_color(&self, cx: &App) -> Hsla {
 147        if self.disabled {
 148            return cx.theme().colors().border_variant;
 149        }
 150
 151        match self.style.clone() {
 152            ToggleStyle::Ghost => cx.theme().colors().border,
 153            ToggleStyle::ElevationBased(_) => cx.theme().colors().border,
 154            ToggleStyle::Custom(color) => color.opacity(0.3),
 155        }
 156    }
 157
 158    /// container size
 159    pub fn container_size() -> Pixels {
 160        px(20.0)
 161    }
 162}
 163
 164impl RenderOnce for Checkbox {
 165    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
 166        let group_id = format!("checkbox_group_{:?}", self.id);
 167        let color = if self.disabled {
 168            Color::Disabled
 169        } else {
 170            Color::Selected
 171        };
 172        let icon = match self.toggle_state {
 173            ToggleState::Selected => {
 174                if self.placeholder {
 175                    None
 176                } else {
 177                    Some(
 178                        Icon::new(IconName::Check)
 179                            .size(IconSize::Small)
 180                            .color(color),
 181                    )
 182                }
 183            }
 184            ToggleState::Indeterminate => {
 185                Some(Icon::new(IconName::Dash).size(IconSize::Small).color(color))
 186            }
 187            ToggleState::Unselected => None,
 188        };
 189
 190        let bg_color = self.bg_color(cx);
 191        let border_color = self.border_color(cx);
 192        let hover_border_color = border_color.alpha(0.7);
 193
 194        let size = Self::container_size();
 195
 196        let checkbox = h_flex()
 197            .id(self.id.clone())
 198            .justify_center()
 199            .items_center()
 200            .size(size)
 201            .group(group_id.clone())
 202            .child(
 203                div()
 204                    .flex()
 205                    .flex_none()
 206                    .justify_center()
 207                    .items_center()
 208                    .m_1()
 209                    .size_4()
 210                    .rounded_xs()
 211                    .bg(bg_color)
 212                    .border_1()
 213                    .border_color(border_color)
 214                    .when(self.disabled, |this| this.cursor_not_allowed())
 215                    .when(self.disabled, |this| {
 216                        this.bg(cx.theme().colors().element_disabled.opacity(0.6))
 217                    })
 218                    .when(!self.disabled, |this| {
 219                        this.group_hover(group_id.clone(), |el| el.border_color(hover_border_color))
 220                    })
 221                    .when(self.placeholder, |this| {
 222                        this.child(
 223                            div()
 224                                .flex_none()
 225                                .rounded_full()
 226                                .bg(color.color(cx).alpha(0.5))
 227                                .size(px(4.)),
 228                        )
 229                    })
 230                    .children(icon),
 231            );
 232
 233        h_flex()
 234            .id(self.id)
 235            .gap(DynamicSpacing::Base06.rems(cx))
 236            .child(checkbox)
 237            .when_some(
 238                self.on_click.filter(|_| !self.disabled),
 239                |this, on_click| {
 240                    this.on_click(move |click, window, cx| {
 241                        on_click(&self.toggle_state.inverse(), click, window, cx)
 242                    })
 243                },
 244            )
 245            // TODO: Allow label size to be different from default.
 246            // TODO: Allow label color to be different from muted.
 247            .when_some(self.label, |this, label| {
 248                this.child(Label::new(label).color(Color::Muted))
 249            })
 250            .when_some(self.tooltip, |this, tooltip| {
 251                this.tooltip(move |window, cx| tooltip(window, cx))
 252            })
 253    }
 254}
 255
 256/// A [`Checkbox`] that has a [`Label`].
 257#[derive(IntoElement, RegisterComponent)]
 258pub struct CheckboxWithLabel {
 259    id: ElementId,
 260    label: Label,
 261    checked: ToggleState,
 262    on_click: Arc<dyn Fn(&ToggleState, &mut Window, &mut App) + 'static>,
 263    filled: bool,
 264    style: ToggleStyle,
 265    checkbox_position: IconPosition,
 266}
 267
 268// TODO: Remove `CheckboxWithLabel` now that `label` is a method of `Checkbox`.
 269impl CheckboxWithLabel {
 270    /// Creates a checkbox with an attached label.
 271    pub fn new(
 272        id: impl Into<ElementId>,
 273        label: Label,
 274        checked: ToggleState,
 275        on_click: impl Fn(&ToggleState, &mut Window, &mut App) + 'static,
 276    ) -> Self {
 277        Self {
 278            id: id.into(),
 279            label,
 280            checked,
 281            on_click: Arc::new(on_click),
 282            filled: false,
 283            style: ToggleStyle::default(),
 284            checkbox_position: IconPosition::Start,
 285        }
 286    }
 287
 288    /// Sets the style of the checkbox using the specified [`ToggleStyle`].
 289    pub fn style(mut self, style: ToggleStyle) -> Self {
 290        self.style = style;
 291        self
 292    }
 293
 294    /// Match the style of the checkbox to the current elevation using [`ToggleStyle::ElevationBased`].
 295    pub fn elevation(mut self, elevation: ElevationIndex) -> Self {
 296        self.style = ToggleStyle::ElevationBased(elevation);
 297        self
 298    }
 299
 300    /// Sets the `fill` setting of the checkbox, indicating whether it should be filled.
 301    pub fn fill(mut self) -> Self {
 302        self.filled = true;
 303        self
 304    }
 305
 306    pub fn checkbox_position(mut self, position: IconPosition) -> Self {
 307        self.checkbox_position = position;
 308        self
 309    }
 310}
 311
 312impl RenderOnce for CheckboxWithLabel {
 313    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
 314        h_flex()
 315            .gap(DynamicSpacing::Base08.rems(cx))
 316            .when(self.checkbox_position == IconPosition::Start, |this| {
 317                this.child(
 318                    Checkbox::new(self.id.clone(), self.checked)
 319                        .style(self.style.clone())
 320                        .when(self.filled, Checkbox::fill)
 321                        .on_click({
 322                            let on_click = self.on_click.clone();
 323                            move |checked, window, cx| {
 324                                (on_click)(checked, window, cx);
 325                            }
 326                        }),
 327                )
 328            })
 329            .child(
 330                div()
 331                    .id(SharedString::from(format!("{}-label", self.id)))
 332                    .on_click({
 333                        let on_click = self.on_click.clone();
 334                        move |_event, window, cx| {
 335                            (on_click)(&self.checked.inverse(), window, cx);
 336                        }
 337                    })
 338                    .child(self.label),
 339            )
 340            .when(self.checkbox_position == IconPosition::End, |this| {
 341                this.child(
 342                    Checkbox::new(self.id.clone(), self.checked)
 343                        .style(self.style)
 344                        .when(self.filled, Checkbox::fill)
 345                        .on_click(move |checked, window, cx| {
 346                            (self.on_click)(checked, window, cx);
 347                        }),
 348                )
 349            })
 350    }
 351}
 352
 353/// Defines the color for a switch component.
 354#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Default)]
 355pub enum SwitchColor {
 356    #[default]
 357    Default,
 358    Accent,
 359    Error,
 360    Warning,
 361    Success,
 362    Custom(Hsla),
 363}
 364
 365impl SwitchColor {
 366    fn get_colors(&self, is_on: bool, cx: &App) -> (Hsla, Hsla) {
 367        if !is_on {
 368            return (
 369                cx.theme().colors().element_disabled,
 370                cx.theme().colors().border,
 371            );
 372        }
 373
 374        match self {
 375            SwitchColor::Default => {
 376                let colors = cx.theme().colors();
 377                let base_color = colors.text;
 378                let bg_color = colors.element_background.blend(base_color.opacity(0.08));
 379                (bg_color, colors.border_variant)
 380            }
 381            SwitchColor::Accent => {
 382                let status = cx.theme().status();
 383                (status.info.opacity(0.4), status.info.opacity(0.2))
 384            }
 385            SwitchColor::Error => {
 386                let status = cx.theme().status();
 387                (status.error.opacity(0.4), status.error.opacity(0.2))
 388            }
 389            SwitchColor::Warning => {
 390                let status = cx.theme().status();
 391                (status.warning.opacity(0.4), status.warning.opacity(0.2))
 392            }
 393            SwitchColor::Success => {
 394                let status = cx.theme().status();
 395                (status.success.opacity(0.4), status.success.opacity(0.2))
 396            }
 397            SwitchColor::Custom(color) => (*color, color.opacity(0.6)),
 398        }
 399    }
 400}
 401
 402impl From<SwitchColor> for Color {
 403    fn from(color: SwitchColor) -> Self {
 404        match color {
 405            SwitchColor::Default => Color::Default,
 406            SwitchColor::Accent => Color::Accent,
 407            SwitchColor::Error => Color::Error,
 408            SwitchColor::Warning => Color::Warning,
 409            SwitchColor::Success => Color::Success,
 410            SwitchColor::Custom(_) => Color::Default,
 411        }
 412    }
 413}
 414
 415/// # Switch
 416///
 417/// Switches are used to represent opposite states, such as enabled or disabled.
 418#[derive(IntoElement, RegisterComponent)]
 419pub struct Switch {
 420    id: ElementId,
 421    toggle_state: ToggleState,
 422    disabled: bool,
 423    on_click: Option<Box<dyn Fn(&ToggleState, &mut Window, &mut App) + 'static>>,
 424    label: Option<SharedString>,
 425    key_binding: Option<KeyBinding>,
 426    color: SwitchColor,
 427    tab_index: Option<isize>,
 428}
 429
 430impl Switch {
 431    /// Creates a new [`Switch`].
 432    pub fn new(id: impl Into<ElementId>, state: ToggleState) -> Self {
 433        Self {
 434            id: id.into(),
 435            toggle_state: state,
 436            disabled: false,
 437            on_click: None,
 438            label: None,
 439            key_binding: None,
 440            color: SwitchColor::default(),
 441            tab_index: None,
 442        }
 443    }
 444
 445    /// Sets the color of the switch using the specified [`SwitchColor`].
 446    pub fn color(mut self, color: SwitchColor) -> Self {
 447        self.color = color;
 448        self
 449    }
 450
 451    /// Sets the disabled state of the [`Switch`].
 452    pub fn disabled(mut self, disabled: bool) -> Self {
 453        self.disabled = disabled;
 454        self
 455    }
 456
 457    /// Binds a handler to the [`Switch`] that will be called when clicked.
 458    pub fn on_click(
 459        mut self,
 460        handler: impl Fn(&ToggleState, &mut Window, &mut App) + 'static,
 461    ) -> Self {
 462        self.on_click = Some(Box::new(handler));
 463        self
 464    }
 465
 466    /// Sets the label of the [`Switch`].
 467    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
 468        self.label = Some(label.into());
 469        self
 470    }
 471
 472    /// Display the keybinding that triggers the switch action.
 473    pub fn key_binding(mut self, key_binding: impl Into<Option<KeyBinding>>) -> Self {
 474        self.key_binding = key_binding.into();
 475        self
 476    }
 477
 478    pub fn tab_index(mut self, tab_index: impl Into<isize>) -> Self {
 479        self.tab_index = Some(tab_index.into());
 480        self
 481    }
 482}
 483
 484impl RenderOnce for Switch {
 485    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
 486        let is_on = self.toggle_state == ToggleState::Selected;
 487        let adjust_ratio = if is_light(cx) { 1.5 } else { 1.0 };
 488
 489        let base_color = cx.theme().colors().text;
 490        let thumb_color = base_color;
 491        let (bg_color, border_color) = self.color.get_colors(is_on, cx);
 492
 493        let bg_hover_color = if is_on {
 494            bg_color.blend(base_color.opacity(0.16 * adjust_ratio))
 495        } else {
 496            bg_color.blend(base_color.opacity(0.05 * adjust_ratio))
 497        };
 498
 499        let thumb_opacity = match (is_on, self.disabled) {
 500            (_, true) => 0.2,
 501            (true, false) => 1.0,
 502            (false, false) => 0.5,
 503        };
 504
 505        let group_id = format!("switch_group_{:?}", self.id);
 506
 507        let switch = div()
 508            .id((self.id.clone(), "switch"))
 509            .p(px(1.0))
 510            .border_2()
 511            .border_color(cx.theme().colors().border_transparent)
 512            .rounded_full()
 513            .when_some(
 514                self.tab_index.filter(|_| !self.disabled),
 515                |this, tab_index| {
 516                    this.tab_index(tab_index).focus(|mut style| {
 517                        style.border_color = Some(cx.theme().colors().border_focused);
 518                        style
 519                    })
 520                },
 521            )
 522            .child(
 523                h_flex()
 524                    .w(DynamicSpacing::Base32.rems(cx))
 525                    .h(DynamicSpacing::Base20.rems(cx))
 526                    .group(group_id.clone())
 527                    .child(
 528                        h_flex()
 529                            .when(is_on, |on| on.justify_end())
 530                            .when(!is_on, |off| off.justify_start())
 531                            .size_full()
 532                            .rounded_full()
 533                            .px(DynamicSpacing::Base02.px(cx))
 534                            .bg(bg_color)
 535                            .when(!self.disabled, |this| {
 536                                this.group_hover(group_id.clone(), |el| el.bg(bg_hover_color))
 537                            })
 538                            .border_1()
 539                            .border_color(border_color)
 540                            .child(
 541                                div()
 542                                    .size(DynamicSpacing::Base12.rems(cx))
 543                                    .rounded_full()
 544                                    .bg(thumb_color)
 545                                    .opacity(thumb_opacity),
 546                            ),
 547                    ),
 548            );
 549
 550        h_flex()
 551            .id(self.id)
 552            .gap(DynamicSpacing::Base06.rems(cx))
 553            .cursor_pointer()
 554            .child(switch)
 555            .when_some(
 556                self.on_click.filter(|_| !self.disabled),
 557                |this, on_click| {
 558                    this.on_click(move |_, window, cx| {
 559                        on_click(&self.toggle_state.inverse(), window, cx)
 560                    })
 561                },
 562            )
 563            .when_some(self.label, |this, label| {
 564                this.child(Label::new(label).size(LabelSize::Small))
 565            })
 566            .children(self.key_binding)
 567    }
 568}
 569
 570/// # SwitchField
 571///
 572/// A field component that combines a label, description, and switch into one reusable component.
 573///
 574/// # Examples
 575///
 576/// ```
 577/// use ui::prelude::*;
 578///
 579/// SwitchField::new(
 580///     "feature-toggle",
 581///     "Enable feature",
 582///     "This feature adds new functionality to the app.",
 583///     ToggleState::Unselected,
 584///     |state, window, cx| {
 585///         // Logic here
 586///     }
 587/// );
 588/// ```
 589#[derive(IntoElement, RegisterComponent)]
 590pub struct SwitchField {
 591    id: ElementId,
 592    label: SharedString,
 593    description: Option<SharedString>,
 594    toggle_state: ToggleState,
 595    on_click: Arc<dyn Fn(&ToggleState, &mut Window, &mut App) + 'static>,
 596    disabled: bool,
 597    color: SwitchColor,
 598    tooltip: Option<Rc<dyn Fn(&mut Window, &mut App) -> AnyView>>,
 599    tab_index: Option<isize>,
 600}
 601
 602impl SwitchField {
 603    pub fn new(
 604        id: impl Into<ElementId>,
 605        label: impl Into<SharedString>,
 606        description: Option<SharedString>,
 607        toggle_state: impl Into<ToggleState>,
 608        on_click: impl Fn(&ToggleState, &mut Window, &mut App) + 'static,
 609    ) -> Self {
 610        Self {
 611            id: id.into(),
 612            label: label.into(),
 613            description: description,
 614            toggle_state: toggle_state.into(),
 615            on_click: Arc::new(on_click),
 616            disabled: false,
 617            color: SwitchColor::Accent,
 618            tooltip: None,
 619            tab_index: None,
 620        }
 621    }
 622
 623    pub fn description(mut self, description: impl Into<SharedString>) -> Self {
 624        self.description = Some(description.into());
 625        self
 626    }
 627
 628    pub fn disabled(mut self, disabled: bool) -> Self {
 629        self.disabled = disabled;
 630        self
 631    }
 632
 633    /// Sets the color of the switch using the specified [`SwitchColor`].
 634    /// This changes the color scheme of the switch when it's in the "on" state.
 635    pub fn color(mut self, color: SwitchColor) -> Self {
 636        self.color = color;
 637        self
 638    }
 639
 640    pub fn tooltip(mut self, tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static) -> Self {
 641        self.tooltip = Some(Rc::new(tooltip));
 642        self
 643    }
 644
 645    pub fn tab_index(mut self, tab_index: isize) -> Self {
 646        self.tab_index = Some(tab_index);
 647        self
 648    }
 649}
 650
 651impl RenderOnce for SwitchField {
 652    fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
 653        let tooltip = self.tooltip.map(|tooltip_fn| {
 654            h_flex()
 655                .gap_0p5()
 656                .child(Label::new(self.label.clone()))
 657                .child(
 658                    IconButton::new("tooltip_button", IconName::Info)
 659                        .icon_size(IconSize::XSmall)
 660                        .icon_color(Color::Muted)
 661                        .shape(crate::IconButtonShape::Square)
 662                        .tooltip({
 663                            let tooltip = tooltip_fn.clone();
 664                            move |window, cx| tooltip(window, cx)
 665                        }),
 666                )
 667        });
 668
 669        h_flex()
 670            .id((self.id.clone(), "container"))
 671            .when(!self.disabled, |this| {
 672                this.hover(|this| this.cursor_pointer())
 673            })
 674            .w_full()
 675            .gap_4()
 676            .justify_between()
 677            .flex_wrap()
 678            .child(match (&self.description, tooltip) {
 679                (Some(description), Some(tooltip)) => v_flex()
 680                    .gap_0p5()
 681                    .max_w_5_6()
 682                    .child(tooltip)
 683                    .child(Label::new(description.clone()).color(Color::Muted))
 684                    .into_any_element(),
 685                (Some(description), None) => v_flex()
 686                    .gap_0p5()
 687                    .max_w_5_6()
 688                    .child(Label::new(self.label.clone()))
 689                    .child(Label::new(description.clone()).color(Color::Muted))
 690                    .into_any_element(),
 691                (None, Some(tooltip)) => tooltip.into_any_element(),
 692                (None, None) => Label::new(self.label.clone()).into_any_element(),
 693            })
 694            .child(
 695                Switch::new((self.id.clone(), "switch"), self.toggle_state)
 696                    .color(self.color)
 697                    .disabled(self.disabled)
 698                    .when_some(
 699                        self.tab_index.filter(|_| !self.disabled),
 700                        |this, tab_index| this.tab_index(tab_index),
 701                    )
 702                    .on_click({
 703                        let on_click = self.on_click.clone();
 704                        move |state, window, cx| {
 705                            (on_click)(state, window, cx);
 706                        }
 707                    }),
 708            )
 709            .when(!self.disabled, |this| {
 710                this.on_click({
 711                    let on_click = self.on_click.clone();
 712                    let toggle_state = self.toggle_state;
 713                    move |_click, window, cx| {
 714                        (on_click)(&toggle_state.inverse(), window, cx);
 715                    }
 716                })
 717            })
 718    }
 719}
 720
 721impl Component for SwitchField {
 722    fn scope() -> ComponentScope {
 723        ComponentScope::Input
 724    }
 725
 726    fn description() -> Option<&'static str> {
 727        Some("A field component that combines a label, description, and switch")
 728    }
 729
 730    fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
 731        Some(
 732            v_flex()
 733                .gap_6()
 734                .children(vec![
 735                    example_group_with_title(
 736                        "States",
 737                        vec![
 738                            single_example(
 739                                "Unselected",
 740                                SwitchField::new(
 741                                    "switch_field_unselected",
 742                                    "Enable notifications",
 743                                    Some("Receive notifications when new messages arrive.".into()),
 744                                    ToggleState::Unselected,
 745                                    |_, _, _| {},
 746                                )
 747                                .into_any_element(),
 748                            ),
 749                            single_example(
 750                                "Selected",
 751                                SwitchField::new(
 752                                    "switch_field_selected",
 753                                    "Enable notifications",
 754                                    Some("Receive notifications when new messages arrive.".into()),
 755                                    ToggleState::Selected,
 756                                    |_, _, _| {},
 757                                )
 758                                .into_any_element(),
 759                            ),
 760                        ],
 761                    ),
 762                    example_group_with_title(
 763                        "Colors",
 764                        vec![
 765                            single_example(
 766                                "Default",
 767                                SwitchField::new(
 768                                    "switch_field_default",
 769                                    "Default color",
 770                                    Some("This uses the default switch color.".into()),
 771                                    ToggleState::Selected,
 772                                    |_, _, _| {},
 773                                )
 774                                .into_any_element(),
 775                            ),
 776                            single_example(
 777                                "Accent",
 778                                SwitchField::new(
 779                                    "switch_field_accent",
 780                                    "Accent color",
 781                                    Some("This uses the accent color scheme.".into()),
 782                                    ToggleState::Selected,
 783                                    |_, _, _| {},
 784                                )
 785                                .color(SwitchColor::Accent)
 786                                .into_any_element(),
 787                            ),
 788                        ],
 789                    ),
 790                    example_group_with_title(
 791                        "Disabled",
 792                        vec![single_example(
 793                            "Disabled",
 794                            SwitchField::new(
 795                                "switch_field_disabled",
 796                                "Disabled field",
 797                                Some("This field is disabled and cannot be toggled.".into()),
 798                                ToggleState::Selected,
 799                                |_, _, _| {},
 800                            )
 801                            .disabled(true)
 802                            .into_any_element(),
 803                        )],
 804                    ),
 805                    example_group_with_title(
 806                        "No Description",
 807                        vec![single_example(
 808                            "No Description",
 809                            SwitchField::new(
 810                                "switch_field_disabled",
 811                                "Disabled field",
 812                                None,
 813                                ToggleState::Selected,
 814                                |_, _, _| {},
 815                            )
 816                            .into_any_element(),
 817                        )],
 818                    ),
 819                    example_group_with_title(
 820                        "With Tooltip",
 821                        vec![
 822                            single_example(
 823                                "Tooltip with Description",
 824                                SwitchField::new(
 825                                    "switch_field_tooltip_with_desc",
 826                                    "Nice Feature",
 827                                    Some("Enable advanced configuration options.".into()),
 828                                    ToggleState::Unselected,
 829                                    |_, _, _| {},
 830                                )
 831                                .tooltip(Tooltip::text("This is content for this tooltip!"))
 832                                .into_any_element(),
 833                            ),
 834                            single_example(
 835                                "Tooltip without Description",
 836                                SwitchField::new(
 837                                    "switch_field_tooltip_no_desc",
 838                                    "Nice Feature",
 839                                    None,
 840                                    ToggleState::Selected,
 841                                    |_, _, _| {},
 842                                )
 843                                .tooltip(Tooltip::text("This is content for this tooltip!"))
 844                                .into_any_element(),
 845                            ),
 846                        ],
 847                    ),
 848                ])
 849                .into_any_element(),
 850        )
 851    }
 852}
 853
 854impl Component for Checkbox {
 855    fn scope() -> ComponentScope {
 856        ComponentScope::Input
 857    }
 858
 859    fn description() -> Option<&'static str> {
 860        Some("A checkbox component that can be used for multiple choice selections")
 861    }
 862
 863    fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
 864        Some(
 865            v_flex()
 866                .gap_6()
 867                .children(vec![
 868                    example_group_with_title(
 869                        "States",
 870                        vec![
 871                            single_example(
 872                                "Unselected",
 873                                Checkbox::new("checkbox_unselected", ToggleState::Unselected)
 874                                    .into_any_element(),
 875                            ),
 876                            single_example(
 877                                "Placeholder",
 878                                Checkbox::new("checkbox_indeterminate", ToggleState::Selected)
 879                                    .placeholder(true)
 880                                    .into_any_element(),
 881                            ),
 882                            single_example(
 883                                "Indeterminate",
 884                                Checkbox::new("checkbox_indeterminate", ToggleState::Indeterminate)
 885                                    .into_any_element(),
 886                            ),
 887                            single_example(
 888                                "Selected",
 889                                Checkbox::new("checkbox_selected", ToggleState::Selected)
 890                                    .into_any_element(),
 891                            ),
 892                        ],
 893                    ),
 894                    example_group_with_title(
 895                        "Styles",
 896                        vec![
 897                            single_example(
 898                                "Default",
 899                                Checkbox::new("checkbox_default", ToggleState::Selected)
 900                                    .into_any_element(),
 901                            ),
 902                            single_example(
 903                                "Filled",
 904                                Checkbox::new("checkbox_filled", ToggleState::Selected)
 905                                    .fill()
 906                                    .into_any_element(),
 907                            ),
 908                            single_example(
 909                                "ElevationBased",
 910                                Checkbox::new("checkbox_elevation", ToggleState::Selected)
 911                                    .style(ToggleStyle::ElevationBased(
 912                                        ElevationIndex::EditorSurface,
 913                                    ))
 914                                    .into_any_element(),
 915                            ),
 916                            single_example(
 917                                "Custom Color",
 918                                Checkbox::new("checkbox_custom", ToggleState::Selected)
 919                                    .style(ToggleStyle::Custom(hsla(142.0 / 360., 0.68, 0.45, 0.7)))
 920                                    .into_any_element(),
 921                            ),
 922                        ],
 923                    ),
 924                    example_group_with_title(
 925                        "Disabled",
 926                        vec![
 927                            single_example(
 928                                "Unselected",
 929                                Checkbox::new(
 930                                    "checkbox_disabled_unselected",
 931                                    ToggleState::Unselected,
 932                                )
 933                                .disabled(true)
 934                                .into_any_element(),
 935                            ),
 936                            single_example(
 937                                "Selected",
 938                                Checkbox::new("checkbox_disabled_selected", ToggleState::Selected)
 939                                    .disabled(true)
 940                                    .into_any_element(),
 941                            ),
 942                        ],
 943                    ),
 944                    example_group_with_title(
 945                        "With Label",
 946                        vec![single_example(
 947                            "Default",
 948                            Checkbox::new("checkbox_with_label", ToggleState::Selected)
 949                                .label("Always save on quit")
 950                                .into_any_element(),
 951                        )],
 952                    ),
 953                ])
 954                .into_any_element(),
 955        )
 956    }
 957}
 958
 959impl Component for Switch {
 960    fn scope() -> ComponentScope {
 961        ComponentScope::Input
 962    }
 963
 964    fn description() -> Option<&'static str> {
 965        Some("A switch component that represents binary states like on/off")
 966    }
 967
 968    fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
 969        Some(
 970            v_flex()
 971                .gap_6()
 972                .children(vec![
 973                    example_group_with_title(
 974                        "States",
 975                        vec![
 976                            single_example(
 977                                "Off",
 978                                Switch::new("switch_off", ToggleState::Unselected)
 979                                    .on_click(|_, _, _cx| {})
 980                                    .into_any_element(),
 981                            ),
 982                            single_example(
 983                                "On",
 984                                Switch::new("switch_on", ToggleState::Selected)
 985                                    .on_click(|_, _, _cx| {})
 986                                    .into_any_element(),
 987                            ),
 988                        ],
 989                    ),
 990                    example_group_with_title(
 991                        "Colors",
 992                        vec![
 993                            single_example(
 994                                "Default",
 995                                Switch::new("switch_default_style", ToggleState::Selected)
 996                                    .color(SwitchColor::Default)
 997                                    .on_click(|_, _, _cx| {})
 998                                    .into_any_element(),
 999                            ),
1000                            single_example(
1001                                "Accent",
1002                                Switch::new("switch_accent_style", ToggleState::Selected)
1003                                    .color(SwitchColor::Accent)
1004                                    .on_click(|_, _, _cx| {})
1005                                    .into_any_element(),
1006                            ),
1007                            single_example(
1008                                "Error",
1009                                Switch::new("switch_error_style", ToggleState::Selected)
1010                                    .color(SwitchColor::Error)
1011                                    .on_click(|_, _, _cx| {})
1012                                    .into_any_element(),
1013                            ),
1014                            single_example(
1015                                "Warning",
1016                                Switch::new("switch_warning_style", ToggleState::Selected)
1017                                    .color(SwitchColor::Warning)
1018                                    .on_click(|_, _, _cx| {})
1019                                    .into_any_element(),
1020                            ),
1021                            single_example(
1022                                "Success",
1023                                Switch::new("switch_success_style", ToggleState::Selected)
1024                                    .color(SwitchColor::Success)
1025                                    .on_click(|_, _, _cx| {})
1026                                    .into_any_element(),
1027                            ),
1028                            single_example(
1029                                "Custom",
1030                                Switch::new("switch_custom_style", ToggleState::Selected)
1031                                    .color(SwitchColor::Custom(hsla(300.0 / 360.0, 0.6, 0.6, 1.0)))
1032                                    .on_click(|_, _, _cx| {})
1033                                    .into_any_element(),
1034                            ),
1035                        ],
1036                    ),
1037                    example_group_with_title(
1038                        "Disabled",
1039                        vec![
1040                            single_example(
1041                                "Off",
1042                                Switch::new("switch_disabled_off", ToggleState::Unselected)
1043                                    .disabled(true)
1044                                    .into_any_element(),
1045                            ),
1046                            single_example(
1047                                "On",
1048                                Switch::new("switch_disabled_on", ToggleState::Selected)
1049                                    .disabled(true)
1050                                    .into_any_element(),
1051                            ),
1052                        ],
1053                    ),
1054                    example_group_with_title(
1055                        "With Label",
1056                        vec![
1057                            single_example(
1058                                "Label",
1059                                Switch::new("switch_with_label", ToggleState::Selected)
1060                                    .label("Always save on quit")
1061                                    .into_any_element(),
1062                            ),
1063                            // TODO: Where did theme_preview_keybinding go?
1064                            // single_example(
1065                            //     "Keybinding",
1066                            //     Switch::new("switch_with_keybinding", ToggleState::Selected)
1067                            //         .key_binding(theme_preview_keybinding("cmd-shift-e"))
1068                            //         .into_any_element(),
1069                            // ),
1070                        ],
1071                    ),
1072                ])
1073                .into_any_element(),
1074        )
1075    }
1076}
1077
1078impl Component for CheckboxWithLabel {
1079    fn scope() -> ComponentScope {
1080        ComponentScope::Input
1081    }
1082
1083    fn description() -> Option<&'static str> {
1084        Some("A checkbox component with an attached label")
1085    }
1086
1087    fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
1088        Some(
1089            v_flex()
1090                .gap_6()
1091                .children(vec![example_group_with_title(
1092                    "States",
1093                    vec![
1094                        single_example(
1095                            "Unselected",
1096                            CheckboxWithLabel::new(
1097                                "checkbox_with_label_unselected",
1098                                Label::new("Always save on quit"),
1099                                ToggleState::Unselected,
1100                                |_, _, _| {},
1101                            )
1102                            .into_any_element(),
1103                        ),
1104                        single_example(
1105                            "Indeterminate",
1106                            CheckboxWithLabel::new(
1107                                "checkbox_with_label_indeterminate",
1108                                Label::new("Always save on quit"),
1109                                ToggleState::Indeterminate,
1110                                |_, _, _| {},
1111                            )
1112                            .into_any_element(),
1113                        ),
1114                        single_example(
1115                            "Selected",
1116                            CheckboxWithLabel::new(
1117                                "checkbox_with_label_selected",
1118                                Label::new("Always save on quit"),
1119                                ToggleState::Selected,
1120                                |_, _, _| {},
1121                            )
1122                            .into_any_element(),
1123                        ),
1124                    ],
1125                )])
1126                .into_any_element(),
1127        )
1128    }
1129}