1use gpui::{
2 AnyElement, App, Axis, Div, ElementId, FocusHandle, InteractiveElement, Interactivity,
3 IntoElement, KeyDownEvent, ParentElement, RenderOnce, Role, SharedString, Stateful,
4 StatefulInteractiveElement, StyleRefinement, Styled, Window, accesskit, div,
5 prelude::FluentBuilder as _,
6};
7use smallvec::SmallVec;
8
9use crate::{LayoutDirection, StyledExt as _, TestSupportExt as _};
10
11#[derive(IntoElement)]
42pub struct Toolbar {
43 id: ElementId,
44 base: crate::ObservedElement<Stateful<Div>>,
45 style: StyleRefinement,
46 disabled: bool,
47 axis: Axis,
48 children: SmallVec<[AnyElement; 4]>,
49}
50
51impl Toolbar {
52 pub fn new(id: impl Into<ElementId>) -> Self {
53 let id = id.into();
54 Self {
55 base: div().id(id.clone()).test_support(),
56 style: StyleRefinement::default(),
57 disabled: false,
58 axis: Axis::Horizontal,
59 children: SmallVec::new(),
60 id,
61 }
62 }
63
64 pub fn disabled(mut self, disabled: bool) -> Self {
67 self.disabled = disabled;
68 self
69 }
70
71 pub fn axis(mut self, axis: Axis) -> Self {
74 self.axis = axis;
75 self
76 }
77}
78
79fn step_focus(window: &mut Window, cx: &mut App, forward: bool) {
80 if forward {
81 window.focus_next(cx);
82 } else {
83 window.focus_prev(cx);
84 }
85}
86
87fn move_focus(container: &FocusHandle, forward: bool, window: &mut Window, cx: &mut App) {
98 let Some(start) = window.focused(cx) else {
99 return;
100 };
101
102 let mut visited = vec![start.clone()];
103 loop {
104 step_focus(window, cx, forward);
105 let Some(focused) = window.focused(cx) else {
106 break;
107 };
108 if visited.contains(&focused) {
109 break;
110 }
111 if container.contains_focused(window, cx) {
112 return;
113 }
114 visited.push(focused);
115 }
116 window.focus(&start, cx);
117}
118
119fn handle_key_down(
120 disabled: bool,
121 axis: Axis,
122 container: &FocusHandle,
123 event: &KeyDownEvent,
124 window: &mut Window,
125 cx: &mut App,
126) {
127 if disabled {
128 return;
129 }
130
131 let forward = match (axis, event.keystroke.key.as_str()) {
132 (Axis::Horizontal, "left") => Some(LayoutDirection::global(cx).is_rtl()),
134 (Axis::Horizontal, "right") => Some(!LayoutDirection::global(cx).is_rtl()),
135 (Axis::Vertical, "up") => Some(false),
136 (Axis::Vertical, "down") => Some(true),
137 _ => None,
138 };
139
140 if let Some(forward) = forward {
141 move_focus(container, forward, window, cx);
142 cx.stop_propagation();
143 }
144}
145
146impl Styled for Toolbar {
147 fn style(&mut self) -> &mut StyleRefinement {
148 &mut self.style
149 }
150}
151
152impl ParentElement for Toolbar {
153 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
154 self.children.extend(elements);
155 }
156}
157
158impl InteractiveElement for Toolbar {
159 fn interactivity(&mut self) -> &mut Interactivity {
160 self.base.interactivity()
161 }
162}
163
164impl StatefulInteractiveElement for Toolbar {}
165
166impl RenderOnce for Toolbar {
167 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
168 let Self {
169 base,
170 style,
171 disabled,
172 axis,
173 children,
174 ..
175 } = self;
176
177 let focus_handle = window
181 .use_keyed_state(self.id, cx, |_, cx| cx.focus_handle().tab_stop(false))
182 .read(cx)
183 .clone();
184 let key_handler = {
185 let focus_handle = focus_handle.clone();
186 move |event: &KeyDownEvent, window: &mut Window, cx: &mut App| {
187 handle_key_down(disabled, axis, &focus_handle, event, window, cx);
188 }
189 };
190
191 base.track_focus(&focus_handle)
192 .role(Role::Toolbar)
193 .aria_orientation(match axis {
194 Axis::Horizontal => accesskit::Orientation::Horizontal,
195 Axis::Vertical => accesskit::Orientation::Vertical,
196 })
197 .on_key_down(key_handler)
198 .on_any_mouse_down(|_, window, _| window.prevent_default())
203 .children(children)
204 .refine_style(&style)
205 }
206}
207
208#[derive(IntoElement)]
223pub struct ToolbarGroup {
224 base: Stateful<Div>,
225 style: StyleRefinement,
226 label: Option<SharedString>,
227 children: SmallVec<[AnyElement; 4]>,
228}
229
230impl ToolbarGroup {
231 pub fn new(id: impl Into<ElementId>) -> Self {
232 Self {
233 base: div().id(id.into()),
234 style: StyleRefinement::default(),
235 label: None,
236 children: SmallVec::new(),
237 }
238 }
239
240 pub fn label(mut self, label: impl Into<SharedString>) -> Self {
242 self.label = Some(label.into());
243 self
244 }
245}
246
247impl Styled for ToolbarGroup {
248 fn style(&mut self) -> &mut StyleRefinement {
249 &mut self.style
250 }
251}
252
253impl ParentElement for ToolbarGroup {
254 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
255 self.children.extend(elements);
256 }
257}
258
259impl InteractiveElement for ToolbarGroup {
260 fn interactivity(&mut self) -> &mut Interactivity {
261 self.base.interactivity()
262 }
263}
264
265impl StatefulInteractiveElement for ToolbarGroup {}
266
267impl RenderOnce for ToolbarGroup {
268 fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
269 self.base
274 .flex()
275 .items_center()
276 .role(Role::Group)
277 .when_some(self.label, |this, label| this.aria_label(label))
278 .children(self.children)
279 .refine_style(&self.style)
280 }
281}
282
283#[cfg(test)]
284mod tests {
285 use super::*;
286
287 #[test]
288 fn test_toolbar_builder() {
289 let toolbar = Toolbar::new("toolbar").disabled(true).child(div());
290
291 assert!(toolbar.disabled);
292 assert_eq!(toolbar.children.len(), 1);
293 }
294
295 #[test]
296 fn test_toolbar_defaults() {
297 let toolbar = Toolbar::new("toolbar");
298
299 assert!(!toolbar.disabled);
300 assert_eq!(toolbar.axis, Axis::Horizontal);
301 assert!(toolbar.children.is_empty());
302 assert_eq!(
303 Toolbar::new("toolbar").axis(Axis::Vertical).axis,
304 Axis::Vertical
305 );
306 }
307
308 #[test]
309 fn test_toolbar_group_builder() {
310 let group = ToolbarGroup::new("history-group")
311 .label("History")
312 .child(div())
313 .child(div());
314
315 assert_eq!(group.label.as_deref(), Some("History"));
316 assert_eq!(group.children.len(), 2);
317 }
318
319 #[cfg(test)]
320 mod behavior {
321 use super::*;
322 use gpui::{
323 Context, Element as _, FocusHandle, Modifiers, Render, TestAppContext,
324 VisualTestContext, canvas, point, px,
325 };
326 use std::sync::{Arc, Mutex};
327
328 struct NavHarness {
329 items: [FocusHandle; 3],
330 }
331
332 impl Render for NavHarness {
333 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
334 let [first, second, third] = &self.items;
335 Toolbar::new("nav-toolbar")
336 .child(div().id("first").size(px(20.)).track_focus(first))
337 .child(div().id("second").size(px(20.)).track_focus(second))
338 .child(div().id("third").size(px(20.)).track_focus(third))
339 }
340 }
341
342 fn harness(cx: &mut TestAppContext) -> ([FocusHandle; 3], &mut VisualTestContext) {
343 let (state, cx) = cx.add_window_view(move |window, cx| {
344 let items = [
345 cx.focus_handle().tab_stop(true),
346 cx.focus_handle().tab_stop(true),
347 cx.focus_handle().tab_stop(true),
348 ];
349 items[0].focus(window, cx);
350 NavHarness { items }
351 });
352 let items = state.read_with(cx, |harness, _| harness.items.clone());
353 cx.update(|window, cx| {
354 window.draw(cx).clear(cx);
355 });
356 (items, cx)
357 }
358
359 fn assert_focused(cx: &mut VisualTestContext, expected: &FocusHandle, label: &str) {
360 cx.update(|window, _| {
361 assert!(
362 expected.is_focused(window),
363 "expected {label} to be focused"
364 );
365 });
366 }
367
368 #[gpui::test]
369 fn arrow_keys_rove_focus_across_items(cx: &mut gpui::TestAppContext) {
370 let ([first, second, third], cx) = harness(cx);
371
372 cx.simulate_keystrokes("right");
373 assert_focused(cx, &second, "second");
374 cx.simulate_keystrokes("right");
375 assert_focused(cx, &third, "third");
376
377 cx.simulate_keystrokes("right");
379 assert_focused(cx, &first, "first (wrapped)");
380
381 cx.simulate_keystrokes("left");
382 assert_focused(cx, &third, "third (wrapped back)");
383 }
384
385 #[gpui::test]
386 fn arrow_keys_follow_global_rtl_direction(cx: &mut gpui::TestAppContext) {
387 let ([first, second, third], cx) = harness(cx);
388 cx.update(|_, cx| crate::LayoutDirection::Rtl.set_global(cx));
389
390 cx.simulate_keystrokes("left");
392 assert_focused(cx, &second, "second");
393 cx.simulate_keystrokes("left");
394 assert_focused(cx, &third, "third");
395 cx.simulate_keystrokes("right");
396 assert_focused(cx, &second, "second (back)");
397 cx.simulate_keystrokes("right");
398 cx.simulate_keystrokes("right");
399 assert_focused(cx, &third, "third (wrapped back)");
400 let _ = first;
401 }
402
403 #[gpui::test]
404 fn a_vertical_toolbar_roves_with_up_and_down(cx: &mut TestAppContext) {
405 struct Vertical([FocusHandle; 3]);
406
407 impl Render for Vertical {
408 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
409 let [first, second, third] = &self.0;
410 Toolbar::new("vertical-toolbar")
411 .axis(Axis::Vertical)
412 .child(div().id("first").size(px(20.)).track_focus(first))
413 .child(div().id("second").size(px(20.)).track_focus(second))
414 .child(div().id("third").size(px(20.)).track_focus(third))
415 }
416 }
417
418 let (state, cx) = cx.add_window_view(|window, cx| {
419 let items = [(); 3].map(|_| cx.focus_handle().tab_stop(true));
420 items[0].focus(window, cx);
421 Vertical(items)
422 });
423 let [first, second, third] = state.read_with(cx, |harness, _| harness.0.clone());
424 cx.update(|window, cx| window.draw(cx).clear(cx));
425
426 cx.simulate_keystrokes("right");
427 assert_focused(cx, &first, "first (Right is not a vertical key)");
428 cx.simulate_keystrokes("down");
429 assert_focused(cx, &second, "second");
430 cx.simulate_keystrokes("down down");
431 assert_focused(cx, &first, "first (wrapped)");
432 cx.simulate_keystrokes("up");
433 assert_focused(cx, &third, "third (wrapped back)");
434 }
435
436 #[gpui::test]
437 fn arrow_keys_wrap_inside_the_toolbar_among_many_page_stops(cx: &mut TestAppContext) {
438 const STOPS: usize = 120;
440
441 struct BusyPage {
442 before: Vec<FocusHandle>,
443 items: [FocusHandle; 3],
444 after: Vec<FocusHandle>,
445 }
446
447 impl Render for BusyPage {
448 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
449 let [first, second, third] = &self.items;
450 div()
451 .flex()
452 .flex_col()
453 .children(self.before.iter().enumerate().map(|(at, handle)| {
454 div().id(("before", at)).size(px(1.)).track_focus(handle)
455 }))
456 .child(
457 Toolbar::new("busy-toolbar")
458 .child(div().id("first").size(px(20.)).track_focus(first))
459 .child(div().id("second").size(px(20.)).track_focus(second))
460 .child(div().id("third").size(px(20.)).track_focus(third)),
461 )
462 .children(self.after.iter().enumerate().map(|(at, handle)| {
463 div().id(("after", at)).size(px(1.)).track_focus(handle)
464 }))
465 }
466 }
467
468 let (state, cx) = cx.add_window_view(|window, cx| {
469 let stop = |cx: &mut Context<BusyPage>| cx.focus_handle().tab_stop(true);
470 let page = BusyPage {
471 before: (0..STOPS).map(|_| stop(cx)).collect(),
472 items: [stop(cx), stop(cx), stop(cx)],
473 after: (0..STOPS).map(|_| stop(cx)).collect(),
474 };
475 page.items[0].focus(window, cx);
476 page
477 });
478 let [first, second, third] = state.read_with(cx, |page, _| page.items.clone());
479 cx.update(|window, cx| {
480 window.draw(cx).clear(cx);
481 });
482
483 cx.simulate_keystrokes("left");
484 assert_focused(cx, &third, "third (Left from the first)");
485 cx.simulate_keystrokes("right");
486 assert_focused(cx, &first, "first (Right from the last)");
487 cx.simulate_keystrokes("right");
488 assert_focused(cx, &second, "second (one step right)");
489 cx.simulate_keystrokes("left");
490 assert_focused(cx, &first, "first (one step left)");
491 }
492
493 #[gpui::test]
494 fn arrow_keys_wrap_across_more_than_a_hundred_items(cx: &mut TestAppContext) {
495 const ITEMS: usize = 120;
496
497 struct LargeToolbar {
498 outside: FocusHandle,
499 items: Vec<FocusHandle>,
500 }
501
502 impl Render for LargeToolbar {
503 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
504 div()
505 .child(div().id("outside").size(px(1.)).track_focus(&self.outside))
506 .child(Toolbar::new("large-toolbar").children(
507 self.items.iter().enumerate().map(|(at, handle)| {
508 div().id(("item", at)).size(px(1.)).track_focus(handle)
509 }),
510 ))
511 }
512 }
513
514 let (state, cx) = cx.add_window_view(|window, cx| {
515 let page = LargeToolbar {
516 outside: cx.focus_handle().tab_stop(true),
517 items: (0..ITEMS)
518 .map(|_| cx.focus_handle().tab_stop(true))
519 .collect(),
520 };
521 page.items[0].focus(window, cx);
522 page
523 });
524 let items = state.read_with(cx, |page, _| page.items.clone());
525 cx.update(|window, cx| {
526 window.draw(cx).clear(cx);
527 });
528
529 cx.simulate_keystrokes("left");
530 assert_focused(cx, &items[ITEMS - 1], "the last item (Left from the first)");
531 cx.simulate_keystrokes("right");
532 assert_focused(cx, &items[0], "the first item (Right from the last)");
533 }
534
535 #[gpui::test]
536 fn arrow_keys_pass_over_stops_ordered_between_the_items(cx: &mut TestAppContext) {
537 struct InterleavedPage {
538 items: [FocusHandle; 3],
539 outside: [FocusHandle; 2],
540 }
541
542 impl Render for InterleavedPage {
543 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
544 let [first, second, third] = &self.items;
545 let [before, after] = &self.outside;
546 div()
547 .child(
548 Toolbar::new("interleaved-toolbar")
549 .child(div().id("first").size(px(20.)).track_focus(first))
550 .child(div().id("second").size(px(20.)).track_focus(second))
551 .child(div().id("third").size(px(20.)).track_focus(third)),
552 )
553 .child(div().id("before").size(px(20.)).track_focus(before))
554 .child(div().id("after").size(px(20.)).track_focus(after))
555 }
556 }
557
558 let (state, cx) = cx.add_window_view(|window, cx| {
561 let stop = |index, cx: &mut Context<InterleavedPage>| {
562 cx.focus_handle().tab_stop(true).tab_index(index)
563 };
564 let page = InterleavedPage {
565 items: [stop(1, cx), stop(3, cx), stop(5, cx)],
566 outside: [stop(2, cx), stop(4, cx)],
567 };
568 page.items[0].focus(window, cx);
569 page
570 });
571 let [first, second, third] = state.read_with(cx, |page, _| page.items.clone());
572 cx.update(|window, cx| {
573 window.draw(cx).clear(cx);
574 });
575
576 cx.simulate_keystrokes("right");
577 assert_focused(cx, &second, "second (Right from the first)");
578 cx.simulate_keystrokes("right");
579 assert_focused(cx, &third, "third (Right from the second)");
580 cx.simulate_keystrokes("right");
581 assert_focused(cx, &first, "first (Right from the last)");
582 cx.simulate_keystrokes("left");
583 assert_focused(cx, &third, "third (Left from the first)");
584 }
585
586 #[gpui::test]
587 fn arrow_keys_keep_focus_when_no_other_item_is_a_tab_stop(cx: &mut TestAppContext) {
588 struct Unreachable {
589 item: FocusHandle,
590 outside: [FocusHandle; 2],
591 }
592
593 impl Render for Unreachable {
594 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
595 let [before, after] = &self.outside;
596 div()
597 .child(div().id("before").size(px(20.)).track_focus(before))
598 .child(
599 Toolbar::new("unreachable-toolbar")
600 .child(div().id("item").size(px(20.)).track_focus(&self.item)),
601 )
602 .child(div().id("after").size(px(20.)).track_focus(after))
603 }
604 }
605
606 let (state, cx) = cx.add_window_view(|window, cx| {
609 let page = Unreachable {
610 item: cx.focus_handle(),
611 outside: [
612 cx.focus_handle().tab_stop(true),
613 cx.focus_handle().tab_stop(true),
614 ],
615 };
616 page.item.focus(window, cx);
617 page
618 });
619 let item = state.read_with(cx, |page, _| page.item.clone());
620 cx.update(|window, cx| {
621 window.draw(cx).clear(cx);
622 });
623
624 cx.simulate_keystrokes("right left");
625 assert_focused(cx, &item, "the item (no other stop in the toolbar)");
626 }
627
628 #[gpui::test]
629 fn toolbar_with_a_single_item_keeps_focus_on_it(cx: &mut gpui::TestAppContext) {
630 struct SingleHarness {
631 item: FocusHandle,
632 }
633
634 impl Render for SingleHarness {
635 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
636 let item = &self.item;
637 Toolbar::new("single-toolbar")
638 .child(div().id("only").size(px(20.)).track_focus(item))
639 }
640 }
641
642 let (state, cx) = cx.add_window_view(|window, cx| {
643 let item = cx.focus_handle().tab_stop(true);
644 item.focus(window, cx);
645 SingleHarness { item }
646 });
647 let item = state.read_with(cx, |harness, _| harness.item.clone());
648 cx.update(|window, cx| {
649 window.draw(cx).clear(cx);
650 });
651
652 cx.simulate_keystrokes("right left right");
653 assert_focused(cx, &item, "the only item");
654 }
655
656 #[gpui::test]
657 fn snapshot_reports_the_toolbar_role_label_and_focus(cx: &mut gpui::TestAppContext) {
658 struct Labelled(FocusHandle);
659
660 impl Render for Labelled {
661 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
662 Toolbar::new("formatting")
663 .aria_label("Formatting")
664 .child(div().id("bold").size(px(20.)).track_focus(&self.0))
665 }
666 }
667
668 let (_, cx) = cx.add_window_view(|window, cx| {
669 let item = cx.focus_handle().tab_stop(true);
670 item.focus(window, cx);
671 Labelled(item)
672 });
673 cx.update(|window, cx| {
674 window.draw(cx).clear(cx);
675 let snapshot = crate::test_support::find(window, &[], &"formatting".into())
676 .expect("the toolbar is observed");
677 assert_eq!(snapshot.role(), Some(Role::Toolbar));
678 assert_eq!(snapshot.label(), Some("Formatting"));
679 assert_eq!(snapshot.focused(), Some(true));
682 });
683 }
684
685 #[gpui::test]
686 fn group_exposes_group_role_and_accessible_name(cx: &mut gpui::TestAppContext) {
687 type Captured = Arc<Mutex<Option<accesskit::Node>>>;
688
689 struct Probe(Captured);
690
691 impl Render for Probe {
692 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
693 let captured = self.0.clone();
694 canvas(
695 move |_, window, cx| {
696 let mut node = accesskit::Node::new(Role::Group);
697 ToolbarGroup::new("history")
698 .label("History")
699 .child(div().size(px(20.)))
700 .render(window, cx)
701 .into_element()
702 .write_a11y_info(&mut node);
703 *captured.lock().unwrap() = Some(node);
704 },
705 |_, _, _, _| {},
706 )
707 }
708 }
709
710 let captured: Captured = Arc::new(Mutex::new(None));
711 let result = captured.clone();
712 let (_, cx) = cx.add_window_view(move |_, _| Probe(captured));
713 cx.update(|window, cx| window.draw(cx).clear(cx));
714 let node = result.lock().unwrap().take().unwrap();
715
716 assert_eq!(node.role(), Role::Group);
717 assert_eq!(node.label(), Some("History"));
718 }
719
720 #[gpui::test]
721 fn disabled_toolbar_ignores_arrow_keys(cx: &mut gpui::TestAppContext) {
722 struct DisabledHarness {
723 items: [FocusHandle; 2],
724 }
725
726 impl Render for DisabledHarness {
727 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
728 let [first, second] = &self.items;
729 Toolbar::new("disabled-toolbar")
730 .disabled(true)
731 .child(div().id("first").size(px(20.)).track_focus(first))
732 .child(div().id("second").size(px(20.)).track_focus(second))
733 }
734 }
735
736 let (state, cx) = cx.add_window_view(|window, cx| {
737 let items = [
738 cx.focus_handle().tab_stop(true),
739 cx.focus_handle().tab_stop(true),
740 ];
741 items[0].focus(window, cx);
742 DisabledHarness { items }
743 });
744 let items = state.read_with(cx, |harness, _| harness.items.clone());
745 cx.update(|window, cx| {
746 window.draw(cx).clear(cx);
747 });
748
749 cx.simulate_keystrokes("right");
750 assert_focused(cx, &items[0], "first (disabled toolbar)");
751 }
752
753 #[gpui::test]
754 fn clicking_blank_toolbar_space_keeps_focus_outside(cx: &mut gpui::TestAppContext) {
755 struct ClickHarness {
756 outside: FocusHandle,
757 item: FocusHandle,
758 }
759
760 impl Render for ClickHarness {
761 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
762 div()
763 .child(div().id("outside").size(px(20.)).track_focus(&self.outside))
764 .child(
765 Toolbar::new("click-toolbar")
766 .flex()
767 .w(px(100.))
768 .h(px(20.))
769 .child(div().id("item").size(px(20.)).track_focus(&self.item)),
770 )
771 }
772 }
773
774 let (state, cx) = cx.add_window_view(|window, cx| {
775 let outside = cx.focus_handle().tab_stop(true);
776 outside.focus(window, cx);
777 ClickHarness {
778 outside,
779 item: cx.focus_handle().tab_stop(true),
780 }
781 });
782 let (outside, item) = state.read_with(cx, |harness, _| {
783 (harness.outside.clone(), harness.item.clone())
784 });
785 cx.update(|window, cx| {
786 window.draw(cx).clear(cx);
787 });
788
789 cx.simulate_click(point(px(80.), px(30.)), Modifiers::default());
791 assert_focused(cx, &outside, "outside (blank toolbar click)");
792
793 cx.simulate_click(point(px(10.), px(30.)), Modifiers::default());
795 assert_focused(cx, &item, "item (clicked)");
796 }
797 }
798}