1use gpui::{
6 AnyElement, App, Context, ElementId, Entity, EventEmitter, FocusHandle, InteractiveElement,
7 Interactivity, IntoElement, ParentElement, RenderOnce, Role, SharedString,
8 StatefulInteractiveElement, StyleRefinement, Styled, Window, div, prelude::FluentBuilder as _,
9};
10
11use crate::{Button, TestSupportExt as _};
12
13#[derive(Clone, Copy, Debug, Eq, PartialEq)]
15pub enum CollapsibleEvent {
16 Change(bool),
17}
18
19pub struct CollapsibleState {
26 open: bool,
27 disabled: bool,
28 root_focus: FocusHandle,
29 trigger_focus: FocusHandle,
30 content_focus: FocusHandle,
31}
32
33impl CollapsibleState {
34 pub fn new(cx: &mut Context<Self>) -> Self {
35 Self {
36 open: false,
37 disabled: false,
38 root_focus: cx.focus_handle(),
39 trigger_focus: cx.focus_handle(),
40 content_focus: cx.focus_handle(),
41 }
42 }
43
44 pub fn default_open(mut self, open: bool) -> Self {
46 self.open = open;
47 self
48 }
49
50 pub fn is_open(&self) -> bool {
51 self.open
52 }
53
54 pub fn is_disabled(&self) -> bool {
55 self.disabled
56 }
57
58 pub fn trigger_focus_handle(&self) -> &FocusHandle {
59 &self.trigger_focus
60 }
61
62 pub fn content_focus_handle(&self) -> &FocusHandle {
63 &self.content_focus
64 }
65
66 pub fn set_open(&mut self, open: bool, window: &mut Window, cx: &mut Context<Self>) {
74 if self.open == open {
75 return;
76 }
77 if !open && self.content_focus.contains_focused(window, cx) {
78 if !self.disabled && self.root_focus.contains(&self.trigger_focus, window) {
79 self.trigger_focus.focus(window, cx);
80 } else if self.disabled && self.root_focus.contains(&self.content_focus, window) {
81 self.root_focus.focus(window, cx);
82 }
83 }
84 self.open = open;
85 cx.emit(CollapsibleEvent::Change(open));
86 cx.notify();
87 window.refresh();
88 }
89
90 pub fn toggle(&mut self, window: &mut Window, cx: &mut Context<Self>) {
92 if !self.disabled {
93 self.set_open(!self.open, window, cx);
94 }
95 }
96
97 pub fn set_disabled(&mut self, disabled: bool, window: &mut Window, cx: &mut Context<Self>) {
100 if self.disabled == disabled {
101 return;
102 }
103 self.disabled = disabled;
104 cx.notify();
105 window.refresh();
106 }
107}
108
109impl EventEmitter<CollapsibleEvent> for CollapsibleState {}
110
111#[derive(IntoElement)]
116pub struct Collapsible {
117 base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
118 state: Entity<CollapsibleState>,
119}
120
121impl Collapsible {
122 pub fn new(id: impl Into<ElementId>, state: &Entity<CollapsibleState>) -> Self {
123 Self {
124 base: div().id(id).test_support(),
125 state: state.clone(),
126 }
127 }
128}
129
130impl Styled for Collapsible {
131 fn style(&mut self) -> &mut StyleRefinement {
132 self.base.style()
133 }
134}
135
136impl ParentElement for Collapsible {
137 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
138 self.base.extend(elements);
139 }
140}
141
142impl InteractiveElement for Collapsible {
143 fn interactivity(&mut self) -> &mut Interactivity {
144 self.base.interactivity()
145 }
146}
147
148impl StatefulInteractiveElement for Collapsible {}
149
150impl RenderOnce for Collapsible {
151 fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
152 let focus = self.state.read(cx).root_focus.clone();
153 self.base
154 .role(Role::Group)
155 .track_focus(&focus.tab_stop(false))
156 }
157}
158
159#[derive(IntoElement)]
163pub struct CollapsibleTrigger {
164 button: Button,
165 state: Entity<CollapsibleState>,
166}
167
168impl CollapsibleTrigger {
169 pub fn new(state: &Entity<CollapsibleState>) -> Self {
170 Self {
171 button: Button::new(("collapsible-trigger", state.entity_id())),
172 state: state.clone(),
173 }
174 }
175
176 pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
177 self.button = self.button.accessibility_label(label);
178 self
179 }
180}
181
182impl Styled for CollapsibleTrigger {
183 fn style(&mut self) -> &mut StyleRefinement {
184 self.button.style()
185 }
186}
187
188impl ParentElement for CollapsibleTrigger {
189 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
190 self.button.extend(elements);
191 }
192}
193
194impl InteractiveElement for CollapsibleTrigger {
195 fn interactivity(&mut self) -> &mut Interactivity {
196 self.button.interactivity()
197 }
198
199 crate::button::forward_hover_styles!(button);
200}
201
202impl StatefulInteractiveElement for CollapsibleTrigger {
203 crate::button::forward_active_styles!(button);
204}
205
206impl RenderOnce for CollapsibleTrigger {
207 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
208 let state = self.state.read(cx);
209 let open = state.open;
210 let disabled = state.disabled;
211 let focus = state.trigger_focus.clone();
212 let state = self.state;
213 self.button
214 .aria_expanded(open)
215 .disabled(disabled)
216 .track_focus(&focus)
217 .on_click(move |_, window, cx| {
218 state.update(cx, |state, cx| state.toggle(window, cx));
219 })
220 .render(window, cx)
221 }
222}
223
224#[derive(IntoElement)]
231pub struct CollapsibleContent {
232 base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
233 state: Entity<CollapsibleState>,
234 label: Option<SharedString>,
235 tab_stop: bool,
236}
237
238impl CollapsibleContent {
239 pub fn new(state: &Entity<CollapsibleState>) -> Self {
240 Self {
241 base: div()
242 .id(("collapsible-content", state.entity_id()))
243 .test_support(),
244 state: state.clone(),
245 label: None,
246 tab_stop: false,
247 }
248 }
249
250 pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
251 self.label = Some(label.into());
252 self
253 }
254
255 pub fn tab_stop(mut self, tab_stop: bool) -> Self {
256 self.tab_stop = tab_stop;
257 self
258 }
259}
260
261impl Styled for CollapsibleContent {
262 fn style(&mut self) -> &mut StyleRefinement {
263 self.base.style()
264 }
265}
266
267impl ParentElement for CollapsibleContent {
268 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
269 self.base.extend(elements);
270 }
271}
272
273impl InteractiveElement for CollapsibleContent {
274 fn interactivity(&mut self) -> &mut Interactivity {
275 self.base.interactivity()
276 }
277}
278
279impl StatefulInteractiveElement for CollapsibleContent {}
280
281impl RenderOnce for CollapsibleContent {
282 fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
283 let state = self.state.read(cx);
284 if !state.open {
285 return gpui::Empty.into_any_element();
286 }
287 let focus = state.content_focus.clone();
288 self.base
289 .role(Role::Region)
290 .when_some(self.label, |this, label| this.aria_label(label))
291 .track_focus(&focus.tab_stop(self.tab_stop))
292 .into_any_element()
293 }
294}
295
296#[cfg(test)]
297mod tests {
298 use std::{cell::RefCell, rc::Rc};
299
300 use gpui::{
301 AppContext as _, Focusable as _, KeyDownEvent, KeyUpEvent, Keystroke, Render, Subscription,
302 TestAppContext, VisualTestContext, px,
303 };
304
305 use super::*;
306 use crate::{Input, InputBase, InputState, Root};
307
308 struct Harness {
309 state: Entity<CollapsibleState>,
310 input: Entity<InputState>,
311 before: FocusHandle,
312 after: FocusHandle,
313 show_host: bool,
314 unhandled: Rc<RefCell<Vec<String>>>,
315 _subscription: Subscription,
316 }
317
318 impl Render for Harness {
319 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
320 let unhandled = self.unhandled.clone();
321 div()
322 .w(px(320.))
323 .flex()
324 .flex_col()
325 .on_key_down(move |event, _, _| {
326 unhandled.borrow_mut().push(event.keystroke.key.clone());
327 })
328 .child(
329 Button::new("before")
330 .track_focus(&self.before)
331 .h(px(32.))
332 .child("Before"),
333 )
334 .when(self.show_host, |this| {
335 this.child(
336 Collapsible::new("disclosure", &self.state)
337 .flex()
338 .flex_col()
339 .child(
340 CollapsibleTrigger::new(&self.state)
341 .accessibility_label("Options")
342 .debug_selector(|| "trigger".into())
343 .h(px(32.))
344 .child("Options"),
345 )
346 .child(
347 CollapsibleContent::new(&self.state)
348 .accessibility_label("Options")
349 .debug_selector(|| "content".into())
350 .h(px(40.))
351 .child(
352 InputBase::new("option-input")
353 .h(px(32.))
354 .child(Input::new(&self.input)),
355 ),
356 ),
357 )
358 })
359 .child(
360 Button::new("after")
361 .track_focus(&self.after)
362 .debug_selector(|| "after".into())
363 .h(px(32.))
364 .child("After"),
365 )
366 }
367 }
368
369 type Changes = Rc<RefCell<Vec<bool>>>;
370
371 fn harness(
372 cx: &mut TestAppContext,
373 open: bool,
374 ) -> (&mut VisualTestContext, Entity<Harness>, Changes) {
375 cx.update(crate::init);
376 let (root, cx) = cx.add_window_view(move |window, cx| {
377 let content = cx.new(|cx| {
378 let state = cx.new(|cx| CollapsibleState::new(cx).default_open(open));
379 let subscription = cx.observe(&state, |_, _, cx| cx.notify());
380 Harness {
381 state,
382 input: cx.new(|cx| InputState::new(window, cx)),
383 before: cx.focus_handle(),
384 after: cx.focus_handle(),
385 show_host: true,
386 unhandled: Rc::new(RefCell::new(Vec::new())),
387 _subscription: subscription,
388 }
389 });
390 Root::new(content, window, cx)
391 });
392 let view = root
393 .read_with(cx, |root, _| root.view().clone())
394 .downcast::<Harness>()
395 .unwrap();
396 let changes = Rc::new(RefCell::new(Vec::new()));
397 cx.update(|window, cx| {
398 let state = view.read(cx).state.clone();
399 let changes = changes.clone();
400 cx.subscribe(&state, move |state, event: &CollapsibleEvent, cx| {
401 let CollapsibleEvent::Change(open) = event;
402 assert_eq!(state.read(cx).is_open(), *open);
403 changes.borrow_mut().push(*open);
404 })
405 .detach();
406 window.activate_window();
407 view.read(cx).before.clone().focus(window, cx);
408 window.draw(cx).clear(cx);
409 });
410 cx.run_until_parked();
411 (cx, view, changes)
412 }
413
414 fn draw(cx: &mut VisualTestContext) {
415 cx.update(|window, cx| window.draw(cx).clear(cx));
416 }
417
418 fn press(cx: &mut VisualTestContext, key: &str) {
419 let keystroke =
420 cx.update(|_, cx| Keystroke::parse_with_os(key, cx.platform_info().os).unwrap());
421 cx.simulate_event(KeyDownEvent {
422 keystroke: keystroke.clone(),
423 is_held: false,
424 prefer_character_input: false,
425 });
426 cx.simulate_event(KeyUpEvent { keystroke });
427 draw(cx);
428 }
429
430 #[gpui::test]
431 fn disclosure_mounting_preserves_normal_focus_and_unbound_keys(cx: &mut TestAppContext) {
432 let (cx, view, changes) = harness(cx, false);
433 let collapsed_after = cx.debug_bounds("after").unwrap().origin.y;
434 assert!(cx.debug_bounds("content").is_none());
435 cx.simulate_keystrokes("tab");
436 draw(cx);
437 cx.update(|_, cx| view.read(cx).unhandled.borrow_mut().clear());
438 cx.simulate_keystrokes("up down home end");
439 draw(cx);
440 cx.update(|window, cx| {
441 let state = view.read(cx).state.read(cx);
442 assert!(state.trigger_focus_handle().is_focused(window));
443 assert!(!state.is_open());
444 assert_eq!(
445 *view.read(cx).unhandled.borrow(),
446 ["up", "down", "home", "end"]
447 );
448 #[cfg(feature = "test-support")]
449 {
450 let trigger = crate::test_support::find(
451 window,
452 &[],
453 &("collapsible-trigger", view.read(cx).state.entity_id()).into(),
454 )
455 .unwrap();
456 assert_eq!(trigger.role(), Some(Role::Button));
457 assert_eq!(trigger.label(), Some("Options"));
458 assert_eq!(trigger.expanded(), Some(false));
459 assert!(
460 crate::test_support::snapshots(window)
461 .iter()
462 .all(|node| node.role() != Some(Role::Region))
463 );
464 }
465 });
466 assert!(changes.borrow().is_empty());
467 press(cx, "space");
468 assert_eq!(
469 cx.debug_bounds("after").unwrap().origin.y - collapsed_after,
470 px(40.)
471 );
472 cx.update(|window, cx| {
473 let state = view.read(cx).state.read(cx);
474 assert!(state.is_open());
475 assert!(state.trigger_focus_handle().is_focused(window));
476 #[cfg(feature = "test-support")]
477 {
478 let id = view.read(cx).state.entity_id();
479 let trigger =
480 crate::test_support::find(window, &[], &("collapsible-trigger", id).into())
481 .unwrap();
482 assert_eq!(trigger.expanded(), Some(true));
483 let region =
484 crate::test_support::find(window, &[], &("collapsible-content", id).into())
485 .unwrap();
486 assert_eq!(region.role(), Some(Role::Region));
487 assert_eq!(region.label(), Some("Options"));
488 }
489 });
490 cx.simulate_keystrokes("tab");
491 draw(cx);
492 cx.update(|window, cx| assert!(view.read(cx).input.focus_handle(cx).is_focused(window)));
493 cx.simulate_keystrokes("tab");
494 draw(cx);
495 cx.update(|window, cx| {
496 assert!(view.read(cx).after.is_focused(window));
497 let state = view.read(cx).state.clone();
498 state.update(cx, |state, cx| {
499 state.set_open(false, window, cx);
500 state.set_open(false, window, cx);
501 });
502 assert!(view.read(cx).after.is_focused(window));
503 });
504 draw(cx);
505 assert!(cx.debug_bounds("content").is_none());
506 assert_eq!(cx.debug_bounds("after").unwrap().origin.y, collapsed_after);
507 cx.simulate_keystrokes("shift-tab");
508 draw(cx);
509 cx.update(|window, cx| {
510 assert!(
511 view.read(cx)
512 .state
513 .read(cx)
514 .trigger_focus_handle()
515 .is_focused(window)
516 );
517 });
518 assert_eq!(*changes.borrow(), [true, false]);
519 }
520
521 #[gpui::test]
522 fn imperative_visibility_retains_content_and_restores_only_a_live_trigger(
523 cx: &mut TestAppContext,
524 ) {
525 let (cx, view, changes) = harness(cx, true);
526 cx.simulate_keystrokes("tab tab");
527 draw(cx);
528 cx.simulate_input("retained");
529 cx.simulate_keystrokes("home");
530 draw(cx);
531 cx.update(|window, cx| {
532 let input = &view.read(cx).input;
533 assert!(input.focus_handle(cx).is_focused(window));
534 assert_eq!(input.read(cx).selected_range(), 0..0);
535 });
536 cx.simulate_keystrokes("end");
537 draw(cx);
538 cx.update(|window, cx| {
539 assert_eq!(view.read(cx).input.read(cx).selected_range(), 8..8);
540 let state = view.read(cx).state.clone();
541 state.update(cx, |state, cx| {
542 state.set_open(false, window, cx);
543 assert!(state.trigger_focus_handle().is_focused(window));
544 state.set_disabled(true, window, cx);
545 });
546 });
547 draw(cx);
548 press(cx, "space");
549 cx.update(|window, cx| {
550 let state = view.read(cx).state.read(cx);
551 assert!(!state.is_open());
552 assert!(state.is_disabled());
553 assert!(state.trigger_focus_handle().is_focused(window));
554 #[cfg(feature = "test-support")]
555 {
556 let trigger = crate::test_support::find(
557 window,
558 &[],
559 &("collapsible-trigger", view.read(cx).state.entity_id()).into(),
560 )
561 .unwrap();
562 assert_eq!(trigger.disabled(), Some(true));
563 }
564 });
565 cx.simulate_keystrokes("tab");
566 draw(cx);
567 cx.update(|window, cx| assert!(view.read(cx).after.is_focused(window)));
568 cx.simulate_keystrokes("shift-tab");
569 draw(cx);
570 cx.update(|window, cx| {
571 assert!(view.read(cx).before.is_focused(window));
572 let state = view.read(cx).state.clone();
573 state.update(cx, |state, cx| {
574 state.set_open(true, window, cx);
575 state.toggle(window, cx);
576 });
577 assert!(state.read(cx).is_open());
578 assert!(view.read(cx).before.is_focused(window));
579 assert_eq!(view.read(cx).input.read(cx).value(), "retained");
580 });
581 draw(cx);
582 assert!(cx.debug_bounds("content").is_some());
583 cx.simulate_keystrokes("tab");
584 draw(cx);
585 cx.update(|window, cx| {
586 assert!(view.read(cx).input.focus_handle(cx).is_focused(window));
587 let state = view.read(cx).state.clone();
588 state.update(cx, |state, cx| state.set_open(false, window, cx));
589 assert!(state.read(cx).root_focus.is_focused(window));
590 });
591 draw(cx);
592 assert!(cx.debug_bounds("content").is_none());
593 cx.simulate_keystrokes("tab");
594 draw(cx);
595 cx.update(|window, cx| {
596 assert!(view.read(cx).after.is_focused(window));
597 let state = view.read(cx).state.clone();
598 state.update(cx, |state, cx| {
599 state.set_disabled(false, window, cx);
600 state.set_open(true, window, cx);
601 });
602 });
603 draw(cx);
604 cx.update(|window, cx| {
605 view.read(cx).input.focus_handle(cx).focus(window, cx);
606 });
607 draw(cx);
608 view.update(cx, |view, cx| {
609 view.show_host = false;
610 cx.notify();
611 });
612 draw(cx);
613 cx.update(|window, cx| {
614 let state = view.read(cx).state.clone();
615 state.update(cx, |state, cx| state.set_open(false, window, cx));
616 assert!(!state.read(cx).trigger_focus_handle().is_focused(window));
617 });
618 assert_eq!(*changes.borrow(), [false, true, false, true, false]);
619 }
620}