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