toggle.rs

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