1use gpui::{
6 AnyElement, App, Axis, Context, ElementId, Entity, EntityId, EventEmitter, FocusHandle,
7 InteractiveElement, Interactivity, IntoElement, KeyBinding, ParentElement, RenderOnce, Role,
8 SharedString, StatefulInteractiveElement, StyleRefinement, Styled, Subscription, Window,
9 accesskit, div, prelude::FluentBuilder as _,
10};
11
12use crate::{
13 TestSupportExt as _, Toggle,
14 a11y_disabled::A11yDisabledExt as _,
15 actions::{SelectDown, SelectFirst, SelectLast, SelectLeft, SelectRight, SelectUp},
16};
17
18const CONTEXT: &str = "ToggleGroup";
19
20pub(crate) fn init(cx: &mut App) {
21 cx.bind_keys([
22 KeyBinding::new(
23 "left",
24 SelectLeft,
25 Some("ToggleGroup && axis == horizontal"),
26 ),
27 KeyBinding::new(
28 "right",
29 SelectRight,
30 Some("ToggleGroup && axis == horizontal"),
31 ),
32 KeyBinding::new("up", SelectUp, Some("ToggleGroup && axis == vertical")),
33 KeyBinding::new("down", SelectDown, Some("ToggleGroup && axis == vertical")),
34 KeyBinding::new("home", SelectFirst, Some(CONTEXT)),
35 KeyBinding::new("end", SelectLast, Some(CONTEXT)),
36 ]);
37}
38
39#[derive(Clone, Debug)]
41pub struct ToggleItem {
42 value: SharedString,
43 label: SharedString,
44 disabled: bool,
45}
46
47impl ToggleItem {
48 pub fn new(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
49 Self {
50 value: value.into(),
51 label: label.into(),
52 disabled: false,
53 }
54 }
55
56 pub fn disabled(mut self, disabled: bool) -> Self {
57 self.disabled = disabled;
58 self
59 }
60
61 pub fn value(&self) -> &SharedString {
62 &self.value
63 }
64
65 pub fn label(&self) -> &SharedString {
66 &self.label
67 }
68
69 pub fn is_disabled(&self) -> bool {
70 self.disabled
71 }
72}
73
74#[derive(Clone, Debug, Eq, PartialEq)]
76pub enum ToggleGroupEvent {
77 Change(Vec<SharedString>),
78}
79
80pub struct ToggleGroupState {
87 items: Vec<ToggleItem>,
88 pressed: Vec<bool>,
89 single_selection: bool,
90 cursor: Option<usize>,
91 disabled: bool,
92 focus: Vec<FocusHandle>,
93 focus_subscriptions: Vec<Subscription>,
94}
95
96impl ToggleGroupState {
97 pub fn new(items: impl IntoIterator<Item = ToggleItem>, cx: &mut Context<Self>) -> Self {
98 let items: Vec<_> = items.into_iter().collect();
99 for (index, item) in items.iter().enumerate() {
100 assert!(
101 items[..index].iter().all(|other| other.value != item.value),
102 "ToggleItem values must be unique"
103 );
104 }
105 let cursor = items.iter().position(|item| !item.disabled);
106 let focus = items.iter().map(|_| cx.focus_handle()).collect();
107 Self {
108 pressed: vec![false; items.len()],
109 single_selection: false,
110 items,
111 cursor,
112 disabled: false,
113 focus,
114 focus_subscriptions: Vec::new(),
115 }
116 }
117
118 pub fn single_selection(mut self) -> Self {
126 assert!(
127 self.pressed.iter().filter(|pressed| **pressed).count() <= 1,
128 "ToggleGroupState single_selection allows at most one default value"
129 );
130 self.single_selection = true;
131 self
132 }
133
134 pub fn default_values<V: AsRef<str>>(mut self, values: impl IntoIterator<Item = V>) -> Self {
140 self.pressed.fill(false);
141 for value in values {
142 let index = self
143 .items
144 .iter()
145 .position(|item| item.value.as_ref() == value.as_ref() && !item.disabled)
146 .expect("ToggleGroupState default_values must identify enabled ToggleItems");
147 self.pressed[index] = true;
148 }
149 assert!(
150 !self.single_selection || self.pressed.iter().filter(|pressed| **pressed).count() <= 1,
151 "ToggleGroupState single_selection allows at most one default value"
152 );
153 self
154 }
155
156 pub fn items(&self) -> &[ToggleItem] {
157 &self.items
158 }
159
160 pub fn is_pressed(&self, index: usize) -> bool {
161 self.pressed[index]
162 }
163
164 pub fn selected_values(&self) -> Vec<SharedString> {
165 self.items
166 .iter()
167 .zip(&self.pressed)
168 .filter_map(|(item, pressed)| pressed.then(|| item.value.clone()))
169 .collect()
170 }
171
172 pub fn set_selected_values<V: AsRef<str>>(
179 &mut self,
180 values: impl IntoIterator<Item = V>,
181 window: &mut Window,
182 cx: &mut Context<Self>,
183 ) -> bool {
184 let mut pressed = vec![false; self.items.len()];
185 for value in values {
186 let Some(index) = self
187 .items
188 .iter()
189 .position(|item| item.value.as_ref() == value.as_ref() && !item.disabled)
190 else {
191 return false;
192 };
193 pressed[index] = true;
194 }
195 if self.single_selection && pressed.iter().filter(|pressed| **pressed).count() > 1 {
196 return false;
197 }
198 if self.pressed != pressed {
199 self.pressed = pressed;
200 cx.notify();
201 window.refresh();
202 }
203 true
204 }
205
206 pub fn option_focus_handle(&self, index: usize) -> &FocusHandle {
207 &self.focus[index]
208 }
209
210 pub fn is_disabled(&self) -> bool {
211 self.disabled
212 }
213
214 pub fn set_disabled(&mut self, disabled: bool, window: &mut Window, cx: &mut Context<Self>) {
217 if self.disabled == disabled {
218 return;
219 }
220 self.disabled = disabled;
221 cx.notify();
222 window.refresh();
223 }
224
225 fn bind_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
226 if !self.focus_subscriptions.is_empty() {
227 return;
228 }
229 self.focus_subscriptions = self
230 .focus
231 .iter()
232 .enumerate()
233 .map(|(index, focus)| {
234 cx.on_focus(focus, window, move |_, window, cx| {
235 cx.defer_in(window, move |state, window, cx| {
238 if state.focus[index].is_focused(window) {
239 state.remember_focus(index, window, cx);
240 }
241 });
242 })
243 })
244 .collect();
245 }
246
247 fn remember_focus(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
248 if self.disabled || self.items[index].disabled || self.cursor == Some(index) {
249 return;
250 }
251 self.cursor = Some(index);
252 cx.notify();
253 window.refresh();
254 }
255
256 fn focus_option(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
257 if self.disabled || self.items[index].disabled {
258 return;
259 }
260 self.focus[index].focus(window, cx);
261 self.remember_focus(index, window, cx);
262 }
263
264 fn set_pressed(
265 &mut self,
266 index: usize,
267 pressed: bool,
268 window: &mut Window,
269 cx: &mut Context<Self>,
270 ) {
271 if self.disabled || self.items[index].disabled {
272 return;
273 }
274 self.focus_option(index, window, cx);
275 if self.pressed[index] == pressed {
276 return;
277 }
278 if self.single_selection && pressed {
279 self.pressed.fill(false);
280 }
281 self.pressed[index] = pressed;
282 cx.emit(ToggleGroupEvent::Change(self.selected_values()));
283 cx.notify();
284 window.refresh();
285 }
286
287 fn focused_index(&self, window: &Window) -> Option<usize> {
288 self.focus.iter().position(|focus| focus.is_focused(window))
289 }
290
291 fn move_focus(&mut self, forward: bool, window: &mut Window, cx: &mut Context<Self>) {
292 if self.disabled {
293 return;
294 }
295 let Some(current) = self.focused_index(window) else {
296 cx.propagate();
297 return;
298 };
299 let len = self.items.len();
300 if let Some(next) = (1..=len)
301 .map(|step| {
302 if forward {
303 (current + step) % len
304 } else {
305 (current + len - step) % len
306 }
307 })
308 .find(|&index| !self.items[index].disabled)
309 {
310 self.focus_option(next, window, cx);
311 }
312 }
313
314 fn focus_edge(&mut self, last: bool, window: &mut Window, cx: &mut Context<Self>) {
315 if self.disabled {
316 return;
317 }
318 if self.focused_index(window).is_none() {
319 cx.propagate();
320 return;
321 }
322 let next = if last {
323 self.items.iter().rposition(|item| !item.disabled)
324 } else {
325 self.items.iter().position(|item| !item.disabled)
326 };
327 if let Some(next) = next {
328 self.focus_option(next, window, cx);
329 }
330 }
331}
332
333impl EventEmitter<ToggleGroupEvent> for ToggleGroupState {}
334
335fn option_id(state: EntityId, index: usize) -> ElementId {
336 (ElementId::from(("toggle-option", state)), index.to_string()).into()
337}
338
339#[derive(IntoElement)]
343pub struct ToggleGroup {
344 base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
345 state: Entity<ToggleGroupState>,
346 label: Option<SharedString>,
347 axis: Axis,
348 direction: Option<crate::Direction>,
349}
350
351impl ToggleGroup {
352 pub fn new(id: impl Into<ElementId>, state: &Entity<ToggleGroupState>) -> Self {
353 Self {
354 base: div().id(id).test_support(),
355 state: state.clone(),
356 label: None,
357 axis: Axis::Horizontal,
358 direction: None,
359 }
360 }
361
362 pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
363 self.label = Some(label.into());
364 self
365 }
366
367 pub fn direction(mut self, direction: crate::Direction) -> Self {
369 self.direction = Some(direction);
370 self
371 }
372
373 pub fn axis(mut self, axis: Axis) -> Self {
374 self.axis = axis;
375 self
376 }
377}
378
379impl Styled for ToggleGroup {
380 fn style(&mut self) -> &mut StyleRefinement {
381 self.base.style()
382 }
383}
384
385impl ParentElement for ToggleGroup {
386 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
387 self.base.extend(elements);
388 }
389}
390
391impl InteractiveElement for ToggleGroup {
392 fn interactivity(&mut self) -> &mut Interactivity {
393 self.base.interactivity()
394 }
395}
396
397impl StatefulInteractiveElement for ToggleGroup {}
398
399impl RenderOnce for ToggleGroup {
400 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
401 let direction = self
402 .direction
403 .unwrap_or_else(|| crate::Direction::current(cx));
404 self.state
405 .update(cx, |state, cx| state.bind_focus(window, cx));
406 let disabled = self.state.read(cx).disabled;
407 let previous = self.state.clone();
408 let next = self.state.clone();
409 let first = self.state.clone();
410 let last = self.state;
411 let base = self
412 .base
413 .role(Role::Group)
414 .when_some(self.label, |this, label| this.aria_label(label))
415 .on_action(move |_: &SelectFirst, window, cx| {
416 first.update(cx, |state, cx| state.focus_edge(false, window, cx));
417 })
418 .on_action(move |_: &SelectLast, window, cx| {
419 last.update(cx, |state, cx| state.focus_edge(true, window, cx));
420 });
421 match self.axis {
422 Axis::Horizontal => base
423 .aria_orientation(accesskit::Orientation::Horizontal)
424 .key_context("ToggleGroup axis=horizontal")
425 .on_action(move |_: &SelectLeft, window, cx| {
426 previous.update(cx, |state, cx| {
427 state.move_focus(direction.horizontal_forward(false), window, cx)
428 });
429 })
430 .on_action(move |_: &SelectRight, window, cx| {
431 next.update(cx, |state, cx| {
432 state.move_focus(direction.horizontal_forward(true), window, cx)
433 });
434 }),
435 Axis::Vertical => base
436 .aria_orientation(accesskit::Orientation::Vertical)
437 .key_context("ToggleGroup axis=vertical")
438 .on_action(move |_: &SelectUp, window, cx| {
439 previous.update(cx, |state, cx| state.move_focus(false, window, cx));
440 })
441 .on_action(move |_: &SelectDown, window, cx| {
442 next.update(cx, |state, cx| state.move_focus(true, window, cx));
443 }),
444 }
445 .a11y_disabled(disabled)
446 }
447}
448
449#[derive(IntoElement)]
452pub struct ToggleOption {
453 toggle: Toggle,
454 state: Entity<ToggleGroupState>,
455 index: usize,
456}
457
458impl ToggleOption {
459 pub fn new(state: &Entity<ToggleGroupState>, index: usize) -> Self {
460 Self {
461 toggle: Toggle::new(option_id(state.entity_id(), index)),
462 state: state.clone(),
463 index,
464 }
465 }
466}
467
468impl Styled for ToggleOption {
469 fn style(&mut self) -> &mut StyleRefinement {
470 self.toggle.style()
471 }
472}
473
474impl ParentElement for ToggleOption {
475 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
476 self.toggle.extend(elements);
477 }
478}
479
480impl InteractiveElement for ToggleOption {
481 fn interactivity(&mut self) -> &mut Interactivity {
482 self.toggle.interactivity()
483 }
484
485 crate::button::forward_hover_styles!(toggle);
486}
487
488impl StatefulInteractiveElement for ToggleOption {
489 crate::button::forward_active_styles!(toggle);
490}
491
492impl RenderOnce for ToggleOption {
493 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
494 let model = self.state.read(cx);
495 let item = model
496 .items
497 .get(self.index)
498 .expect("ToggleOption index must identify an item");
499 let disabled = model.disabled || item.disabled;
500 let pressed = model.is_pressed(self.index);
501 let tab_stop = model.cursor == Some(self.index);
502 let focus = model.option_focus_handle(self.index).clone();
503 let label = item.label.clone();
504 let index = self.index;
505 let state = self.state;
506 self.toggle
507 .accessibility_label(label)
508 .pressed(pressed)
509 .disabled(disabled)
510 .track_focus(&focus)
511 .tab_stop(tab_stop)
512 .on_change(move |pressed, _, window, cx| {
513 state.update(cx, |state, cx| {
514 state.set_pressed(index, pressed, window, cx)
515 });
516 })
517 .render(window, cx)
518 }
519}
520
521#[cfg(test)]
522mod tests {
523 use std::{cell::RefCell, rc::Rc};
524
525 use gpui::{
526 AppContext as _, Element as _, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, Render,
527 TestAppContext, Toggled, VisualTestContext, px,
528 };
529
530 use super::*;
531 use crate::{Button, Root};
532
533 struct Harness {
534 state: Entity<ToggleGroupState>,
535 axis: Axis,
536 direction: crate::Direction,
537 before: FocusHandle,
538 after: FocusHandle,
539 unhandled: Rc<RefCell<Vec<String>>>,
540 _subscription: Subscription,
541 }
542
543 impl Render for Harness {
544 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
545 let unhandled = self.unhandled.clone();
546 div()
547 .w(px(400.))
548 .flex()
549 .flex_col()
550 .on_key_down(move |event, _, _| {
551 unhandled.borrow_mut().push(event.keystroke.key.clone());
552 })
553 .child(
554 Button::new("before")
555 .track_focus(&self.before)
556 .h(px(32.))
557 .child("Before"),
558 )
559 .child(
560 ToggleGroup::new("group", &self.state)
561 .axis(self.axis)
562 .direction(self.direction)
563 .accessibility_label("Text emphasis")
564 .flex()
565 .when(self.axis == Axis::Vertical, |this| this.flex_col())
566 .children(self.state.read(cx).items().iter().enumerate().map(
567 |(index, item)| {
568 ToggleOption::new(&self.state, index)
569 .debug_selector(move || format!("option-{index}"))
570 .w(px(100.))
571 .h(px(32.))
572 .child(item.label().clone())
573 },
574 )),
575 )
576 .child(
577 Button::new("after")
578 .track_focus(&self.after)
579 .h(px(32.))
580 .child("After"),
581 )
582 }
583 }
584
585 type Changes = Rc<RefCell<Vec<Vec<SharedString>>>>;
586
587 fn harness(
588 cx: &mut TestAppContext,
589 axis: Axis,
590 single_selection: bool,
591 ) -> (&mut VisualTestContext, Entity<Harness>, Changes) {
592 cx.update(crate::init);
593 let (root, cx) = cx.add_window_view(move |window, cx| {
594 let content = cx.new(|cx| {
595 let state = cx.new(|cx| {
596 let state = ToggleGroupState::new(
597 [
598 ToggleItem::new("bold", "Bold"),
599 ToggleItem::new("underline", "Unavailable").disabled(true),
600 ToggleItem::new("italic", "Italic"),
601 ToggleItem::new("strike", "Strike"),
602 ],
603 cx,
604 );
605 if single_selection {
606 state.single_selection()
607 } else {
608 state
609 }
610 .default_values(["bold"])
611 });
612 let subscription = cx.observe(&state, |_, _, cx| cx.notify());
613 Harness {
614 state,
615 axis,
616 direction: crate::Direction::Ltr,
617 before: cx.focus_handle().tab_stop(true),
618 after: cx.focus_handle().tab_stop(true),
619 unhandled: Rc::new(RefCell::new(Vec::new())),
620 _subscription: subscription,
621 }
622 });
623 Root::new(content, window, cx)
624 });
625 let view = root
626 .read_with(cx, |root, _| root.view().clone())
627 .downcast::<Harness>()
628 .unwrap();
629 let changes = Rc::new(RefCell::new(Vec::new()));
630 cx.update(|window, cx| {
631 let state = view.read(cx).state.clone();
632 let changes = changes.clone();
633 cx.subscribe(&state, move |_, event: &ToggleGroupEvent, _| {
634 let ToggleGroupEvent::Change(values) = event;
635 changes.borrow_mut().push(values.clone());
636 })
637 .detach();
638 window.activate_window();
639 view.read(cx).before.clone().focus(window, cx);
640 window.draw(cx).clear(cx);
641 });
642 cx.run_until_parked();
643 (cx, view, changes)
644 }
645
646 fn draw(cx: &mut VisualTestContext) {
647 cx.update(|window, cx| window.draw(cx).clear(cx));
648 }
649
650 fn press(cx: &mut VisualTestContext, key: &str) {
651 let keystroke =
652 cx.update(|_, cx| Keystroke::parse_with_os(key, cx.platform_info().os).unwrap());
653 cx.simulate_event(KeyDownEvent {
654 keystroke: keystroke.clone(),
655 is_held: false,
656 prefer_character_input: false,
657 });
658 cx.simulate_event(KeyUpEvent { keystroke });
659 draw(cx);
660 }
661
662 #[gpui::test]
663 fn focus_navigation_is_independent_of_multiple_selection(cx: &mut TestAppContext) {
664 let (cx, view, changes) = harness(cx, Axis::Horizontal, false);
665 cx.simulate_keystrokes("tab right");
666 draw(cx);
667 cx.update(|window, cx| {
668 let state = view.read(cx).state.read(cx);
669 assert!(state.option_focus_handle(2).is_focused(window));
670 assert_eq!(state.selected_values(), [SharedString::from("bold")]);
671 });
672 assert!(changes.borrow().is_empty());
673 press(cx, "space");
674 press(cx, "enter");
675 cx.simulate_keystrokes("end");
676 draw(cx);
677 press(cx, "enter");
678 cx.simulate_keystrokes("right");
679 draw(cx);
680 cx.update(|window, cx| {
681 assert!(
682 view.read(cx)
683 .state
684 .read(cx)
685 .option_focus_handle(0)
686 .is_focused(window)
687 );
688 });
689 let bold = cx.debug_bounds("option-0").unwrap().center();
690 cx.simulate_click(bold, Modifiers::default());
691 draw(cx);
692 let disabled = cx.debug_bounds("option-1").unwrap().center();
693 cx.simulate_click(disabled, Modifiers::default());
694 draw(cx);
695 assert_eq!(
696 *changes.borrow(),
697 [
698 vec!["bold", "italic"],
699 vec!["bold"],
700 vec!["bold", "strike"],
701 vec!["strike"]
702 ]
703 .map(|values| values
704 .into_iter()
705 .map(SharedString::from)
706 .collect::<Vec<_>>())
707 );
708 cx.simulate_keystrokes("tab");
709 draw(cx);
710 cx.update(|window, cx| assert!(view.read(cx).after.is_focused(window)));
711 cx.simulate_keystrokes("shift-tab");
712 draw(cx);
713 cx.update(|window, cx| {
714 let state = view.read(cx).state.read(cx);
715 assert!(state.option_focus_handle(0).is_focused(window));
716 assert_eq!(state.selected_values(), [SharedString::from("strike")]);
717 });
718 }
719
720 #[gpui::test]
721 fn vertical_and_programmatic_focus_preserve_one_tab_entry_and_disabled_values(
722 cx: &mut TestAppContext,
723 ) {
724 let (cx, view, changes) = harness(cx, Axis::Vertical, false);
725 cx.simulate_keystrokes("tab down");
726 draw(cx);
727 cx.update(|window, cx| {
728 assert!(
729 view.read(cx)
730 .state
731 .read(cx)
732 .option_focus_handle(2)
733 .is_focused(window)
734 );
735 view.read(cx).unhandled.borrow_mut().clear();
736 });
737 cx.simulate_keystrokes("left right");
738 draw(cx);
739 cx.update(|window, cx| {
740 assert_eq!(*view.read(cx).unhandled.borrow(), ["left", "right"]);
741 let focus = view.read(cx).state.read(cx).option_focus_handle(3).clone();
742 focus.focus(window, cx);
743 });
744 draw(cx);
745 cx.run_until_parked();
746 draw(cx);
747 cx.simulate_keystrokes("tab");
748 draw(cx);
749 cx.update(|window, cx| assert!(view.read(cx).after.is_focused(window)));
750 cx.simulate_keystrokes("shift-tab");
751 draw(cx);
752 cx.update(|window, cx| {
753 assert!(
754 view.read(cx)
755 .state
756 .read(cx)
757 .option_focus_handle(3)
758 .is_focused(window)
759 );
760 });
761 assert!(changes.borrow().is_empty());
762 press(cx, "space");
763 cx.update(|window, cx| {
764 let state = view.read(cx).state.clone();
765 state.update(cx, |state, cx| state.set_disabled(true, window, cx));
766 let group = ToggleGroup::new("native-group", &state)
767 .axis(Axis::Vertical)
768 .accessibility_label("Text emphasis")
769 .render(window, cx)
770 .into_element();
771 assert_eq!(group.a11y_role(), Some(Role::Group));
772 let mut node = accesskit::Node::new(Role::Group);
773 group.write_a11y_info(&mut node);
774 assert_eq!(node.label(), Some("Text emphasis"));
775 assert_eq!(node.orientation(), Some(accesskit::Orientation::Vertical));
776 assert!(node.is_disabled());
777 let option = ToggleOption::new(&state, 3)
778 .render(window, cx)
779 .into_element();
780 let mut node = accesskit::Node::new(option.a11y_role().unwrap());
781 option.write_a11y_info(&mut node);
782 assert_eq!(node.role(), Role::Button);
783 assert_eq!(node.toggled(), Some(Toggled::True));
784 assert!(node.is_disabled());
785 });
786 draw(cx);
787 press(cx, "space");
788 cx.simulate_keystrokes("down home tab");
789 draw(cx);
790 cx.update(|window, cx| assert!(view.read(cx).after.is_focused(window)));
791 cx.simulate_keystrokes("shift-tab");
792 draw(cx);
793 cx.update(|window, cx| {
794 let state = view.read(cx).state.clone();
795 assert!(view.read(cx).before.is_focused(window));
796 assert_eq!(
797 state.read(cx).selected_values(),
798 ["bold", "strike"].map(SharedString::from)
799 );
800 state.update(cx, |state, cx| state.set_disabled(false, window, cx));
801 });
802 draw(cx);
803 cx.simulate_keystrokes("tab");
804 draw(cx);
805 cx.update(|window, cx| {
806 assert!(
807 view.read(cx)
808 .state
809 .read(cx)
810 .option_focus_handle(3)
811 .is_focused(window)
812 );
813 });
814 assert_eq!(changes.borrow().len(), 1);
815 }
816
817 #[gpui::test]
818 fn single_selection_replaces_and_clears_pressed_values_with_shared_navigation(
819 cx: &mut TestAppContext,
820 ) {
821 let (cx, view, changes) = harness(cx, Axis::Horizontal, true);
822 view.update(cx, |view, cx| {
823 view.direction = crate::Direction::Rtl;
824 cx.notify();
825 });
826 draw(cx);
827 cx.simulate_keystrokes("tab left");
828 draw(cx);
829 cx.update(|window, cx| {
830 let state = view.read(cx).state.read(cx);
831 assert!(state.option_focus_handle(2).is_focused(window));
832 assert_eq!(state.selected_values(), [SharedString::from("bold")]);
833 });
834 assert!(changes.borrow().is_empty());
835
836 press(cx, "enter");
837 cx.update(|window, cx| {
838 let state = view.read(cx).state.clone();
839 assert_eq!(
840 state.read(cx).selected_values(),
841 [SharedString::from("italic")]
842 );
843 for (index, toggled) in [(0, Toggled::False), (2, Toggled::True)] {
844 let option = ToggleOption::new(&state, index)
845 .render(window, cx)
846 .into_element();
847 let mut node = accesskit::Node::new(option.a11y_role().unwrap());
848 option.write_a11y_info(&mut node);
849 assert_eq!(node.role(), Role::Button);
850 assert_eq!(node.toggled(), Some(toggled));
851 }
852 });
853 press(cx, "space");
854 cx.update(|_, cx| assert!(view.read(cx).state.read(cx).selected_values().is_empty()));
855
856 let bold = cx.debug_bounds("option-0").unwrap().center();
857 cx.simulate_click(bold, Modifiers::default());
858 draw(cx);
859 let disabled = cx.debug_bounds("option-1").unwrap().center();
860 cx.simulate_click(disabled, Modifiers::default());
861 draw(cx);
862 cx.update(|window, cx| {
863 let state = view.read(cx).state.clone();
864 state.update(cx, |state, cx| state.set_disabled(true, window, cx));
865 let option = ToggleOption::new(&state, 0)
866 .render(window, cx)
867 .into_element();
868 let mut node = accesskit::Node::new(option.a11y_role().unwrap());
869 option.write_a11y_info(&mut node);
870 assert_eq!(node.label(), Some("Bold"));
871 assert_eq!(node.toggled(), Some(Toggled::True));
872 assert!(node.is_disabled());
873 });
874 draw(cx);
875 press(cx, "space");
876 let italic = cx.debug_bounds("option-2").unwrap().center();
877 cx.simulate_click(italic, Modifiers::default());
878 draw(cx);
879 cx.simulate_keystrokes("tab");
880 draw(cx);
881 cx.update(|window, cx| {
882 assert!(view.read(cx).after.is_focused(window));
883 assert_eq!(
884 view.read(cx).state.read(cx).selected_values(),
885 [SharedString::from("bold")]
886 );
887 });
888 assert_eq!(
889 *changes.borrow(),
890 [vec!["italic"], vec![], vec!["bold"]].map(|values| values
891 .into_iter()
892 .map(SharedString::from)
893 .collect::<Vec<_>>())
894 );
895 }
896
897 #[gpui::test]
898 fn programmatic_selection_preserves_cursor_and_validates_without_user_events(
899 cx: &mut TestAppContext,
900 ) {
901 for single in [false, true] {
902 let (cx, view, changes) = harness(cx, Axis::Horizontal, single);
903 cx.simulate_keystrokes("tab right");
904 draw(cx);
905 cx.update(|window, cx| {
906 let state = view.read(cx).state.clone();
907 state.update(cx, |state, cx| {
908 assert!(state.set_selected_values(["strike", "strike"], window, cx));
909 assert!(!state.set_selected_values(["bold", "missing"], window, cx));
910 assert!(!state.set_selected_values(["bold", "underline"], window, cx));
911 assert_eq!(state.selected_values(), [SharedString::from("strike")]);
912 let accepted = state.set_selected_values(["strike", "bold"], window, cx);
913 assert_eq!(accepted, !single);
914 let expected = if single {
915 vec!["strike"]
916 } else {
917 vec!["bold", "strike"]
918 };
919 assert_eq!(
920 state.selected_values(),
921 expected
922 .into_iter()
923 .map(SharedString::from)
924 .collect::<Vec<_>>()
925 );
926 assert!(state.option_focus_handle(2).is_focused(window));
927 });
928 for index in [0, 2, 3] {
929 let option = ToggleOption::new(&state, index)
930 .render(window, cx)
931 .into_element();
932 let mut node = accesskit::Node::new(option.a11y_role().unwrap());
933 option.write_a11y_info(&mut node);
934 let pressed = index == 3 || (index == 0 && !single);
935 assert_eq!(
936 node.toggled(),
937 Some(if pressed {
938 Toggled::True
939 } else {
940 Toggled::False
941 })
942 );
943 }
944 });
945 draw(cx);
946 cx.simulate_keystrokes("tab");
947 draw(cx);
948 cx.update(|window, cx| {
949 assert!(view.read(cx).after.is_focused(window));
950 let state = view.read(cx).state.clone();
951 state.update(cx, |state, cx| {
952 state.set_disabled(true, window, cx);
953 assert!(state.set_selected_values(std::iter::empty::<&str>(), window, cx));
954 assert!(state.selected_values().is_empty());
955 assert!(state.set_selected_values(["bold"], window, cx));
956 state.set_disabled(false, window, cx);
957 });
958 assert!(view.read(cx).after.is_focused(window));
959 });
960 draw(cx);
961 cx.simulate_keystrokes("shift-tab");
962 draw(cx);
963 cx.update(|window, cx| {
964 let state = view.read(cx).state.read(cx);
965 assert!(state.option_focus_handle(2).is_focused(window));
966 assert_eq!(state.selected_values(), [SharedString::from("bold")]);
967 });
968 assert!(changes.borrow().is_empty());
969 }
970 }
971
972 #[gpui::test]
973 fn single_selection_defaults_accept_zero_or_one_distinct_value_in_either_order(
974 cx: &mut TestAppContext,
975 ) {
976 cx.new(|cx| {
977 let items = || {
978 [
979 ToggleItem::new("bold", "Bold"),
980 ToggleItem::new("italic", "Italic"),
981 ]
982 };
983 for defaults_first in [false, true] {
984 let rejected = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
985 let state = ToggleGroupState::new(items(), cx);
986 if defaults_first {
987 state.default_values(["bold", "italic"]).single_selection()
988 } else {
989 state.single_selection().default_values(["bold", "italic"])
990 }
991 }));
992 assert!(rejected.is_err());
993 }
994 let empty = ToggleGroupState::new(items(), cx)
995 .single_selection()
996 .default_values(std::iter::empty::<&str>());
997 assert!(empty.selected_values().is_empty());
998 let state = ToggleGroupState::new(items(), cx)
999 .default_values(["bold", "bold"])
1000 .single_selection();
1001 assert_eq!(state.selected_values(), [SharedString::from("bold")]);
1002 state
1003 });
1004 }
1005}