1use gpui::{
6 AnyElement, App, Context, ElementId, Entity, EntityId, EventEmitter, FocusHandle,
7 InteractiveElement, Interactivity, IntoElement, KeyBinding, MouseButton, ParentElement,
8 RenderOnce, Role, SharedString, StatefulInteractiveElement, StyleRefinement, Styled, Window,
9 div, prelude::FluentBuilder as _,
10};
11
12use crate::{
13 StyledExt as _, TestSupportExt as _,
14 a11y_disabled::A11yDisabledExt as _,
15 actions::{SelectDown, SelectFirst, SelectLast, SelectUp},
16};
17
18const CONTEXT: &str = "Accordion";
19
20pub(crate) fn init(cx: &mut App) {
21 cx.bind_keys([
22 KeyBinding::new("up", SelectUp, Some(CONTEXT)),
23 KeyBinding::new("down", SelectDown, Some(CONTEXT)),
24 KeyBinding::new("home", SelectFirst, Some(CONTEXT)),
25 KeyBinding::new("end", SelectLast, Some(CONTEXT)),
26 ]);
27}
28
29#[derive(Clone, Debug)]
31pub struct AccordionItem {
32 value: SharedString,
33 label: SharedString,
34 disabled: bool,
35}
36
37impl AccordionItem {
38 pub fn new(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
39 Self {
40 value: value.into(),
41 label: label.into(),
42 disabled: false,
43 }
44 }
45
46 pub fn disabled(mut self, disabled: bool) -> Self {
47 self.disabled = disabled;
48 self
49 }
50
51 pub fn value(&self) -> &SharedString {
52 &self.value
53 }
54
55 pub fn label(&self) -> &SharedString {
56 &self.label
57 }
58
59 pub fn is_disabled(&self) -> bool {
60 self.disabled
61 }
62}
63
64#[derive(Clone, Debug, Eq, PartialEq)]
67pub enum AccordionEvent {
68 Change(Vec<SharedString>),
69}
70
71pub struct AccordionState {
77 items: Vec<AccordionItem>,
78 open: Vec<bool>,
79 multiple: bool,
80 root_focus: FocusHandle,
81 trigger_focus: Vec<FocusHandle>,
82 panel_focus: Vec<FocusHandle>,
83}
84
85impl AccordionState {
86 pub fn new(items: impl IntoIterator<Item = AccordionItem>, cx: &mut Context<Self>) -> Self {
87 let items: Vec<_> = items.into_iter().collect();
88 for (index, item) in items.iter().enumerate() {
89 assert!(
90 items[..index].iter().all(|other| other.value != item.value),
91 "AccordionItem values must be unique"
92 );
93 }
94 let trigger_focus = items.iter().map(|_| cx.focus_handle()).collect();
95 let panel_focus = items.iter().map(|_| cx.focus_handle()).collect();
96 Self {
97 open: vec![false; items.len()],
98 items,
99 multiple: false,
100 root_focus: cx.focus_handle(),
101 trigger_focus,
102 panel_focus,
103 }
104 }
105
106 pub fn multiple(mut self, multiple: bool) -> Self {
112 assert!(
113 multiple || self.open.iter().filter(|open| **open).count() <= 1,
114 "AccordionState single-open mode cannot have multiple open items"
115 );
116 self.multiple = multiple;
117 self
118 }
119
120 pub fn default_open<V: AsRef<str>>(mut self, values: impl IntoIterator<Item = V>) -> Self {
127 self.open.fill(false);
128 for value in values {
129 let index = self
130 .items
131 .iter()
132 .position(|item| item.value.as_ref() == value.as_ref() && !item.disabled)
133 .expect("AccordionState default_open must identify enabled AccordionItems");
134 self.open[index] = true;
135 }
136 assert!(
137 self.multiple || self.open.iter().filter(|open| **open).count() <= 1,
138 "AccordionState single-open mode cannot have multiple open items"
139 );
140 self
141 }
142
143 pub fn items(&self) -> &[AccordionItem] {
144 &self.items
145 }
146
147 pub fn is_open(&self, index: usize) -> bool {
148 self.open[index]
149 }
150
151 pub fn open_values(&self) -> Vec<SharedString> {
153 self.items
154 .iter()
155 .zip(&self.open)
156 .filter_map(|(item, open)| open.then(|| item.value.clone()))
157 .collect()
158 }
159
160 pub fn trigger_focus_handle(&self, index: usize) -> &FocusHandle {
162 &self.trigger_focus[index]
163 }
164
165 pub fn panel_focus_handle(&self, index: usize) -> &FocusHandle {
167 &self.panel_focus[index]
168 }
169
170 pub fn toggle(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
177 if self.items[index].disabled {
178 return;
179 }
180 let mut next = self.open.clone();
181 if next[index] {
182 next[index] = false;
183 } else {
184 if !self.multiple {
185 next.fill(false);
186 }
187 next[index] = true;
188 }
189 self.set_open(next, Some(index), window, cx);
190 }
191
192 pub fn close(&mut self, window: &mut Window, cx: &mut Context<Self>) {
196 self.set_open(vec![false; self.items.len()], None, window, cx);
197 }
198
199 fn set_open(
200 &mut self,
201 next: Vec<bool>,
202 requested_header: Option<usize>,
203 window: &mut Window,
204 cx: &mut Context<Self>,
205 ) {
206 if self.open == next {
207 return;
208 }
209 if let Some(previous) = self.open.iter().enumerate().find_map(|(index, open)| {
210 (*open && !next[index] && self.panel_focus[index].contains_focused(window, cx))
211 .then_some(index)
212 }) {
213 let target = &self.trigger_focus[requested_header.unwrap_or(previous)];
214 if self.root_focus.contains(target, window) {
217 target.focus(window, cx);
218 }
219 }
220 self.open = next;
221 cx.emit(AccordionEvent::Change(self.open_values()));
222 cx.notify();
223 window.refresh();
224 }
225
226 fn focused_index(&self, window: &Window) -> Option<usize> {
227 self.trigger_focus
228 .iter()
229 .position(|focus| focus.is_focused(window))
230 }
231
232 fn move_focus(&self, forward: bool, window: &mut Window, cx: &mut Context<Self>) {
233 let Some(current) = self.focused_index(window) else {
234 cx.propagate();
235 return;
236 };
237 let len = self.items.len();
238 if let Some(next) = (1..=len)
239 .map(|step| {
240 if forward {
241 (current + step) % len
242 } else {
243 (current + len - step) % len
244 }
245 })
246 .find(|&index| !self.items[index].disabled)
247 {
248 self.trigger_focus[next].focus(window, cx);
249 }
250 }
251
252 fn focus_edge(&self, last: bool, window: &mut Window, cx: &mut Context<Self>) {
253 if self.focused_index(window).is_none() {
254 cx.propagate();
255 return;
256 }
257 let next = if last {
258 self.items.iter().rposition(|item| !item.disabled)
259 } else {
260 self.items.iter().position(|item| !item.disabled)
261 };
262 if let Some(next) = next {
263 self.trigger_focus[next].focus(window, cx);
264 }
265 }
266}
267
268impl EventEmitter<AccordionEvent> for AccordionState {}
269
270fn part_id(state: EntityId, part: &'static str, index: usize) -> ElementId {
271 (ElementId::from((part, state)), index.to_string()).into()
272}
273
274#[derive(IntoElement)]
277pub struct Accordion {
278 base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
279 state: Entity<AccordionState>,
280 style: StyleRefinement,
281 children: Vec<AnyElement>,
282}
283
284impl Accordion {
285 pub fn new(id: impl Into<ElementId>, state: &Entity<AccordionState>) -> Self {
286 Self {
287 base: div().id(id).test_support(),
288 state: state.clone(),
289 style: StyleRefinement::default(),
290 children: Vec::new(),
291 }
292 }
293}
294
295impl Styled for Accordion {
296 fn style(&mut self) -> &mut StyleRefinement {
297 &mut self.style
298 }
299}
300
301impl ParentElement for Accordion {
302 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
303 self.children.extend(elements);
304 }
305}
306
307impl InteractiveElement for Accordion {
308 fn interactivity(&mut self) -> &mut Interactivity {
309 self.base.interactivity()
310 }
311}
312
313impl StatefulInteractiveElement for Accordion {}
314
315impl RenderOnce for Accordion {
316 fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
317 let root_focus = self.state.read(cx).root_focus.clone();
318 let previous = self.state.clone();
319 let next = self.state.clone();
320 let first = self.state.clone();
321 let last = self.state;
322 self.base
323 .role(Role::Group)
324 .key_context(CONTEXT)
325 .track_focus(&root_focus.tab_stop(false))
326 .on_action(move |_: &SelectUp, window, cx| {
327 previous.update(cx, |state, cx| state.move_focus(false, window, cx));
328 })
329 .on_action(move |_: &SelectDown, window, cx| {
330 next.update(cx, |state, cx| state.move_focus(true, window, cx));
331 })
332 .on_action(move |_: &SelectFirst, window, cx| {
333 first.update(cx, |state, cx| state.focus_edge(false, window, cx));
334 })
335 .on_action(move |_: &SelectLast, window, cx| {
336 last.update(cx, |state, cx| state.focus_edge(true, window, cx));
337 })
338 .children(self.children)
339 .refine_style(&self.style)
340 }
341}
342
343#[derive(IntoElement)]
349pub struct AccordionHeader {
350 base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
351 state: Entity<AccordionState>,
352 index: usize,
353 heading_level: usize,
354 style: StyleRefinement,
355 children: Vec<AnyElement>,
356}
357
358impl AccordionHeader {
359 pub fn new(state: &Entity<AccordionState>, index: usize) -> Self {
361 Self {
362 base: div()
363 .id(part_id(state.entity_id(), "accordion-trigger", index))
364 .test_support(),
365 state: state.clone(),
366 index,
367 heading_level: 3,
368 style: StyleRefinement::default(),
369 children: Vec::new(),
370 }
371 }
372
373 pub fn heading_level(mut self, level: usize) -> Self {
375 assert!(level > 0, "AccordionHeader heading_level must be positive");
376 self.heading_level = level;
377 self
378 }
379}
380
381impl Styled for AccordionHeader {
382 fn style(&mut self) -> &mut StyleRefinement {
383 &mut self.style
384 }
385}
386
387impl ParentElement for AccordionHeader {
388 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
389 self.children.extend(elements);
390 }
391}
392
393impl InteractiveElement for AccordionHeader {
394 fn interactivity(&mut self) -> &mut Interactivity {
395 self.base.interactivity()
396 }
397}
398
399impl StatefulInteractiveElement for AccordionHeader {}
400
401impl RenderOnce for AccordionHeader {
402 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
403 let model = self.state.read(cx);
404 let item = model
405 .items
406 .get(self.index)
407 .expect("AccordionHeader index must identify an item");
408 let disabled = item.disabled;
409 let expanded = model.is_open(self.index);
410 let label = item.label.clone();
411 let focus = model.trigger_focus_handle(self.index).clone();
412 let heading_id = part_id(self.state.entity_id(), "accordion-heading", self.index);
413 let index = self.index;
414 let click_state = self.state;
415 let button = self
416 .base
417 .role(Role::Button)
418 .aria_label(label)
419 .aria_expanded(expanded)
420 .when(!disabled || focus.is_focused(window), |this| {
421 this.track_focus(&focus.tab_stop(!disabled))
422 })
423 .when(disabled, |this| {
424 this.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
425 })
426 .when(!disabled, |this| {
427 this.on_click(move |_, window, cx| {
428 click_state.update(cx, |state, cx| state.toggle(index, window, cx));
429 })
430 })
431 .children(self.children)
432 .refine_style(&self.style)
433 .a11y_disabled(disabled);
434
435 div()
436 .id(heading_id)
437 .test_support()
438 .role(Role::Heading)
439 .aria_level(self.heading_level)
440 .child(button)
441 }
442}
443
444#[derive(IntoElement)]
453pub struct AccordionPanel {
454 base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
455 state: Entity<AccordionState>,
456 index: usize,
457 tab_stop: bool,
458 style: StyleRefinement,
459 children: Vec<AnyElement>,
460}
461
462impl AccordionPanel {
463 pub fn new(state: &Entity<AccordionState>, index: usize) -> Self {
465 Self {
466 base: div()
467 .id(part_id(state.entity_id(), "accordion-panel", index))
468 .test_support(),
469 state: state.clone(),
470 index,
471 tab_stop: false,
472 style: StyleRefinement::default(),
473 children: Vec::new(),
474 }
475 }
476
477 pub fn tab_stop(mut self, tab_stop: bool) -> Self {
478 self.tab_stop = tab_stop;
479 self
480 }
481}
482
483impl Styled for AccordionPanel {
484 fn style(&mut self) -> &mut StyleRefinement {
485 &mut self.style
486 }
487}
488
489impl ParentElement for AccordionPanel {
490 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
491 self.children.extend(elements);
492 }
493}
494
495impl InteractiveElement for AccordionPanel {
496 fn interactivity(&mut self) -> &mut Interactivity {
497 self.base.interactivity()
498 }
499}
500
501impl StatefulInteractiveElement for AccordionPanel {}
502
503impl RenderOnce for AccordionPanel {
504 fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
505 let model = self.state.read(cx);
506 let item = model
507 .items
508 .get(self.index)
509 .expect("AccordionPanel index must identify an item");
510 if !model.is_open(self.index) {
511 return gpui::Empty.into_any_element();
512 }
513 let focus = model.panel_focus_handle(self.index).clone();
514 self.base
515 .role(Role::Region)
516 .aria_label(item.label.clone())
517 .track_focus(&focus.tab_stop(self.tab_stop))
518 .children(self.children)
519 .refine_style(&self.style)
520 .into_any_element()
521 }
522}
523
524#[cfg(test)]
525mod tests {
526 use std::{cell::RefCell, rc::Rc};
527
528 use gpui::{
529 AppContext as _, Element as _, Focusable as _, KeyDownEvent, KeyUpEvent, Keystroke,
530 Modifiers, Render, Subscription, TestAppContext, VisualTestContext, accesskit, canvas, px,
531 };
532
533 use super::*;
534 use crate::{Button, Input, InputBase, InputState, Root};
535
536 struct Harness {
537 state: Entity<AccordionState>,
538 input: Entity<InputState>,
539 before: FocusHandle,
540 after: FocusHandle,
541 show_host: bool,
542 unhandled_keys: Rc<RefCell<Vec<String>>>,
543 _subscription: Subscription,
544 }
545
546 impl Render for Harness {
547 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
548 let unhandled_keys = self.unhandled_keys.clone();
549 div()
550 .w(px(400.))
551 .flex()
552 .flex_col()
553 .on_key_down(move |event, _, _| {
554 unhandled_keys
555 .borrow_mut()
556 .push(event.keystroke.key.clone());
557 })
558 .child(
559 Button::new("before")
560 .debug_selector(|| "before".into())
561 .track_focus(&self.before)
562 .h(px(32.))
563 .child("Before"),
564 )
565 .when(self.show_host, |this| {
566 this.child(
567 Accordion::new("accordion", &self.state)
568 .flex()
569 .flex_col()
570 .children(self.state.read(cx).items().iter().enumerate().map(
571 |(index, item)| {
572 div()
573 .flex()
574 .flex_col()
575 .gap(px(8.))
576 .child(
577 AccordionHeader::new(&self.state, index)
578 .debug_selector(move || {
579 format!("header-{index}").into()
580 })
581 .h(px(32.))
582 .child(item.label().clone()),
583 )
584 .child(
585 AccordionPanel::new(&self.state, index)
586 .tab_stop(index == 2)
587 .h(px(40.))
588 .child(if index == 0 {
589 InputBase::new("panel-input")
590 .debug_selector(|| "panel-input".into())
591 .h(px(32.))
592 .child(Input::new(&self.input))
593 .into_any_element()
594 } else {
595 div().child("Panel text").into_any_element()
596 }),
597 )
598 },
599 )),
600 )
601 })
602 .child(
603 Button::new("after")
604 .debug_selector(|| "after".into())
605 .track_focus(&self.after)
606 .h(px(32.))
607 .child("After"),
608 )
609 }
610 }
611
612 type Changes = Rc<RefCell<Vec<Vec<SharedString>>>>;
613
614 fn items() -> Vec<AccordionItem> {
615 vec![
616 AccordionItem::new("general", "General"),
617 AccordionItem::new("disabled", "Unavailable").disabled(true),
618 AccordionItem::new("help", "Help"),
619 AccordionItem::new("advanced", "Advanced"),
620 ]
621 }
622
623 fn harness(
624 cx: &mut TestAppContext,
625 items: Vec<AccordionItem>,
626 multiple: bool,
627 ) -> (&mut VisualTestContext, Entity<Harness>, Changes) {
628 cx.update(crate::init);
629 let (root, cx) = cx.add_window_view(move |window, cx| {
630 let content = cx.new(|cx| {
631 let state = cx.new(|cx| AccordionState::new(items, cx).multiple(multiple));
632 let subscription = cx.observe(&state, |_, _, cx| cx.notify());
633 Harness {
634 state,
635 input: cx.new(|cx| InputState::new(window, cx)),
636 before: cx.focus_handle().tab_stop(true),
637 after: cx.focus_handle().tab_stop(true),
638 show_host: true,
639 unhandled_keys: Rc::new(RefCell::new(Vec::new())),
640 _subscription: subscription,
641 }
642 });
643 Root::new(content, window, cx)
644 });
645 let view = root
646 .read_with(cx, |root, _| root.view().clone())
647 .downcast::<Harness>()
648 .unwrap();
649 let changes = Rc::new(RefCell::new(Vec::new()));
650 cx.update(|window, cx| {
651 let state = view.read(cx).state.clone();
652 let changes = changes.clone();
653 cx.subscribe(&state, move |state, event: &AccordionEvent, cx| {
654 let AccordionEvent::Change(value) = event;
655 assert_eq!(state.read(cx).open_values(), *value);
656 changes.borrow_mut().push(value.clone());
657 })
658 .detach();
659 window.activate_window();
660 let before = view.read(cx).before.clone();
661 before.focus(window, cx);
662 window.draw(cx).clear(cx);
663 });
664 cx.run_until_parked();
665 (cx, view, changes)
666 }
667
668 fn draw(cx: &mut VisualTestContext) {
669 cx.update(|window, cx| window.draw(cx).clear(cx));
670 }
671
672 fn press(cx: &mut VisualTestContext, key: &str) {
673 let keystroke =
674 cx.update(|_, cx| Keystroke::parse_with_os(key, cx.platform_info().os).unwrap());
675 cx.simulate_event(KeyDownEvent {
676 keystroke: keystroke.clone(),
677 is_held: false,
678 prefer_character_input: false,
679 });
680 cx.simulate_event(KeyUpEvent { keystroke });
681 draw(cx);
682 }
683
684 fn click_header(cx: &mut VisualTestContext, index: usize) {
685 let selector = ["header-0", "header-1", "header-2", "header-3"][index];
686 let position = cx.debug_bounds(selector).unwrap().center();
687 cx.simulate_click(position, Modifiers::default());
688 draw(cx);
689 }
690
691 fn assert_header(cx: &mut VisualTestContext, view: &Entity<Harness>, index: usize) {
692 cx.update(|window, cx| {
693 assert!(
694 view.read(cx)
695 .state
696 .read(cx)
697 .trigger_focus_handle(index)
698 .is_focused(window)
699 );
700 });
701 }
702
703 fn assert_open(cx: &mut VisualTestContext, view: &Entity<Harness>, open: Option<usize>) {
704 cx.update(|_, cx| {
705 let state = view.read(cx).state.read(cx);
706 let expected: Vec<_> = open
707 .map(|index| state.items()[index].value().clone())
708 .into_iter()
709 .collect();
710 assert_eq!(state.open_values(), expected);
711 });
712 }
713
714 #[gpui::test]
715 fn multiple_defaults_follow_item_order_and_single_mode_keeps_one_value(
716 cx: &mut TestAppContext,
717 ) {
718 cx.update(|cx| {
719 let multiple = cx.new(|cx| {
720 AccordionState::new(items(), cx)
721 .multiple(true)
722 .default_open(["help", "general", "help"])
723 });
724 let state = multiple.read(cx);
725 assert_eq!(
726 state.open_values(),
727 [SharedString::from("general"), SharedString::from("help")]
728 );
729 assert!(state.is_open(0));
730 assert!(!state.is_open(1));
731 assert!(state.is_open(2));
732 assert!(!state.is_open(3));
733
734 let single = cx.new(|cx| AccordionState::new(items(), cx).default_open(["help"]));
735 assert_eq!(single.read(cx).open_values(), [SharedString::from("help")]);
736 });
737 }
738
739 #[gpui::test]
740 fn multiple_activation_keeps_other_panels_and_restores_only_closing_content(
741 cx: &mut TestAppContext,
742 ) {
743 let (cx, view, changes) = harness(cx, items(), true);
744 click_header(cx, 2);
745 click_header(cx, 0);
746 cx.simulate_keystrokes("down down");
747 draw(cx);
748 assert_header(cx, &view, 3);
749 press(cx, "enter");
750 click_header(cx, 1);
751 press(cx, "space");
752 assert_eq!(
753 *changes.borrow(),
754 [
755 vec![SharedString::from("help")],
756 vec![SharedString::from("general"), SharedString::from("help")],
757 vec![
758 SharedString::from("general"),
759 SharedString::from("help"),
760 SharedString::from("advanced"),
761 ],
762 vec![SharedString::from("general"), SharedString::from("help")],
763 ]
764 );
765
766 #[cfg(feature = "test-support")]
767 cx.update(|window, cx| {
768 let state = view.read(cx).state.clone();
769 for index in [0, 2] {
770 let header = crate::test_support::find(
771 window,
772 &[],
773 &part_id(state.entity_id(), "accordion-trigger", index),
774 )
775 .unwrap();
776 assert_eq!(header.expanded(), Some(true));
777 let panel = crate::test_support::find(
778 window,
779 &[],
780 &part_id(state.entity_id(), "accordion-panel", index),
781 )
782 .unwrap();
783 assert_eq!(panel.role(), Some(Role::Region));
784 assert_eq!(
785 panel.label(),
786 Some(state.read(cx).items()[index].label().as_ref())
787 );
788 }
789 });
790
791 cx.update(|window, cx| {
792 let input_focus = view.read(cx).input.focus_handle(cx);
793 input_focus.focus(window, cx);
794 let state = view.read(cx).state.clone();
795 state.update(cx, |state, cx| state.toggle(3, window, cx));
796 assert!(input_focus.is_focused(window));
797 });
798 draw(cx);
799 cx.update(|window, cx| {
800 let state = view.read(cx).state.clone();
801 state.update(cx, |state, cx| state.toggle(2, window, cx));
802 assert!(view.read(cx).input.focus_handle(cx).is_focused(window));
803 });
804 draw(cx);
805 cx.update(|window, cx| {
806 let state = view.read(cx).state.clone();
807 state.update(cx, |state, cx| state.toggle(0, window, cx));
808 });
809 draw(cx);
810 assert_header(cx, &view, 0);
811 assert_open(cx, &view, Some(3));
812 assert!(cx.debug_bounds("panel-input").is_none());
813
814 cx.update(|window, cx| {
815 let state = view.read(cx).state.clone();
816 state.update(cx, |state, cx| state.toggle(2, window, cx));
817 });
818 draw(cx);
819 cx.update(|window, cx| {
820 let state = view.read(cx).state.clone();
821 let panel_focus = state.read(cx).panel_focus_handle(2).clone();
822 panel_focus.focus(window, cx);
823 state.update(cx, |state, cx| state.close(window, cx));
824 });
825 draw(cx);
826 assert_header(cx, &view, 2);
827 assert_open(cx, &view, None);
828 let count = changes.borrow().len();
829 assert_eq!(changes.borrow().last(), Some(&Vec::new()));
830 cx.update(|window, cx| {
831 let state = view.read(cx).state.clone();
832 state.update(cx, |state, cx| state.close(window, cx));
833 });
834 assert_eq!(changes.borrow().len(), count);
835 }
836
837 #[gpui::test]
838 fn every_enabled_header_is_a_tab_stop_and_arrow_focus_does_not_expand(cx: &mut TestAppContext) {
839 let (cx, view, changes) = harness(cx, items(), false);
840 cx.simulate_keystrokes("tab");
841 draw(cx);
842 assert_header(cx, &view, 0);
843 for (key, index) in [
844 ("up", 3),
845 ("home", 0),
846 ("down", 2),
847 ("end", 3),
848 ("down", 0),
849 ("tab", 2),
850 ("tab", 3),
851 ] {
852 cx.simulate_keystrokes(key);
853 draw(cx);
854 assert_header(cx, &view, index);
855 assert_open(cx, &view, None);
856 }
857 cx.simulate_keystrokes("tab");
858 draw(cx);
859 cx.update(|window, cx| assert!(view.read(cx).after.is_focused(window)));
860 cx.simulate_keystrokes("shift-tab shift-tab shift-tab");
861 draw(cx);
862 assert_header(cx, &view, 0);
863 cx.update(|_, cx| view.read(cx).unhandled_keys.borrow_mut().clear());
864 cx.simulate_keystrokes("left right");
865 draw(cx);
866 cx.update(|_, cx| {
867 assert_eq!(*view.read(cx).unhandled_keys.borrow(), ["left", "right"]);
868 });
869 assert!(changes.borrow().is_empty());
870 }
871
872 #[gpui::test]
873 fn native_pointer_enter_and_space_toggle_once_and_ignore_disabled_items(
874 cx: &mut TestAppContext,
875 ) {
876 let (cx, view, changes) = harness(cx, items(), false);
877 let collapsed_after = cx.debug_bounds("after").unwrap().origin.y;
878 let first_header = cx.debug_bounds("header-0").unwrap();
879 assert_eq!(collapsed_after - first_header.origin.y, px(128.));
880 click_header(cx, 0);
881 assert_header(cx, &view, 0);
882 assert_open(cx, &view, Some(0));
883 assert_eq!(
884 cx.debug_bounds("after").unwrap().origin.y - collapsed_after,
885 px(48.)
886 );
887 press(cx, "enter");
888 assert_open(cx, &view, None);
889 assert_eq!(cx.debug_bounds("after").unwrap().origin.y, collapsed_after);
890 press(cx, "space");
891 assert_open(cx, &view, Some(0));
892 click_header(cx, 1);
893 cx.update(|window, cx| {
894 let state = view.read(cx).state.clone();
895 state.update(cx, |state, cx| state.toggle(1, window, cx));
896 });
897 assert_header(cx, &view, 0);
898 assert_open(cx, &view, Some(0));
899 click_header(cx, 2);
900 assert_open(cx, &view, Some(2));
901 press(cx, "space");
902 assert_open(cx, &view, None);
903 assert_eq!(
904 *changes.borrow(),
905 [Some("general"), None, Some("general"), Some("help"), None].map(|value| value
906 .map(SharedString::from)
907 .into_iter()
908 .collect::<Vec<_>>())
909 );
910 }
911
912 #[gpui::test]
913 fn panel_data_survives_unmount_and_collapsing_focused_content_restores_header(
914 cx: &mut TestAppContext,
915 ) {
916 let (cx, view, _) = harness(cx, items(), false);
917 cx.simulate_keystrokes("tab");
918 draw(cx);
919 press(cx, "enter");
920 cx.simulate_keystrokes("tab");
921 draw(cx);
922 cx.update(|window, cx| {
923 assert!(view.read(cx).input.focus_handle(cx).is_focused(window));
924 });
925 cx.simulate_input("retained");
926 draw(cx);
927 cx.simulate_keystrokes("home");
928 draw(cx);
929 cx.update(|window, cx| {
930 let input = &view.read(cx).input;
931 assert!(input.focus_handle(cx).is_focused(window));
932 assert_eq!(input.read(cx).selected_range(), 0..0);
933 });
934 cx.simulate_keystrokes("end");
935 draw(cx);
936 cx.update(|window, cx| {
937 let input = &view.read(cx).input;
938 assert!(input.focus_handle(cx).is_focused(window));
939 assert_eq!(input.read(cx).selected_range(), 8..8);
940 });
941 assert_open(cx, &view, Some(0));
942 let restored_before_event = Rc::new(RefCell::new(Vec::new()));
943 let subscription = cx.update(|window, cx| {
944 view.update(cx, |view, cx| {
945 let restored_before_event = restored_before_event.clone();
946 cx.subscribe_in(
947 &view.state,
948 window,
949 move |_, state, _: &AccordionEvent, window, cx| {
950 restored_before_event
951 .borrow_mut()
952 .push(state.read(cx).trigger_focus_handle(2).is_focused(window));
953 },
954 )
955 })
956 });
957 cx.update(|window, cx| {
958 let state = view.read(cx).state.clone();
959 state.update(cx, |state, cx| state.toggle(2, window, cx));
960 });
961 draw(cx);
962 assert_header(cx, &view, 2);
963 assert!(cx.debug_bounds("panel-input").is_none());
964 cx.simulate_keystrokes("tab");
965 draw(cx);
966 cx.update(|window, cx| {
967 assert!(
968 view.read(cx)
969 .state
970 .read(cx)
971 .panel_focus_handle(2)
972 .is_focused(window)
973 );
974 view.read(cx).unhandled_keys.borrow_mut().clear();
975 });
976 cx.simulate_keystrokes("up down home end");
977 draw(cx);
978 assert_open(cx, &view, Some(2));
979 cx.update(|window, cx| {
980 assert_eq!(
981 *view.read(cx).unhandled_keys.borrow(),
982 ["up", "down", "home", "end"]
983 );
984 let state = view.read(cx).state.clone();
985 state.update(cx, |state, cx| state.close(window, cx));
986 });
987 draw(cx);
988 assert_header(cx, &view, 2);
989 assert_eq!(*restored_before_event.borrow(), [true, true]);
990 drop(subscription);
991 cx.update(|window, cx| {
992 let after = view.read(cx).after.clone();
993 after.focus(window, cx);
994 let state = view.read(cx).state.clone();
995 state.update(cx, |state, cx| state.toggle(0, window, cx));
996 assert!(view.read(cx).after.is_focused(window));
997 assert_eq!(view.read(cx).input.read(cx).value(), "retained");
998 });
999 draw(cx);
1000 assert!(cx.debug_bounds("panel-input").is_some());
1001 cx.update(|window, cx| {
1002 let state = view.read(cx).state.clone();
1003 state.update(cx, |state, cx| state.close(window, cx));
1004 assert!(view.read(cx).after.is_focused(window));
1005 });
1006 }
1007
1008 #[gpui::test]
1009 fn closing_after_host_removal_does_not_focus_a_detached_header(cx: &mut TestAppContext) {
1010 let (cx, view, changes) = harness(cx, items(), false);
1011 click_header(cx, 2);
1012 cx.simulate_keystrokes("tab");
1013 draw(cx);
1014 view.update(cx, |view, cx| {
1015 view.show_host = false;
1016 cx.notify();
1017 });
1018 draw(cx);
1019 cx.update(|window, cx| {
1020 let state = view.read(cx).state.clone();
1021 state.update(cx, |state, cx| {
1022 state.close(window, cx);
1023 state.close(window, cx);
1024 });
1025 assert!(!state.read(cx).trigger_focus_handle(2).is_focused(window));
1026 });
1027 assert_eq!(
1028 *changes.borrow(),
1029 [vec![SharedString::from("help")], vec![]]
1030 );
1031 }
1032
1033 #[gpui::test]
1034 fn empty_disabled_and_single_enabled_collections_preserve_tab_navigation(
1035 cx: &mut TestAppContext,
1036 ) {
1037 for items in [
1038 Vec::new(),
1039 vec![AccordionItem::new("disabled", "Unavailable").disabled(true)],
1040 ] {
1041 let (cx, view, changes) = harness(cx, items, false);
1042 cx.simulate_keystrokes("tab");
1043 draw(cx);
1044 cx.update(|window, cx| assert!(view.read(cx).after.is_focused(window)));
1045 assert_open(cx, &view, None);
1046 assert!(changes.borrow().is_empty());
1047 }
1048 let (cx, view, changes) = harness(cx, vec![AccordionItem::new("only", "Only")], false);
1049 cx.simulate_keystrokes("tab up down home end");
1050 draw(cx);
1051 assert_header(cx, &view, 0);
1052 assert_open(cx, &view, None);
1053 assert!(changes.borrow().is_empty());
1054 }
1055
1056 #[gpui::test]
1057 fn heading_level_is_written_to_native_metadata(cx: &mut TestAppContext) {
1058 struct Probe {
1059 state: Entity<AccordionState>,
1060 nodes: Rc<RefCell<Vec<accesskit::Node>>>,
1061 }
1062 impl Render for Probe {
1063 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1064 let state = self.state.clone();
1065 let nodes = self.nodes.clone();
1066 canvas(
1067 move |_, window, cx| {
1068 let mut captured = nodes.borrow_mut();
1069 captured.clear();
1070 let heading = AccordionHeader::new(&state, 0)
1071 .heading_level(2)
1072 .render(window, cx)
1073 .into_element();
1074 let mut node = accesskit::Node::new(heading.a11y_role().unwrap());
1075 heading.write_a11y_info(&mut node);
1076 captured.push(node);
1077 },
1078 |_, _, _, _| {},
1079 )
1080 }
1081 }
1082 let nodes = Rc::new(RefCell::new(Vec::new()));
1083 let (_, cx) = cx.add_window_view({
1084 let nodes = nodes.clone();
1085 move |_, cx| Probe {
1086 state: cx
1087 .new(|cx| AccordionState::new([AccordionItem::new("general", "General")], cx)),
1088 nodes,
1089 }
1090 });
1091 draw(cx);
1092 let nodes = nodes.borrow();
1093 assert_eq!(nodes[0].role(), Role::Heading);
1094 assert_eq!(nodes[0].level(), Some(2));
1095 }
1096
1097 #[cfg(feature = "test-support")]
1098 #[gpui::test]
1099 fn accessibility_reports_expanded_disabled_and_only_the_mounted_region(
1100 cx: &mut TestAppContext,
1101 ) {
1102 let (cx, view, _) = harness(cx, items(), false);
1103 cx.update(|window, cx| {
1104 let state = view.read(cx).state.clone();
1105 for (index, item) in state.read(cx).items().iter().enumerate() {
1106 let heading = crate::test_support::find(
1107 window,
1108 &[],
1109 &part_id(state.entity_id(), "accordion-heading", index),
1110 )
1111 .unwrap();
1112 assert_eq!(heading.role(), Some(Role::Heading));
1113 let button = crate::test_support::find(
1114 window,
1115 &[],
1116 &part_id(state.entity_id(), "accordion-trigger", index),
1117 )
1118 .unwrap();
1119 assert_eq!(button.role(), Some(Role::Button));
1120 assert_eq!(button.label(), Some(item.label().as_ref()));
1121 assert_eq!(button.expanded(), Some(false));
1122 assert_eq!(button.disabled(), (index == 1).then_some(true));
1123 }
1124 assert!(
1125 crate::test_support::snapshots(window)
1126 .iter()
1127 .all(|node| node.role() != Some(Role::Region))
1128 );
1129 assert!(crate::test_support::find(window, &[], &"panel-input".into()).is_none());
1130 });
1131 click_header(cx, 0);
1132 cx.update(|window, cx| {
1133 let state = view.read(cx).state.clone();
1134 let button = crate::test_support::find(
1135 window,
1136 &[],
1137 &part_id(state.entity_id(), "accordion-trigger", 0),
1138 )
1139 .unwrap();
1140 assert_eq!(button.expanded(), Some(true));
1141 let regions: Vec<_> = crate::test_support::snapshots(window)
1142 .into_iter()
1143 .filter(|node| node.role() == Some(Role::Region))
1144 .collect();
1145 assert_eq!(regions.len(), 1);
1146 assert_eq!(regions[0].label(), Some("General"));
1147 assert!(crate::test_support::find(window, &[], &"panel-input".into()).is_some());
1148 });
1149 click_header(cx, 2);
1150 cx.update(|window, cx| {
1151 let state = view.read(cx).state.clone();
1152 assert!(
1153 crate::test_support::find(
1154 window,
1155 &[],
1156 &part_id(state.entity_id(), "accordion-panel", 0),
1157 )
1158 .is_none()
1159 );
1160 assert!(crate::test_support::find(window, &[], &"panel-input".into()).is_none());
1161 let regions: Vec<_> = crate::test_support::snapshots(window)
1162 .into_iter()
1163 .filter(|node| node.role() == Some(Role::Region))
1164 .collect();
1165 assert_eq!(regions.len(), 1);
1166 assert_eq!(regions[0].label(), Some("Help"));
1167 });
1168 }
1169}