1use std::rc::Rc;
6
7use gpui::{
8 AnyElement, App, ClickEvent, Div, ElementId, FocusHandle, InteractiveElement, Interactivity,
9 IntoElement, MouseButton, ParentElement, Refineable as _, RenderOnce, Role, SharedString,
10 Stateful, StatefulInteractiveElement, StyleRefinement, Styled, Toggled, Window, div,
11 prelude::FluentBuilder as _,
12};
13use smallvec::SmallVec;
14
15use crate::{StateStyle, StyledExt as _, TestSupportExt as _, a11y_disabled::A11yDisabledExt as _};
16
17type ChangeHandler = Rc<dyn Fn(bool, &ClickEvent, &mut Window, &mut App)>;
18
19#[derive(IntoElement)]
26pub struct Switch {
27 id: ElementId,
28 base: crate::ObservedElement<Stateful<Div>>,
29 style: StyleRefinement,
30 semantic_styles: SwitchStyles,
31 checked: bool,
32 disabled: bool,
33 children: SmallVec<[AnyElement; 2]>,
34 on_change: Option<ChangeHandler>,
35 accessibility_label: Option<SharedString>,
36 field: crate::FieldMetadata,
37 tab_index: isize,
38 tab_stop: bool,
39 provided_focus_handle: Option<FocusHandle>,
40}
41
42#[derive(Default)]
44pub struct SwitchStyles {
45 checked: StyleRefinement,
46 disabled: StyleRefinement,
47}
48
49impl SwitchStyles {
50 pub fn checked(mut self, build: impl FnOnce(StateStyle) -> StateStyle) -> Self {
52 self.checked
53 .refine(&build(StateStyle::default()).into_refinement());
54 self
55 }
56
57 pub fn disabled(mut self, build: impl FnOnce(StateStyle) -> StateStyle) -> Self {
59 self.disabled
60 .refine(&build(StateStyle::default()).into_refinement());
61 self
62 }
63}
64
65impl Switch {
66 pub fn new(id: impl Into<ElementId>) -> Self {
67 let id = id.into();
68 Self {
69 base: div().id(id.clone()).test_support(),
70 id,
71 style: StyleRefinement::default(),
72 semantic_styles: SwitchStyles::default(),
73 checked: false,
74 disabled: false,
75 children: SmallVec::new(),
76 on_change: None,
77 accessibility_label: None,
78 field: crate::FieldMetadata::default(),
79 tab_index: 0,
80 tab_stop: true,
81 provided_focus_handle: None,
82 }
83 }
84
85 pub fn checked(mut self, checked: bool) -> Self {
87 self.checked = checked;
88 self
89 }
90
91 pub fn disabled(mut self, disabled: bool) -> Self {
96 self.disabled = disabled;
97 self
98 }
99
100 pub fn styles(mut self, build: impl FnOnce(SwitchStyles) -> SwitchStyles) -> Self {
102 self.semantic_styles = build(self.semantic_styles);
103 self
104 }
105
106 fn resolved_style(&self) -> StyleRefinement {
107 crate::state_style::resolve_style(
108 &self.style,
109 [
110 self.checked.then_some(&self.semantic_styles.checked),
111 self.disabled.then_some(&self.semantic_styles.disabled),
112 ]
113 .into_iter()
114 .flatten(),
115 )
116 }
117
118 pub fn on_change(
120 mut self,
121 handler: impl Fn(bool, &ClickEvent, &mut Window, &mut App) + 'static,
122 ) -> Self {
123 self.on_change = Some(Rc::new(handler));
124 self
125 }
126
127 pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
132 self.accessibility_label = Some(label.into());
133 self
134 }
135
136 pub fn field(mut self, metadata: crate::FieldMetadata) -> Self {
140 self.field = metadata;
141 self
142 }
143
144 pub fn tab_index(mut self, tab_index: isize) -> Self {
146 self.tab_index = tab_index;
147 self
148 }
149
150 pub fn tab_stop(mut self, tab_stop: bool) -> Self {
152 self.tab_stop = tab_stop;
153 self
154 }
155
156 pub fn track_focus(mut self, focus_handle: &FocusHandle) -> Self {
158 self.provided_focus_handle = Some(focus_handle.clone());
159 self
160 }
161
162 fn focus_handle(&self, window: &mut Window, cx: &mut App) -> FocusHandle {
163 self.provided_focus_handle.clone().unwrap_or_else(|| {
164 window
165 .use_keyed_state(self.id.clone(), cx, |_, cx| cx.focus_handle())
166 .read(cx)
167 .clone()
168 })
169 }
170}
171
172impl Styled for Switch {
173 fn style(&mut self) -> &mut StyleRefinement {
174 &mut self.style
175 }
176}
177
178impl ParentElement for Switch {
179 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
180 self.children.extend(elements);
181 }
182}
183
184impl InteractiveElement for Switch {
185 fn interactivity(&mut self) -> &mut Interactivity {
186 self.base.interactivity()
187 }
188}
189
190impl StatefulInteractiveElement for Switch {}
191
192impl RenderOnce for Switch {
193 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
194 let focus_handle = self.focus_handle(window, cx);
195 let checked = self.checked;
196 let disabled = self.disabled;
197 let style = self.resolved_style();
198 let field = self.field;
199
200 self.base
201 .role(Role::Switch)
202 .aria_toggled(if checked {
203 Toggled::True
204 } else {
205 Toggled::False
206 })
207 .when_some(field.label.or(self.accessibility_label), |this, label| {
208 this.aria_label(label)
209 })
210 .when(!disabled || focus_handle.is_focused(window), |this| {
213 this.track_focus(
214 &focus_handle
215 .tab_index(self.tab_index)
216 .tab_stop(self.tab_stop && !disabled),
217 )
218 })
219 .when(disabled, |this| {
220 this.on_mouse_down(MouseButton::Left, |_, _, cx| {
221 cx.stop_propagation();
222 })
223 })
224 .when_some(
225 (!disabled).then_some(self.on_change).flatten(),
226 |this, on_change| {
227 this.on_click(move |event, window, cx| {
228 on_change(!checked, event, window, cx);
229 })
230 },
231 )
232 .children(self.children)
233 .refine_style(&style)
234 .when_some(field.description, |this, description| {
235 this.aria_description(description)
236 })
237 .a11y_form(disabled, field.required, field.invalid)
238 }
239}
240
241#[cfg(test)]
242mod tests {
243 use super::*;
244 use std::{
245 cell::Cell,
246 rc::Rc,
247 sync::{Arc, Mutex},
248 };
249
250 use gpui::{
251 AppContext as _, Context, Element as _, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers,
252 Render, TestAppContext, VisualTestContext, accesskit, canvas, point, px,
253 };
254
255 struct SwitchHarness {
256 checked: bool,
257 disabled: bool,
258 toggles: Rc<Cell<usize>>,
259 keyboard_events: Rc<Cell<usize>>,
260 last_value: Rc<Cell<bool>>,
261 parent_clicks: Rc<Cell<usize>>,
262 }
263
264 impl Render for SwitchHarness {
265 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
266 let toggles = self.toggles.clone();
267 let keyboard_events = self.keyboard_events.clone();
268 let last_value = self.last_value.clone();
269 let parent_clicks = self.parent_clicks.clone();
270
271 div()
272 .id("switch-parent")
273 .tab_group()
274 .size(px(100.))
275 .on_click(move |_, _, _| parent_clicks.set(parent_clicks.get() + 1))
276 .child(
277 Switch::new("switch")
278 .checked(self.checked)
279 .disabled(self.disabled)
280 .size_full()
281 .on_change(move |value, event, _, _| {
282 toggles.set(toggles.get() + 1);
283 last_value.set(value);
284 if matches!(event, ClickEvent::Keyboard(_)) {
285 keyboard_events.set(keyboard_events.get() + 1);
286 }
287 }),
288 )
289 }
290 }
291
292 fn harness(
293 cx: &mut TestAppContext,
294 checked: bool,
295 disabled: bool,
296 ) -> (
297 &mut VisualTestContext,
298 Rc<Cell<usize>>,
299 Rc<Cell<usize>>,
300 Rc<Cell<bool>>,
301 Rc<Cell<usize>>,
302 ) {
303 let toggles = Rc::new(Cell::new(0));
304 let keyboard_events = Rc::new(Cell::new(0));
305 let last_value = Rc::new(Cell::new(checked));
306 let parent_clicks = Rc::new(Cell::new(0));
307 let (_, cx) = cx.add_window_view({
308 let toggles = toggles.clone();
309 let keyboard_events = keyboard_events.clone();
310 let last_value = last_value.clone();
311 let parent_clicks = parent_clicks.clone();
312 move |_, _| SwitchHarness {
313 checked,
314 disabled,
315 toggles,
316 keyboard_events,
317 last_value,
318 parent_clicks,
319 }
320 });
321 cx.update(|window, cx| window.draw(cx).clear(cx));
322 (cx, toggles, keyboard_events, last_value, parent_clicks)
323 }
324
325 fn activate_key(cx: &mut VisualTestContext, key: &str) {
326 let keystroke =
327 cx.update(|_, cx| Keystroke::parse_with_os(key, cx.platform_info().os).unwrap());
328 cx.simulate_event(KeyDownEvent {
329 keystroke: keystroke.clone(),
330 is_held: false,
331 prefer_character_input: false,
332 });
333 cx.simulate_event(KeyUpEvent { keystroke });
334 }
335
336 #[gpui::test]
337 fn pointer_enter_and_space_report_one_activation_each(cx: &mut TestAppContext) {
338 let (cx, toggles, keyboard_events, last_value, _) = harness(cx, false, false);
339 cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
340 assert_eq!(toggles.get(), 1);
341 assert_eq!(keyboard_events.get(), 0);
342 assert!(last_value.get());
343 toggles.set(0);
344 cx.update(|window, cx| {
345 assert!(window.focused(cx).is_some());
346 window.draw(cx).clear(cx);
347 });
348
349 activate_key(cx, "enter");
350 activate_key(cx, "space");
351
352 assert_eq!(toggles.get(), 2);
353 assert_eq!(keyboard_events.get(), 2);
354 assert!(last_value.get());
355 }
356
357 #[gpui::test]
358 fn disabled_switch_is_inert_and_blocks_parent_activation(cx: &mut TestAppContext) {
359 let (cx, toggles, _, _, parent_clicks) = harness(cx, false, true);
360
361 cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
362 activate_key(cx, "enter");
363 activate_key(cx, "space");
364
365 assert_eq!(toggles.get(), 0);
366 assert_eq!(parent_clicks.get(), 0);
367 }
368
369 struct DisableDuringFocus {
370 handles: [FocusHandle; 3],
371 value: bool,
372 disabled: bool,
373 activations: usize,
374 }
375
376 impl Render for DisableDuringFocus {
377 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
378 let change = cx.listener(|this, value: &bool, _, cx| {
379 this.value = *value;
380 this.disabled = true;
381 this.activations += 1;
382 cx.notify();
383 });
384 div()
385 .size_full()
386 .flex()
387 .tab_group()
388 .child(
389 crate::Button::new("before")
390 .track_focus(&self.handles[0])
391 .child("Before"),
392 )
393 .child(
394 Switch::new("disable-self")
395 .checked(self.value)
396 .track_focus(&self.handles[1])
397 .disabled(self.disabled)
398 .child("Disable self")
399 .on_change(move |value, _, window, cx| change(&value, window, cx)),
400 )
401 .child(
402 crate::Button::new("after")
403 .track_focus(&self.handles[2])
404 .child("After"),
405 )
406 }
407 }
408
409 #[gpui::test]
410 fn disabling_focused_switch_preserves_bidirectional_traversal(cx: &mut TestAppContext) {
411 cx.update(crate::init);
412 for (key, expected, back, opposite) in
413 [("tab", 2, "shift-tab", 0), ("shift-tab", 0, "tab", 2)]
414 {
415 let handles = cx.update(|cx| std::array::from_fn(|_| cx.focus_handle()));
416 let controls = cx.new(|_| DisableDuringFocus {
417 handles: handles.clone(),
418 value: false,
419 disabled: false,
420 activations: 0,
421 });
422 let (_, cx) =
423 cx.add_window_view(|window, cx| crate::Root::new(controls.clone(), window, cx));
424 cx.update(|window, cx| {
425 window.activate_window();
426 window.draw(cx).clear(cx);
427 handles[0].focus(window, cx);
428 window.draw(cx).clear(cx);
429 });
430 activate_key(cx, "tab");
431 cx.update(|window, cx| {
432 window.draw(cx).clear(cx);
433 assert_eq!(window.focused(cx).as_ref(), Some(&handles[1]));
434 });
435 activate_key(cx, "space");
436 cx.update(|window, cx| {
437 window.draw(cx).clear(cx);
438 assert!(controls.read(cx).disabled);
439 assert!(controls.read(cx).value);
440 assert_eq!(controls.read(cx).activations, 1);
441 });
442 activate_key(cx, "enter");
443 activate_key(cx, "space");
444 cx.update(|_, cx| assert_eq!(controls.read(cx).activations, 1));
445 activate_key(cx, key);
446 cx.update(|window, cx| {
447 window.draw(cx).clear(cx);
448 assert_eq!(window.focused(cx).as_ref(), Some(&handles[expected]));
449 });
450 activate_key(cx, back);
451 cx.update(|window, cx| {
452 window.draw(cx).clear(cx);
453 assert_eq!(window.focused(cx).as_ref(), Some(&handles[opposite]));
454 });
455 controls.update(cx, |this, cx| {
456 this.disabled = false;
457 cx.notify();
458 });
459 cx.update(|window, cx| window.draw(cx).clear(cx));
460 activate_key(cx, key);
461 cx.update(|window, cx| {
462 window.draw(cx).clear(cx);
463 assert_eq!(window.focused(cx).as_ref(), Some(&handles[1]));
464 });
465 }
466 }
467
468 #[test]
469 fn semantic_root_styles_follow_switch_priority() {
470 let styled = |switch: Switch| {
471 switch.styles(|styles| {
472 styles
473 .checked(|style| style.opacity(0.8))
474 .disabled(|style| style.opacity(0.5))
475 })
476 };
477
478 assert_eq!(styled(Switch::new("normal")).resolved_style().opacity, None);
479 assert_eq!(
480 styled(Switch::new("checked").checked(true))
481 .resolved_style()
482 .opacity,
483 Some(0.8)
484 );
485 assert_eq!(
486 styled(Switch::new("checked-disabled").checked(true).disabled(true))
487 .resolved_style()
488 .opacity,
489 Some(0.5)
490 );
491 assert_eq!(
492 styled(
493 Switch::new("state-over-instance")
494 .checked(true)
495 .disabled(true)
496 .opacity(0.9),
497 )
498 .resolved_style()
499 .opacity,
500 Some(0.5)
501 );
502 }
503
504 #[gpui::test]
505 fn accessibility_exposes_switch_role_label_and_toggled_state(cx: &mut TestAppContext) {
506 type Captured = Arc<Mutex<Option<(accesskit::Node, accesskit::Node)>>>;
507
508 struct A11yProbe {
509 captured: Captured,
510 }
511
512 impl Render for A11yProbe {
513 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
514 let captured = self.captured.clone();
515 canvas(
516 move |_, window, cx| {
517 let mut info = |switch: Switch| {
518 let element = switch.render(window, cx).into_element();
519 let mut node = accesskit::Node::new(element.a11y_role().unwrap());
520 element.write_a11y_info(&mut node);
521 node
522 };
523 let enabled = info(
524 Switch::new("enabled")
525 .checked(true)
526 .accessibility_label("Airplane mode")
527 .on_change(|_, _, _, _| {}),
528 );
529 let disabled = info(
530 Switch::new("disabled")
531 .checked(false)
532 .disabled(true)
533 .accessibility_label("Airplane mode")
534 .on_change(|_, _, _, _| {}),
535 );
536 *captured.lock().unwrap() = Some((enabled, disabled));
537 },
538 |_, _, _, _| {},
539 )
540 }
541 }
542
543 let captured: Captured = Arc::new(Mutex::new(None));
544 let result = captured.clone();
545 let (_, cx) = cx.add_window_view(move |_, _| A11yProbe { captured });
546 cx.update(|window, cx| window.draw(cx).clear(cx));
547 let (enabled, disabled) = result.lock().unwrap().take().unwrap();
548
549 assert_eq!(enabled.role(), Role::Switch);
550 assert_eq!(enabled.label(), Some("Airplane mode"));
551 assert_eq!(enabled.toggled(), Some(Toggled::True));
552 assert!(enabled.supports_action(accesskit::Action::Click));
553
554 assert_eq!(disabled.role(), Role::Switch);
555 assert_eq!(disabled.toggled(), Some(Toggled::False));
556 assert!(!disabled.supports_action(accesskit::Action::Click));
557 assert!(!enabled.is_disabled());
558 assert!(disabled.is_disabled());
559 }
560}