1use crate::{
2 ActiveTheme, Disableable, Side, Sizable, Size, StyledExt, text::Text, tooltip::ComponentTooltip,
3};
4use gpui::{
5 App, Background, ElementId, Hsla, InteractiveElement, IntoElement, ParentElement as _,
6 RenderOnce, SharedString, StyleRefinement, Styled, Window, div, prelude::FluentBuilder as _,
7 px,
8};
9use gpui_base::{Spring, Switch as BaseSwitch, SwitchThumb, SwitchTrack, spring};
10use std::{rc::Rc, time::Duration};
11
12const THUMB_SPRING: Spring = Spring::new(Duration::from_millis(180)).with_epsilon(0.1);
17
18#[derive(IntoElement)]
20pub struct Switch {
21 id: ElementId,
22 style: StyleRefinement,
23 checked: bool,
24 disabled: bool,
25 label: Option<Text>,
26 accessibility_label: Option<SharedString>,
28 label_side: Side,
29 on_click: Option<Rc<dyn Fn(&bool, &mut Window, &mut App)>>,
30 size: Size,
31 color: Option<Hsla>,
32 tooltip: ComponentTooltip,
33}
34
35impl Switch {
36 pub fn new(id: impl Into<ElementId>) -> Self {
38 let id: ElementId = id.into();
39 Self {
40 id: id.clone(),
41 style: StyleRefinement::default(),
42 checked: false,
43 disabled: false,
44 label: None,
45 accessibility_label: None,
46 on_click: None,
47 label_side: Side::Right,
48 size: Size::Medium,
49 color: None,
50 tooltip: ComponentTooltip::default(),
51 }
52 }
53
54 pub fn checked(mut self, checked: bool) -> Self {
56 self.checked = checked;
57 self
58 }
59
60 pub fn label(mut self, label: impl Into<Text>) -> Self {
62 self.label = Some(label.into());
63 self
64 }
65
66 pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
73 self.accessibility_label = Some(label.into());
74 self
75 }
76
77 pub fn on_click<F>(mut self, handler: F) -> Self
79 where
80 F: Fn(&bool, &mut Window, &mut App) + 'static,
81 {
82 self.on_click = Some(Rc::new(handler));
83 self
84 }
85
86 pub fn color(mut self, color: impl Into<Hsla>) -> Self {
89 self.color = Some(color.into());
90 self
91 }
92
93 pub fn tooltip(mut self, tooltip: impl Into<SharedString>) -> Self {
95 self.tooltip.text = Some((tooltip.into(), None));
96 self
97 }
98}
99
100impl Styled for Switch {
101 fn style(&mut self) -> &mut gpui::StyleRefinement {
102 &mut self.style
103 }
104}
105
106impl Sizable for Switch {
107 fn with_size(mut self, size: impl Into<Size>) -> Self {
108 self.size = size.into();
109 self
110 }
111}
112
113impl Disableable for Switch {
114 fn disabled(mut self, disabled: bool) -> Self {
115 self.disabled = disabled;
116 self
117 }
118}
119
120impl RenderOnce for Switch {
121 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
122 let checked = self.checked;
123 let on_click = self.on_click.clone();
124 let accessibility_label = self
125 .accessibility_label
126 .clone()
127 .or_else(|| self.label.as_ref().map(|label| label.get_text(cx)));
128
129 let checked_bg = self
130 .color
131 .map(Background::from)
132 .unwrap_or(cx.theme().tokens.primary.into());
133 let unchecked_bg: Background = cx.theme().tokens.switch.into();
134 let disabled_checked_bg = checked_bg.clone().opacity(0.5);
135 let toggle_bg: Background = cx.theme().tokens.switch_thumb.into();
136
137 let (bg_width, bg_height) = match self.size {
138 Size::XSmall | Size::Small => (px(28.), px(16.)),
139 _ => (px(36.), px(20.)),
140 };
141 let bar_width = match self.size {
142 Size::XSmall | Size::Small => px(12.),
143 _ => px(16.),
144 };
145 let inset = px(2.);
146 let radius = if cx.theme().radius >= px(4.) {
147 bg_height
148 } else {
149 cx.theme().radius
150 };
151
152 let thumb_x = spring(
158 (self.id.clone(), "thumb"),
159 if checked {
160 bg_width - bar_width - inset * 2
161 } else {
162 px(0.)
163 },
164 THUMB_SPRING,
165 window,
166 cx,
167 );
168
169 div().refine_style(&self.style).child(
170 BaseSwitch::new(self.id.clone())
171 .checked(checked)
172 .disabled(self.disabled)
173 .when_some(accessibility_label, |this, label| {
174 this.accessibility_label(label)
175 })
176 .when_some(on_click, |this, on_click| {
177 this.on_change(move |next, _, window, cx| on_click(&next, window, cx))
178 })
179 .h_flex()
180 .gap_2()
181 .items_start()
182 .when(self.label_side.is_left(), |this| this.flex_row_reverse())
183 .child(
184 SwitchTrack::new((self.id.clone(), "track"))
186 .checked(checked)
187 .disabled(self.disabled)
188 .when(cfg!(test), |this| {
189 this.debug_selector(|| "switch-bar".into())
190 })
191 .w(bg_width)
192 .h(bg_height)
193 .rounded(radius)
194 .flex()
195 .items_center()
196 .border(inset)
197 .border_color(cx.theme().transparent)
198 .when(!checked, |this| this.bg(unchecked_bg))
199 .styles(|styles| {
200 styles
201 .checked(|style| style.bg(checked_bg))
202 .disabled(|style| {
203 style.when(checked, |style| style.bg(disabled_checked_bg))
204 })
205 })
206 .map(|this| self.tooltip.apply(this))
207 .child(
208 SwitchThumb::new(checked)
210 .disabled(self.disabled)
211 .rounded(radius)
212 .size(bar_width)
213 .left(thumb_x)
214 .when(!self.disabled, |this| this.bg(toggle_bg))
215 .styles(|styles| {
216 styles
217 .disabled(|style| style.bg(toggle_bg.clone().opacity(0.35)))
218 }),
219 ),
220 )
221 .when_some(self.label, |this, label| {
222 this.child(
223 div()
224 .when(cfg!(test), |this| {
225 this.debug_selector(|| "switch-label".into())
226 })
227 .line_height(bg_height)
228 .child(label)
229 .map(|this| match self.size {
230 Size::XSmall | Size::Small => this.text_sm(),
231 _ => this.text_base(),
232 }),
233 )
234 }),
235 )
236 }
237}
238
239#[cfg(test)]
240mod tests {
241 use std::{cell::Cell, rc::Rc};
242
243 use gpui::{
244 Context, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, Render,
245 StatefulInteractiveElement as _, TestAppContext, VisualTestContext, point,
246 };
247
248 use super::*;
249
250 #[test]
251 fn an_explicit_accessibility_label_replaces_the_visible_one() {
252 let plain = Switch::new("wifi").label("Wi-Fi");
253 assert_eq!(plain.accessibility_label, None);
254 assert!(matches!(
255 &plain.label,
256 Some(Text::String(label)) if label.as_ref() == "Wi-Fi"
257 ));
258
259 let named = Switch::new("wifi")
260 .label("Wi-Fi")
261 .accessibility_label("Toggle Wi-Fi");
262 assert_eq!(
263 named.accessibility_label.as_deref(),
264 Some("Toggle Wi-Fi"),
265 "an explicit name must win over the visible label"
266 );
267 assert!(
268 matches!(
269 &named.label,
270 Some(Text::String(label)) if label.as_ref() == "Wi-Fi"
271 ),
272 "and must not change what is drawn"
273 );
274 }
275
276 struct SwitchHarness {
277 disabled: bool,
278 toggles: Rc<Cell<usize>>,
279 parent_clicks: Rc<Cell<usize>>,
280 }
281
282 impl Render for SwitchHarness {
283 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
284 let toggles = self.toggles.clone();
285 let parent_clicks = self.parent_clicks.clone();
286 div()
287 .id("switch-parent")
288 .tab_group()
289 .size(px(100.))
290 .on_click(move |_, _, _| parent_clicks.set(parent_clicks.get() + 1))
291 .child(Switch::new("switch").disabled(self.disabled).on_click(
292 move |checked, _, _| {
293 assert!(*checked);
294 toggles.set(toggles.get() + 1);
295 },
296 ))
297 }
298 }
299
300 fn harness(
301 cx: &mut TestAppContext,
302 disabled: bool,
303 ) -> (&mut VisualTestContext, Rc<Cell<usize>>, Rc<Cell<usize>>) {
304 cx.update(crate::init);
305 let toggles = Rc::new(Cell::new(0));
306 let parent_clicks = Rc::new(Cell::new(0));
307 let (_, cx) = cx.add_window_view({
308 let toggles = toggles.clone();
309 let parent_clicks = parent_clicks.clone();
310 move |_, _| SwitchHarness {
311 disabled,
312 toggles,
313 parent_clicks,
314 }
315 });
316 cx.update(|window, cx| window.draw(cx).clear(cx));
317 (cx, toggles, parent_clicks)
318 }
319
320 fn activate_key(cx: &mut VisualTestContext, key: &str) {
321 let keystroke = Keystroke::parse(key).unwrap();
322 cx.simulate_event(KeyDownEvent {
323 keystroke: keystroke.clone(),
324 is_held: false,
325 prefer_character_input: false,
326 });
327 cx.simulate_event(KeyUpEvent { keystroke });
328 }
329
330 #[gpui::test]
331 fn canonical_pointer_activation_fires_once_and_focuses(cx: &mut TestAppContext) {
332 let (cx, toggles, _) = harness(cx, false);
333 cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
334
335 assert_eq!(toggles.get(), 1);
336 cx.update(|window, cx| assert!(window.focused(cx).is_some()));
337 }
338
339 #[gpui::test]
340 fn canonical_switch_supports_tab_enter_and_space(cx: &mut TestAppContext) {
341 let (cx, toggles, _) = harness(cx, false);
342 cx.update(|window, cx| window.focus_next(cx));
343 cx.update(|window, cx| assert!(window.focused(cx).is_some()));
344
345 activate_key(cx, "enter");
346 activate_key(cx, "space");
347
348 assert_eq!(toggles.get(), 2);
349 }
350
351 #[gpui::test]
352 fn canonical_disabled_switch_is_inert_and_blocks_parent(cx: &mut TestAppContext) {
353 let (cx, toggles, parent_clicks) = harness(cx, true);
354 cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
355
356 assert_eq!(toggles.get(), 0);
357 assert_eq!(parent_clicks.get(), 0);
358 cx.update(|window, cx| assert!(window.focused(cx).is_none()));
359 }
360
361 #[gpui::test]
362 fn label_prepaints_with_the_base_switch_content(cx: &mut TestAppContext) {
363 struct LabelHarness;
364
365 impl Render for LabelHarness {
366 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
367 div()
368 .debug_selector(|| "labeled-switch".into())
369 .child(Switch::new("switch").label("Airplane mode"))
370 }
371 }
372
373 cx.update(crate::init);
374 let (_, cx) = cx.add_window_view(|_, _| LabelHarness);
375 cx.update(|window, cx| window.draw(cx).clear(cx));
376
377 let bounds = cx
378 .debug_bounds("labeled-switch")
379 .expect("the complete labeled Switch must participate in prepaint");
380 assert!(bounds.size.width > px(36.));
381 let bar = cx
382 .debug_bounds("switch-bar")
383 .expect("the Switch bar must participate in prepaint");
384 let label = cx
385 .debug_bounds("switch-label")
386 .expect("the Switch label must participate in prepaint");
387 assert_eq!(bar.origin.y, label.origin.y);
388 }
389}