1use std::{cell::RefCell, rc::Rc};
2
3use gpui::{
4 Anchor, AnyElement, App, Background, Bounds, ClickEvent, Edges, ElementId, Entity, EntityId,
5 InteractiveElement, IntoElement, ParentElement, Pixels, RenderOnce, ScrollHandle, SharedString,
6 StatefulInteractiveElement as _, StyleRefinement, Styled, Window, div, point,
7 prelude::FluentBuilder as _, px,
8};
9use gpui_base::{LayoutDirection, LogicalStyledExt as _, spring};
10use rust_i18n::t;
11use smallvec::SmallVec;
12
13use super::{
14 Tab, TabVariant,
15 tab::{FOLDER_TAB_GAP, FolderTabMetrics},
16};
17use crate::button::{Button, ButtonVariants as _};
18use crate::menu::{DropdownMenu as _, PopupMenuItem};
19use crate::scroll::ScrollableMask;
20use crate::{
21 ActiveTheme, ElementExt, Icon, InteractiveElementExt as _, Selectable, Sizable, Size,
22 StyledExt, h_flex, styled::raised_shadow,
23};
24
25struct TabIndicatorBounds {
26 container: Bounds<Pixels>,
27 tabs: Vec<Bounds<Pixels>>,
28 placed: (Pixels, Pixels),
31}
32
33impl TabIndicatorBounds {
34 fn new(num_tabs: usize) -> Self {
35 Self {
36 container: Bounds::default(),
37 tabs: vec![Bounds::default(); num_tabs],
38 placed: (px(0.), px(0.)),
39 }
40 }
41
42 fn resize(&mut self, num_tabs: usize) {
43 self.tabs.resize(num_tabs, Bounds::default());
44 }
45}
46
47#[derive(IntoElement)]
49pub struct TabBar {
50 id: ElementId,
51 base: gpui_base::Tabs,
52 style: StyleRefinement,
53 scroll_handle: Option<ScrollHandle>,
54 prefix: Option<AnyElement>,
55 suffix: Option<AnyElement>,
56 children: SmallVec<[Tab; 2]>,
57 last_empty_space: AnyElement,
58 selected_index: Option<usize>,
59 variant: TabVariant,
60 size: Size,
61 menu: bool,
62 max_width: Option<Pixels>,
63 on_click: Option<Rc<dyn Fn(&usize, &mut Window, &mut App) + 'static>>,
64}
65
66impl TabBar {
67 pub fn new(id: impl Into<ElementId>) -> Self {
69 let id = id.into();
70 Self {
71 id: id.clone(),
72 base: gpui_base::Tabs::new(id).px(px(-1.)),
73 style: StyleRefinement::default(),
74 children: SmallVec::new(),
75 scroll_handle: None,
76 prefix: None,
77 suffix: None,
78 variant: TabVariant::default(),
79 size: Size::default(),
80 last_empty_space: div().w_3().into_any_element(),
81 selected_index: None,
82 on_click: None,
83 menu: false,
84 max_width: None,
85 }
86 }
87
88 pub fn with_variant(mut self, variant: TabVariant) -> Self {
90 self.variant = variant;
91 self
92 }
93
94 pub fn pill(mut self) -> Self {
96 self.variant = TabVariant::Pill;
97 self
98 }
99
100 pub fn outline(mut self) -> Self {
102 self.variant = TabVariant::Outline;
103 self
104 }
105
106 pub fn segmented(mut self) -> Self {
108 self.variant = TabVariant::Segmented;
109 self
110 }
111
112 pub fn underline(mut self) -> Self {
114 self.variant = TabVariant::Underline;
115 self
116 }
117
118 pub fn folder(mut self) -> Self {
120 self.variant = TabVariant::Folder;
121 self
122 }
123
124 pub fn menu(mut self, menu: bool) -> Self {
126 self.menu = menu;
127 self
128 }
129
130 pub fn max_width(mut self, width: impl Into<Pixels>) -> Self {
134 self.max_width = Some(width.into());
135 self
136 }
137
138 pub fn track_scroll(mut self, scroll_handle: &ScrollHandle) -> Self {
144 self.scroll_handle = Some(scroll_handle.clone());
145 self
146 }
147
148 pub fn prefix(mut self, prefix: impl IntoElement) -> Self {
150 self.prefix = Some(prefix.into_any_element());
151 self
152 }
153
154 pub fn suffix(mut self, suffix: impl IntoElement) -> Self {
156 self.suffix = Some(suffix.into_any_element());
157 self
158 }
159
160 pub fn children(mut self, children: impl IntoIterator<Item = impl Into<Tab>>) -> Self {
162 self.children.extend(children.into_iter().map(Into::into));
163 self
164 }
165
166 pub fn child(mut self, child: impl Into<Tab>) -> Self {
168 self.children.push(child.into());
169 self
170 }
171
172 pub fn selected_index(mut self, index: usize) -> Self {
174 self.selected_index = Some(index);
175 self
176 }
177
178 pub fn last_empty_space(mut self, last_empty_space: impl IntoElement) -> Self {
180 self.last_empty_space = last_empty_space.into_any_element();
181 self
182 }
183
184 pub fn on_click<F>(mut self, on_click: F) -> Self
188 where
189 F: Fn(&usize, &mut Window, &mut App) + 'static,
190 {
191 self.on_click = Some(Rc::new(on_click));
192 self
193 }
194
195 fn render_indicator(
202 &self,
203 bounds_rc: &Option<Rc<RefCell<TabIndicatorBounds>>>,
204 window: &mut Window,
205 cx: &mut App,
206 ) -> Option<(AnyElement, u64)> {
207 let has_indicator = matches!(
208 self.variant,
209 TabVariant::Segmented | TabVariant::Pill | TabVariant::Underline
210 );
211 let num_tabs = self.children.len();
212 let selected_ix = self.selected_index.unwrap_or(usize::MAX);
213
214 if !(has_indicator && num_tabs > 0 && selected_ix < num_tabs) {
215 return None;
216 }
217
218 let prev_key = format!("{}-tab-prev", self.id);
219 let anim_key = format!("{}-tab-anim", self.id);
220 let init_key = format!("{}-tab-init", self.id);
221
222 let prev_selected = window.use_keyed_state(prev_key, cx, |_, _| selected_ix);
223 let anim_params = window.use_keyed_state(anim_key, cx, |_, _| (px(0.), px(0.), 0u64));
225 let initialized = window.use_keyed_state(init_key, cx, |_, _| false);
226
227 if !*initialized.read(cx) {
229 initialized.update(cx, |v, _| *v = true);
230 }
231
232 self.update_anim_params(selected_ix, bounds_rc, &prev_selected, &anim_params, cx);
233
234 let (to_left, to_width, epoch) = *anim_params.read(cx);
235 if let Some(rc) = bounds_rc {
236 rc.borrow_mut().placed = (to_left, to_width);
237 }
238 if to_width <= px(0.) {
239 return None;
240 }
241
242 let indicator_key = format!("{}-tab-indicator", self.id);
246 let left = spring(
247 (indicator_key.clone(), "left"),
248 to_left,
249 cx.theme().motion_tokens().spring_move,
250 window,
251 cx,
252 );
253 let width = spring(
254 (indicator_key, "width"),
255 to_width,
256 cx.theme().motion_tokens().spring_move,
257 window,
258 cx,
259 );
260
261 let variant = self.variant;
262 let size = self.size;
263 let inner_height = variant.inner_height(size);
264 let inner_radius = variant.inner_radius(size, cx);
265
266 let indicator = div()
267 .absolute()
268 .top_0()
269 .bottom_0()
270 .left(left)
271 .w(width)
272 .map(|el| match variant {
273 TabVariant::Segmented => el.flex().items_center().child(
274 div()
275 .w_full()
276 .h(inner_height)
277 .bg(cx.theme().tokens.background)
278 .rounded(inner_radius)
279 .shadow(raised_shadow()),
280 ),
281 TabVariant::Pill => el.flex().items_center().child(
282 div()
283 .size_full()
284 .bg(cx.theme().tokens.primary)
285 .rounded(cx.theme().radius_full()),
286 ),
287 TabVariant::Underline => el.child(
288 div()
289 .absolute()
290 .left_0()
291 .right_0()
292 .bottom_0()
293 .h(px(2.))
294 .bg(cx.theme().tokens.primary),
295 ),
296 _ => el,
297 });
298
299 Some((indicator.into_any_element(), epoch))
300 }
301
302 fn update_anim_params(
304 &self,
305 selected_ix: usize,
306 bounds_rc: &Option<Rc<RefCell<TabIndicatorBounds>>>,
307 prev_selected: &gpui::Entity<usize>,
308 anim_params: &gpui::Entity<(Pixels, Pixels, u64)>,
309 cx: &mut App,
310 ) {
311 let rc = match bounds_rc {
312 Some(rc) => rc,
313 None => return,
314 };
315
316 let prev_ix = *prev_selected.read(cx);
317 let bounds = rc.borrow();
318 let container = bounds.container;
319
320 if container.size.width == px(0.) {
321 if prev_ix != selected_ix {
322 prev_selected.update(cx, |v, _| *v = selected_ix);
323 }
324 return;
325 }
326
327 let first_tab_origin = bounds
330 .tabs
331 .first()
332 .map(|tab| tab.origin.x)
333 .unwrap_or(container.origin.x);
334
335 if prev_ix != selected_ix {
336 if let Some(to_b) = bounds.tabs.get(selected_ix) {
337 let left = to_b.origin.x - first_tab_origin;
338 let width = to_b.size.width;
339 let epoch = anim_params.read(cx).2;
342 let epoch = match bounds.tabs.get(prev_ix) {
343 Some(_) => epoch + 1,
344 None => epoch,
345 };
346 anim_params.update(cx, |v, _| *v = (left, width, epoch));
347 }
348 drop(bounds);
349 prev_selected.update(cx, |v, _| *v = selected_ix);
350 return;
351 }
352
353 if let Some(to_b) = bounds.tabs.get(selected_ix) {
354 let left = to_b.origin.x - first_tab_origin;
355 let width = to_b.size.width;
356 let (to_left, to_width, epoch) = *anim_params.read(cx);
357
358 if left != to_left || width != to_width {
359 anim_params.update(cx, |v, _| *v = (left, width, epoch));
360 }
361 }
362 }
363}
364
365impl Styled for TabBar {
366 fn style(&mut self) -> &mut StyleRefinement {
367 &mut self.style
368 }
369}
370
371impl Sizable for TabBar {
372 fn with_size(mut self, size: impl Into<Size>) -> Self {
373 self.size = size.into();
374 self
375 }
376}
377
378impl RenderOnce for TabBar {
379 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
380 let default_gap = match self.size {
381 Size::Small | Size::XSmall => px(8.),
382 Size::Large => px(16.),
383 _ => px(12.),
384 };
385 let (bg, paddings, gap): (Background, _, _) = match self.variant {
386 TabVariant::Tab => {
387 let padding = Edges::all(px(0.));
388 (cx.theme().tokens.tab_bar.into(), padding, px(0.))
389 }
390 TabVariant::Outline => {
391 let padding = Edges::all(px(0.));
392 (cx.theme().transparent.into(), padding, default_gap)
393 }
394 TabVariant::Pill => {
395 let padding = Edges::all(px(0.));
396 (cx.theme().transparent.into(), padding, px(4.))
397 }
398 TabVariant::Segmented => {
399 let padding_x = match self.size {
400 Size::XSmall => px(2.),
401 Size::Small => px(3.),
402 _ => px(4.),
403 };
404 let padding = Edges {
405 left: padding_x,
406 right: padding_x,
407 ..Default::default()
408 };
409
410 (cx.theme().tokens.tab_bar_segmented.into(), padding, px(2.))
411 }
412 TabVariant::Underline => {
413 let gap = match self.size {
415 Size::XSmall => px(10.),
416 Size::Small => px(12.),
417 Size::Large => px(20.),
418 _ => px(16.),
419 };
420
421 (cx.theme().transparent.into(), Edges::all(px(0.)), gap)
422 }
423 TabVariant::Folder => (
424 cx.theme().tokens.tab_bar.into(),
425 Edges::all(px(0.)),
426 FOLDER_TAB_GAP,
427 ),
428 };
429 let overhang = self.variant.overhang(self.size, cx);
430 let tabs_top_padding = match self.variant {
433 TabVariant::Folder => FolderTabMetrics::new(self.size, cx).top_padding,
434 _ => px(0.),
435 };
436
437 let has_indicator = matches!(
438 self.variant,
439 TabVariant::Segmented | TabVariant::Pill | TabVariant::Underline
440 );
441 let num_tabs = self.children.len();
442 let rtl = LayoutDirection::global(cx).is_rtl();
443 let has_suffix_or_menu = self.suffix.is_some() || self.menu;
444
445 let bounds_rc = if has_indicator && num_tabs > 0 {
448 let rc: Rc<RefCell<TabIndicatorBounds>> = window
449 .use_keyed_state(format!("{}-tab-bounds", self.id), cx, |_, _| {
450 Rc::new(RefCell::new(TabIndicatorBounds::new(num_tabs)))
451 })
452 .read(cx)
453 .clone();
454 rc.borrow_mut().resize(num_tabs);
455 Some(rc)
456 } else {
457 None
458 };
459
460 let scroll_handle = self.scroll_handle.clone().unwrap_or_else(|| {
462 window
463 .use_keyed_state(format!("{}-scroll", self.id), cx, |_, _| {
464 ScrollHandle::new()
465 })
466 .read(cx)
467 .clone()
468 });
469 let reveal = TabReveal {
470 spring_id: format!("{}-reveal", self.id).into(),
471 target: window.use_keyed_state(format!("{}-reveal", self.id), cx, |_, _| None),
472 scroll_handle: scroll_handle.clone(),
473 view: window.current_view(),
474 peek: match self.size {
475 Size::XSmall | Size::Small => px(24.),
476 Size::Large => px(40.),
477 _ => px(32.),
478 },
479 num_tabs,
480 rtl,
481 leading: usize::from(rtl && has_suffix_or_menu),
482 };
483 reveal.advance(window, cx);
484
485 let padding_x = paddings.left;
486 let indicator = self.render_indicator(&bounds_rc, window, cx);
487 let indicator_epoch = indicator.as_ref().map(|(_, epoch)| *epoch).unwrap_or(0);
488 let mut indicator_element = indicator.map(|(el, _)| el);
489 let indicator_ready = indicator_element.is_some();
490
491 let view = window.current_view();
492 let mut item_metas: Vec<(
493 Option<SharedString>,
494 Option<Icon>,
495 bool,
496 Option<TabClickHandler>,
497 )> = Vec::new();
498 let selected_index = self.selected_index;
499 let tabs = self.base;
500 let mut rendered_tabs = Vec::with_capacity(self.children.len());
501 let max_width = self.max_width;
502 let hovered_tab = (self.variant == TabVariant::Folder).then(|| {
505 window.use_keyed_state(format!("{}-tab-hovered", self.id), cx, |_, _| None::<usize>)
506 });
507 let hovered_ix = hovered_tab.as_ref().and_then(|state| *state.read(cx));
508 let has_shape = |ix| selected_index == Some(ix) || hovered_ix == Some(ix);
509
510 for (ix, child) in self.children.into_iter().enumerate() {
511 item_metas.push((
512 child.label.clone(),
513 child.icon.clone(),
514 child.disabled,
515 None,
516 ));
517 let tab_bar_prefix = child.tab_bar_prefix.unwrap_or(true);
518 let mut tab = child
519 .ix(ix)
520 .tab_bar_prefix(tab_bar_prefix)
521 .max_width(max_width)
522 .with_variant(self.variant)
523 .with_size(self.size);
524 tab.indicator_active = has_indicator;
525 tab.indicator_ready = indicator_ready;
526 tab.indicator_epoch = indicator_epoch;
527 tab.hovered = hovered_ix == Some(ix);
528 tab.separator = self.variant == TabVariant::Folder
529 && ix + 1 < num_tabs
530 && !has_shape(ix)
531 && !has_shape(ix + 1);
532 let disabled = tab.disabled;
533 let mut tab = tab
534 .when_some(selected_index, |tab, selected_index| {
535 tab.selected(selected_index == ix)
536 })
537 .map(|mut tab| {
538 let on_click: Option<TabClickHandler> = match self.on_click.clone() {
540 Some(on_click) => {
541 Some(Rc::new(move |_, window, cx| on_click(&ix, window, cx)))
542 }
543 None => tab.on_click.take(),
544 };
545 tab.on_click = on_click.map(|on_click| {
546 let reveal = reveal.clone();
547 Rc::new(
548 move |event: &ClickEvent, window: &mut Window, cx: &mut App| {
549 reveal.reveal(ix, cx);
550 on_click(event, window, cx)
551 },
552 ) as TabClickHandler
553 });
554 tab
555 });
556 if let Some(meta) = item_metas.last_mut() {
559 meta.3 = tab.on_click.clone();
560 }
561 let flex_grow = tab.style().flex_grow;
564 let flex_basis = tab.style().flex_basis;
565 let push_end = rtl && !has_suffix_or_menu && ix + 1 == num_tabs;
570
571 rendered_tabs.push(if let Some(ref rc) = bounds_rc {
572 let rc = rc.clone();
573 let selected = selected_index == Some(ix);
574 div()
578 .flex_shrink_0()
579 .map(|mut this| {
580 this.style().flex_grow = flex_grow;
581 this.style().flex_basis = flex_basis;
582 this
583 })
584 .when(push_end, |this| this.ml_auto())
585 .on_prepaint(move |bounds, window, _| {
586 let mut measured = rc.borrow_mut();
587 if let Some(slot) = measured.tabs.get_mut(ix) {
588 *slot = bounds;
589 }
590 if selected && measured.container.size.width > px(0.) {
598 let first = measured
599 .tabs
600 .first()
601 .map_or(bounds.origin.x, |tab| tab.origin.x);
602 if (bounds.origin.x - first, bounds.size.width) != measured.placed {
603 window.on_next_frame(move |_, cx| cx.notify(view));
604 }
605 }
606 })
607 .relative()
608 .when(ix == 0, |this| {
609 this.when_some(indicator_element.take(), |this, indicator| {
610 this.child(indicator)
611 })
612 })
613 .child(tab)
614 .into_any_element()
615 } else if let Some(hovered_tab) = hovered_tab.clone() {
616 div()
617 .id(("folder-tab", ix))
618 .flex_shrink_0()
619 .map(|mut this| {
620 this.style().flex_grow = flex_grow;
621 this.style().flex_basis = flex_basis;
622 this
623 })
624 .when(push_end, |this| this.ml_auto())
625 .when(!disabled, |this| {
626 this.on_hover(move |hovered, _, cx| {
627 hovered_tab.update(cx, |state, cx| {
628 let next = match *hovered {
629 true => Some(ix),
630 false if *state == Some(ix) => None,
631 false => *state,
632 };
633 if next != *state {
634 *state = next;
635 cx.notify();
636 }
637 });
638 })
639 })
640 .child(tab)
641 .into_any_element()
642 } else {
643 tab.when(push_end, |this| this.ml_auto()).into_any_element()
644 });
645 }
646 if rtl {
649 rendered_tabs.reverse();
650 }
651 let last_empty_space = has_suffix_or_menu.then(|| {
652 div()
653 .flex_shrink_0()
654 .when(rtl, |this| this.ml_auto())
655 .child(self.last_empty_space)
656 });
657
658 tabs.group("tab-bar")
659 .relative()
660 .flex_row_dir(cx)
662 .items_center()
663 .bg(bg)
664 .text_color(cx.theme().tab_foreground)
665 .when(
666 self.variant == TabVariant::Underline || self.variant == TabVariant::Tab,
667 |this| {
668 this.child(
669 div()
670 .id("border-b")
671 .absolute()
672 .left_0()
673 .bottom_0()
674 .size_full()
675 .border_b_1()
676 .border_color(cx.theme().border),
677 )
678 },
679 )
680 .rounded(self.variant.tab_bar_radius(self.size, cx))
681 .paddings(paddings)
682 .refine_style(&self.style)
683 .when_some(self.prefix, |this, prefix| this.child(prefix))
684 .child(
685 h_flex()
686 .id("tabs")
687 .flex_1()
688 .min_w_0()
689 .mx(-padding_x)
690 .px(padding_x)
691 .overflow_x_hidden()
692 .when_some(bounds_rc.clone(), |this, rc| {
695 this.on_prepaint(move |bounds, _, _| {
696 rc.borrow_mut().container = bounds;
697 })
698 })
699 .child(
700 h_flex()
701 .id("tabs-inner")
702 .flex_1()
705 .relative()
708 .px(overhang)
710 .pt(tabs_top_padding)
711 .gap(gap)
712 .overflow_x_scroll()
713 .lock_scroll_axis()
714 .track_scroll(&scroll_handle)
715 .map(|this| {
716 if rtl {
717 this.children(last_empty_space).children(rendered_tabs)
718 } else {
719 this.children(rendered_tabs).children(last_empty_space)
720 }
721 }),
722 )
723 .child(ScrollableMask::vertical_wheel(&scroll_handle)),
725 )
726 .when(self.menu, |this| {
727 this.child(
728 Button::new("more")
729 .xsmall()
730 .ghost()
731 .dropdown_caret(true)
732 .dropdown_menu(move |mut this, _, _| {
733 this = this.scrollable(true);
734 for (ix, (label, icon, disabled, on_click)) in
735 item_metas.iter().enumerate()
736 {
737 let base = if let Some(label) = label.clone() {
738 PopupMenuItem::new(label)
739 } else if let Some(icon) = icon.clone() {
740 PopupMenuItem::element(move |_, _| icon.clone())
741 } else {
742 PopupMenuItem::new(t!("Dock.Unnamed"))
743 };
744 this = this.item(
745 base.checked(selected_index == Some(ix))
746 .disabled(*disabled)
747 .when_some(on_click.clone(), |this, on_click| {
748 this.on_click(move |event, window, cx| {
749 on_click(event, window, cx)
750 })
751 }),
752 );
753 }
754
755 this
756 })
757 .anchor(Anchor::TopRight),
758 )
759 })
760 .when_some(self.suffix, |this, suffix| this.child(suffix))
761 }
762}
763
764type TabClickHandler = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>;
765
766#[derive(Clone)]
771struct TabReveal {
772 spring_id: SharedString,
773 target: Entity<Option<RevealTarget>>,
775 scroll_handle: ScrollHandle,
776 view: EntityId,
777 peek: Pixels,
779 num_tabs: usize,
780 rtl: bool,
782 leading: usize,
784}
785
786#[derive(Clone, Copy)]
787struct RevealTarget {
788 to: Pixels,
789 last: Option<Pixels>,
791}
792
793impl TabReveal {
794 fn reveal(&self, ix: usize, cx: &mut App) {
795 let Some(to) = self.offset_revealing(ix) else {
796 return;
797 };
798 let running = self.target.read(cx).is_some();
799 if !running && to == self.scroll_handle.offset().x {
800 return;
801 }
802 self.target.update(cx, |target, _| match target {
803 Some(target) => target.to = to,
805 None => *target = Some(RevealTarget { to, last: None }),
806 });
807 cx.notify(self.view);
808 }
809
810 fn item(&self, ix: usize) -> Option<Bounds<Pixels>> {
813 if ix >= self.num_tabs {
814 return None;
815 }
816 let child = match self.rtl {
817 false => ix,
818 true => self.leading + self.num_tabs - 1 - ix,
819 };
820 self.scroll_handle.bounds_for_item(child)
821 }
822
823 fn offset_revealing(&self, ix: usize) -> Option<Pixels> {
826 let handle = &self.scroll_handle;
827 let viewport = handle.bounds();
828 let tab = self.item(ix)?;
829 let max = handle.max_offset().x;
830 let (left_ix, right_ix) = match self.rtl {
833 false => (ix.checked_sub(1), Some(ix + 1)),
834 true => (Some(ix + 1), ix.checked_sub(1)),
835 };
836 let want_left = match left_ix.and_then(|ix| self.item(ix)) {
839 Some(prev) => (prev.right() - self.peek).max(prev.left()),
840 None => viewport.left(),
841 };
842 let want_right = match right_ix.and_then(|ix| self.item(ix)) {
843 Some(next) => (next.left() + self.peek).min(next.right()),
844 None => viewport.right() + max,
845 };
846
847 let mut offset = handle.offset().x;
848 let show_left = |offset: &mut Pixels, left: Pixels| {
849 if left < viewport.left() - *offset {
850 *offset = viewport.left() - left;
851 }
852 };
853 let show_right = |offset: &mut Pixels, right: Pixels| {
854 if right > viewport.right() - *offset {
855 *offset = viewport.right() - right;
856 }
857 };
858 if tab.center().x + offset > viewport.center().x {
861 show_left(&mut offset, want_left);
862 show_right(&mut offset, want_right);
863 } else {
864 show_right(&mut offset, want_right);
865 show_left(&mut offset, want_left);
866 }
867 show_right(&mut offset, tab.right());
868 show_left(&mut offset, tab.left());
869 Some(offset.min(px(0.)).max(-max))
870 }
871
872 fn advance(&self, window: &mut Window, cx: &mut App) {
874 let Some(target) = *self.target.read(cx) else {
875 return;
876 };
877 let offset = self.scroll_handle.offset();
878 if target.last.is_some_and(|last| last != offset.x) {
880 self.target.update(cx, |target, _| *target = None);
881 return;
882 }
883
884 let policy = cx.theme().motion_tokens().spring_move;
885 if target.last.is_none() {
886 spring(
888 self.spring_id.clone(),
889 offset.x,
890 policy.with_travel(false),
891 window,
892 cx,
893 );
894 }
895 let x = spring(self.spring_id.clone(), target.to, policy, window, cx);
896 self.scroll_handle.set_offset(point(x, offset.y));
897 self.target.update(cx, |state, _| {
898 *state = (x != target.to).then_some(RevealTarget {
899 last: Some(x),
900 ..target
901 })
902 });
903 }
904}
905
906#[cfg(test)]
907mod tests {
908 use std::{
909 cell::{Cell, RefCell},
910 rc::Rc,
911 };
912
913 use gpui::{Context, Modifiers, MouseButton, MouseUpEvent, Render, TestAppContext};
914
915 use super::*;
916 use crate::scroll::ScrollableElement as _;
917
918 struct Harness {
919 group_handler: bool,
920 disabled: bool,
921 child_clicks: Rc<Cell<usize>>,
922 group_clicks: Rc<Cell<usize>>,
923 }
924
925 impl Render for Harness {
926 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
927 let child_clicks = self.child_clicks.clone();
928 let group_clicks = self.group_clicks.clone();
929 TabBar::new("tabs")
930 .w(px(240.))
931 .child(
932 Tab::new()
933 .debug_selector(|| "first-tab".into())
934 .disabled(self.disabled)
935 .label("First")
936 .on_click(move |_, _, _| child_clicks.set(child_clicks.get() + 1)),
937 )
938 .when(self.group_handler, |tabs| {
939 tabs.on_click(move |ix, _, _| group_clicks.set(*ix + 1))
940 })
941 }
942 }
943
944 fn harness(
945 cx: &mut TestAppContext,
946 group_handler: bool,
947 disabled: bool,
948 ) -> (
949 &mut gpui::VisualTestContext,
950 Rc<Cell<usize>>,
951 Rc<Cell<usize>>,
952 ) {
953 cx.update(crate::theme::init);
954 let child_clicks = Rc::new(Cell::new(0));
955 let group_clicks = Rc::new(Cell::new(0));
956 let (_, cx) = cx.add_window_view({
957 let child_clicks = child_clicks.clone();
958 let group_clicks = group_clicks.clone();
959 move |_, _| Harness {
960 group_handler,
961 disabled,
962 child_clicks,
963 group_clicks,
964 }
965 });
966 cx.update(|window, cx| window.draw(cx).clear(cx));
967 (cx, child_clicks, group_clicks)
968 }
969
970 #[gpui::test]
971 fn group_callback_overrides_child_callback(cx: &mut TestAppContext) {
972 let (cx, child_clicks, group_clicks) = harness(cx, true, false);
973 let position = cx.debug_bounds("first-tab").unwrap().center();
974 cx.simulate_click(position, Modifiers::default());
975 assert_eq!(child_clicks.get(), 0);
976 assert_eq!(group_clicks.get(), 1);
977 }
978
979 #[gpui::test]
980 fn child_callback_is_preserved_without_group_callback(cx: &mut TestAppContext) {
981 let (cx, child_clicks, group_clicks) = harness(cx, false, false);
982 let position = cx.debug_bounds("first-tab").unwrap().center();
983 cx.simulate_click(position, Modifiers::default());
984 assert_eq!(child_clicks.get(), 1);
985 assert_eq!(group_clicks.get(), 0);
986 }
987
988 #[gpui::test]
989 fn disabled_tab_suppresses_child_and_group_callbacks(cx: &mut TestAppContext) {
990 let (cx, child_clicks, group_clicks) = harness(cx, true, true);
991 let position = cx.debug_bounds("first-tab").unwrap().center();
992 cx.simulate_click(position, Modifiers::default());
993 assert_eq!(child_clicks.get(), 0);
994 assert_eq!(group_clicks.get(), 0);
995 }
996
997 struct MenuHarness {
998 group_handler: bool,
999 clicks: Rc<RefCell<Vec<String>>>,
1000 events: Rc<RefCell<Vec<ClickEvent>>>,
1001 }
1002
1003 impl Render for MenuHarness {
1004 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1005 let events = self.events.clone();
1006 let tab = |label: &'static str, clicks: Rc<RefCell<Vec<String>>>| {
1007 let events = events.clone();
1008 Tab::new()
1009 .debug_selector(move || format!("{label}-tab"))
1010 .label(label)
1011 .on_click(move |event, _, _| {
1012 clicks.borrow_mut().push(format!("tab {label}"));
1013 events.borrow_mut().push(event.clone());
1014 })
1015 };
1016 let clicks = self.clicks.clone();
1017 div().size_full().child(
1018 TabBar::new("menu-tabs")
1019 .w(px(240.))
1020 .menu(true)
1021 .child(tab("First", self.clicks.clone()))
1022 .child(tab("Second", self.clicks.clone()))
1023 .when(self.group_handler, |tabs| {
1024 tabs.on_click(move |ix, _, _| clicks.borrow_mut().push(format!("bar {ix}")))
1025 }),
1026 )
1027 }
1028 }
1029
1030 fn choose_first_menu_item(
1032 group_handler: bool,
1033 activate: impl FnOnce(&mut gpui::VisualTestContext),
1034 cx: &mut TestAppContext,
1035 ) -> (Vec<String>, Vec<ClickEvent>) {
1036 cx.update(crate::init);
1037 let clicks = Rc::new(RefCell::new(Vec::new()));
1038 let events = Rc::new(RefCell::new(Vec::new()));
1039 let (_, cx) = cx.add_window_view({
1040 let clicks = clicks.clone();
1041 let events = events.clone();
1042 move |_, _| MenuHarness {
1043 group_handler,
1044 clicks,
1045 events,
1046 }
1047 });
1048 cx.update(|window, cx| window.draw(cx).clear(cx));
1049 let tab = cx.debug_bounds("First-tab").unwrap();
1050 let more = point(px(232.), tab.center().y);
1052 cx.simulate_mouse_down(more, MouseButton::Left, Modifiers::default());
1053 cx.simulate_event(MouseUpEvent {
1054 position: more,
1055 button: MouseButton::Left,
1056 modifiers: Modifiers::default(),
1057 click_count: 1,
1058 });
1059 cx.run_until_parked();
1060 cx.update(|window, cx| window.draw(cx).clear(cx));
1061 activate(cx);
1062 cx.run_until_parked();
1063 (clicks.borrow().clone(), events.borrow().clone())
1064 }
1065
1066 #[gpui::test]
1067 fn overflow_menu_runs_the_tab_callback_without_a_bar_callback(cx: &mut TestAppContext) {
1068 assert_eq!(
1069 choose_first_menu_item(false, |cx| cx.simulate_keystrokes("down enter"), cx).0,
1070 vec!["tab First".to_string()]
1071 );
1072 }
1073
1074 #[gpui::test]
1075 fn overflow_menu_prefers_the_bar_callback(cx: &mut TestAppContext) {
1076 assert_eq!(
1077 choose_first_menu_item(true, |cx| cx.simulate_keystrokes("down enter"), cx).0,
1078 vec!["bar 0".to_string()]
1079 );
1080 }
1081
1082 #[cfg(feature = "test-support")]
1083 #[gpui::test]
1084 fn overflow_menu_preserves_pointer_events_and_keyboard_activation(cx: &mut TestAppContext) {
1085 let position = Cell::new(point(px(0.), px(0.)));
1086 let (clicks, events) = choose_first_menu_item(
1087 false,
1088 |cx| {
1089 let item = cx.update(|window, _| {
1090 gpui_base::test_support::find_all(window, &[], &ElementId::from(0usize))
1091 .into_iter()
1092 .find(|item| item.role() == Some(gpui::Role::MenuItem))
1093 .expect("first overflow menu item")
1094 });
1095 position.set(item.bounds().center());
1096 cx.simulate_click(
1097 position.get(),
1098 Modifiers {
1099 shift: true,
1100 ..Modifiers::default()
1101 },
1102 );
1103 },
1104 cx,
1105 );
1106 assert_eq!(clicks, vec!["tab First"]);
1107 assert_eq!(events.len(), 1);
1108 assert!(matches!(events[0], ClickEvent::Mouse(_)));
1109 assert!(events[0].modifiers().shift);
1110 assert_eq!(events[0].mouse_position(), Some(position.get()));
1111
1112 let (clicks, events) =
1113 choose_first_menu_item(false, |cx| cx.simulate_keystrokes("down enter"), cx);
1114 assert_eq!(clicks, vec!["tab First"]);
1115 assert_eq!(events.len(), 1);
1116 assert!(matches!(events[0], ClickEvent::Keyboard(_)));
1117 }
1118
1119 struct ContentHarness;
1120
1121 impl Render for ContentHarness {
1122 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1123 TabBar::new("content-tabs").w(px(320.)).child(
1124 Tab::new()
1125 .prefix(div().debug_selector(|| "tab-prefix".into()).child("P"))
1126 .child(div().debug_selector(|| "tab-child".into()).child("Content"))
1127 .suffix(div().debug_selector(|| "tab-suffix".into()).child("S")),
1128 )
1129 }
1130 }
1131
1132 #[gpui::test]
1133 fn prefix_content_and_suffix_keep_their_order(cx: &mut TestAppContext) {
1134 cx.update(crate::theme::init);
1135 let (_, cx) = cx.add_window_view(|_, _| ContentHarness);
1136 cx.update(|window, cx| window.draw(cx).clear(cx));
1137
1138 let prefix = cx.debug_bounds("tab-prefix").unwrap();
1139 let child = cx.debug_bounds("tab-child").unwrap();
1140 let suffix = cx.debug_bounds("tab-suffix").unwrap();
1141 assert!(prefix.origin.x < child.origin.x);
1142 assert!(child.origin.x < suffix.origin.x);
1143 assert!(prefix.size.width > px(0.));
1144 assert!(child.size.width > px(0.));
1145 assert!(suffix.size.width > px(0.));
1146 }
1147
1148 struct DirectionHarness {
1149 suffix: bool,
1150 }
1151
1152 impl Render for DirectionHarness {
1153 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1154 TabBar::new("direction-tabs")
1155 .w(px(400.))
1156 .child(Tab::new().child(div().debug_selector(|| "rtl-tab-0".into()).child("A")))
1157 .child(Tab::new().child(div().debug_selector(|| "rtl-tab-1".into()).child("B")))
1158 .when(self.suffix, |this| {
1159 this.suffix(div().debug_selector(|| "rtl-suffix".into()).child("S"))
1160 })
1161 }
1162 }
1163
1164 #[gpui::test]
1165 fn tabs_start_from_the_right_in_rtl(cx: &mut TestAppContext) {
1166 cx.update(|cx| {
1167 crate::theme::init(cx);
1168 gpui_base::LayoutDirection::Rtl.set_global(cx);
1169 });
1170 for suffix in [false, true] {
1171 let (_, cx) = cx.add_window_view(|_, _| DirectionHarness { suffix });
1172 cx.update(|window, cx| window.draw(cx).clear(cx));
1173
1174 let first = cx.debug_bounds("rtl-tab-0").unwrap();
1175 let second = cx.debug_bounds("rtl-tab-1").unwrap();
1176 assert!(second.right() < first.left(), "suffix: {suffix}");
1177 assert!(first.right() > px(360.), "suffix: {suffix}");
1179 if suffix {
1180 let suffix = cx.debug_bounds("rtl-suffix").unwrap();
1181 assert!(suffix.right() < second.left());
1182 }
1183 }
1184 }
1185
1186 struct ScrollHarness {
1187 scroll_handle: ScrollHandle,
1188 }
1189
1190 struct DynamicScrollHarness {
1191 scroll_handle: ScrollHandle,
1192 menu: bool,
1193 size: Size,
1194 tabs: usize,
1195 selected_index: usize,
1196 }
1197
1198 struct ManualScrollHarness {
1199 scroll_handle: ScrollHandle,
1200 tabs: usize,
1201 selected_index: usize,
1202 label: &'static str,
1203 top: Pixels,
1204 }
1205
1206 impl ScrollHarness {
1207 fn tabs() -> impl Iterator<Item = Tab> {
1208 (0..5).map(|ix| {
1209 Tab::new()
1210 .w(px(60.))
1211 .label(format!("Tab {ix}"))
1212 .debug_selector(move || format!("tab-{ix}"))
1213 })
1214 }
1215 }
1216
1217 impl Render for ScrollHarness {
1218 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1219 div().w(px(100.)).child(
1220 TabBar::new("scrolling-tabs")
1221 .w_full()
1222 .segmented()
1223 .menu(true)
1224 .track_scroll(&self.scroll_handle)
1225 .selected_index(4)
1226 .children(Self::tabs()),
1227 )
1228 }
1229 }
1230
1231 impl DynamicScrollHarness {
1232 fn tabs(&self) -> impl Iterator<Item = Tab> {
1233 (0..self.tabs).map(|ix| {
1234 Tab::new()
1235 .w(px(60.))
1236 .label(format!("Tab {ix}"))
1237 .debug_selector(move || format!("dynamic-tab-{ix}"))
1238 })
1239 }
1240 }
1241
1242 impl Render for DynamicScrollHarness {
1243 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1244 div()
1245 .w(px(100.))
1246 .debug_selector(|| "dynamic-bar".into())
1247 .child(
1248 TabBar::new("dynamic-scrolling-tabs")
1249 .with_size(self.size)
1250 .w_full()
1251 .segmented()
1252 .menu(self.menu)
1253 .track_scroll(&self.scroll_handle)
1254 .selected_index(self.selected_index)
1255 .children(self.tabs()),
1256 )
1257 }
1258 }
1259
1260 impl ManualScrollHarness {
1261 fn tabs(&self) -> impl Iterator<Item = Tab> {
1262 let width = if self.label == "old" {
1263 px(60.)
1264 } else {
1265 px(120.)
1266 };
1267 let label = self.label;
1268 (0..self.tabs).map(move |ix| {
1269 Tab::new()
1270 .w(width)
1271 .label(format!("Tab {ix} {label}"))
1272 .debug_selector(move || format!("manual-tab-{ix}"))
1273 })
1274 }
1275 }
1276
1277 impl Render for ManualScrollHarness {
1278 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1279 div().w(px(160.)).h(px(40.)).child(
1280 div().relative().top(self.top).w_full().child(
1281 TabBar::new("manual-scrolling-tabs")
1282 .w_full()
1283 .segmented()
1284 .menu(true)
1285 .track_scroll(&self.scroll_handle)
1286 .selected_index(self.selected_index)
1287 .children(self.tabs()),
1288 ),
1289 )
1290 }
1291 }
1292
1293 fn draw(cx: &mut gpui::VisualTestContext) {
1294 cx.run_until_parked();
1295 cx.update(|window, cx| window.draw(cx).clear(cx));
1296 }
1297
1298 #[gpui::test]
1299 fn scrolling_to_a_tab_uses_logical_tab_indices(cx: &mut TestAppContext) {
1300 cx.update(crate::theme::init);
1301 let scroll_handle = ScrollHandle::new();
1302 let (_, cx) = cx.add_window_view({
1303 let scroll_handle = scroll_handle.clone();
1304 move |_, _| ScrollHarness { scroll_handle }
1305 });
1306
1307 draw(cx);
1308 draw(cx);
1309 assert_eq!(scroll_handle.offset().x, px(0.));
1310 scroll_handle.scroll_to_item(4);
1311 draw(cx);
1312 draw(cx);
1313
1314 let viewport = scroll_handle.bounds();
1315 let last_tab = cx.debug_bounds("tab-4").unwrap();
1316 assert!(
1317 last_tab.left() >= viewport.left(),
1318 "last tab {last_tab:?} is left of viewport {viewport:?}, offset {:?}",
1319 scroll_handle.offset()
1320 );
1321 assert!(
1322 last_tab.right() <= viewport.right(),
1323 "last tab {last_tab:?} is right of viewport {viewport:?}, offset {:?}",
1324 scroll_handle.offset()
1325 );
1326 assert_eq!(scroll_handle.children_count(), 6);
1327 }
1328
1329 #[gpui::test]
1330 fn scrolling_to_a_new_tab_preserves_the_explicit_target(cx: &mut TestAppContext) {
1331 cx.update(crate::theme::init);
1332 let scroll_handle = ScrollHandle::new();
1333 let (view, cx) = cx.add_window_view({
1334 let scroll_handle = scroll_handle.clone();
1335 move |_, _| DynamicScrollHarness {
1336 scroll_handle,
1337 menu: true,
1338 size: Size::default(),
1339 tabs: 4,
1340 selected_index: 3,
1341 }
1342 });
1343
1344 draw(cx);
1345 draw(cx);
1346
1347 view.update(cx, |view, cx| {
1348 view.tabs = 5;
1349 view.selected_index = 4;
1350 view.scroll_handle.scroll_to_item(4);
1351 cx.notify();
1352 });
1353 draw(cx);
1354
1355 let viewport = scroll_handle.bounds();
1356 let last_tab = cx.debug_bounds("dynamic-tab-4").unwrap();
1357 assert!(last_tab.left() >= viewport.left());
1358 assert!(last_tab.right() <= viewport.right());
1359 assert_eq!(scroll_handle.children_count(), 6);
1360 }
1361
1362 #[gpui::test]
1363 fn scrolling_to_a_new_tab_preserves_bar_padding(cx: &mut TestAppContext) {
1364 cx.update(crate::theme::init);
1365 for (size, padding) in [
1366 (Size::XSmall, px(2.)),
1367 (Size::Small, px(3.)),
1368 (Size::Medium, px(4.)),
1369 (Size::Large, px(4.)),
1370 ] {
1371 let scroll_handle = ScrollHandle::new();
1372 let (view, cx) = cx.add_window_view({
1373 let scroll_handle = scroll_handle.clone();
1374 move |_, _| DynamicScrollHarness {
1375 scroll_handle,
1376 menu: false,
1377 size,
1378 tabs: 4,
1379 selected_index: 0,
1380 }
1381 });
1382 draw(cx);
1383 draw(cx);
1384 view.update(cx, |view, cx| {
1385 view.tabs = 5;
1386 view.scroll_handle.scroll_to_item(4);
1387 cx.notify();
1388 });
1389 draw(cx);
1390 draw(cx);
1391 let bar = cx.debug_bounds("dynamic-bar").unwrap();
1392 let last_tab = cx.debug_bounds("dynamic-tab-4").unwrap();
1393 assert_eq!(
1394 bar.right() - last_tab.right(),
1395 padding,
1396 "right padding for {size:?}"
1397 );
1398 scroll_handle.scroll_to_item(0);
1399 draw(cx);
1400 draw(cx);
1401 let first_tab = cx.debug_bounds("dynamic-tab-0").unwrap();
1402 assert_eq!(
1403 first_tab.left() - bar.left(),
1404 padding,
1405 "left padding for {size:?}"
1406 );
1407 assert_eq!(scroll_handle.children_count(), 5);
1408 }
1409 }
1410
1411 #[gpui::test]
1412 fn closing_an_unselected_trailing_tab_preserves_manual_scrolling(cx: &mut TestAppContext) {
1413 cx.update(crate::theme::init);
1414 let scroll_handle = ScrollHandle::new();
1415 let (view, cx) = cx.add_window_view({
1416 let scroll_handle = scroll_handle.clone();
1417 move |_, _| ManualScrollHarness {
1418 scroll_handle,
1419 tabs: 6,
1420 selected_index: 0,
1421 label: "old",
1422 top: px(0.),
1423 }
1424 });
1425
1426 draw(cx);
1427 scroll_handle.set_offset(gpui::point(px(-100.), px(0.)));
1428 draw(cx);
1429 assert_eq!(scroll_handle.offset().x, px(-100.));
1430
1431 view.update(cx, |view, cx| {
1432 view.tabs = 5;
1433 cx.notify();
1434 });
1435 draw(cx);
1436
1437 assert_eq!(scroll_handle.offset().x, px(-100.));
1438 }
1439
1440 #[gpui::test]
1441 fn changing_selection_does_not_move_manual_scrolling(cx: &mut TestAppContext) {
1442 cx.update(crate::theme::init);
1443 let scroll_handle = ScrollHandle::new();
1444 let (view, cx) = cx.add_window_view({
1445 let scroll_handle = scroll_handle.clone();
1446 move |_, _| ManualScrollHarness {
1447 scroll_handle,
1448 tabs: 6,
1449 selected_index: 0,
1450 label: "old",
1451 top: px(0.),
1452 }
1453 });
1454
1455 draw(cx);
1456 scroll_handle.set_offset(gpui::point(px(-100.), px(0.)));
1457 draw(cx);
1458
1459 view.update(cx, |view, cx| {
1460 view.selected_index = 5;
1461 cx.notify();
1462 });
1463 draw(cx);
1464
1465 assert_eq!(scroll_handle.offset().x, px(-100.));
1466 }
1467
1468 #[gpui::test]
1469 fn changing_tab_labels_does_not_move_manual_scrolling(cx: &mut TestAppContext) {
1470 cx.update(crate::theme::init);
1471 let scroll_handle = ScrollHandle::new();
1472 let (view, cx) = cx.add_window_view({
1473 let scroll_handle = scroll_handle.clone();
1474 move |_, _| ManualScrollHarness {
1475 scroll_handle,
1476 tabs: 6,
1477 selected_index: 0,
1478 label: "old",
1479 top: px(0.),
1480 }
1481 });
1482
1483 draw(cx);
1484 scroll_handle.set_offset(gpui::point(px(-100.), px(0.)));
1485 draw(cx);
1486
1487 view.update(cx, |view, cx| {
1488 view.label = "new";
1489 cx.notify();
1490 });
1491 draw(cx);
1492
1493 assert_eq!(scroll_handle.offset().x, px(-100.));
1494 }
1495
1496 #[gpui::test]
1497 fn moving_the_tab_bar_preserves_manual_scrolling(cx: &mut TestAppContext) {
1498 cx.update(crate::theme::init);
1499 let scroll_handle = ScrollHandle::new();
1500 let (view, cx) = cx.add_window_view({
1501 let scroll_handle = scroll_handle.clone();
1502 move |_, _| ManualScrollHarness {
1503 scroll_handle,
1504 tabs: 6,
1505 selected_index: 0,
1506 label: "old",
1507 top: px(0.),
1508 }
1509 });
1510
1511 draw(cx);
1512 scroll_handle.set_offset(gpui::point(px(-100.), px(0.)));
1513 draw(cx);
1514 assert_eq!(scroll_handle.offset().x, px(-100.));
1515 let viewport_size = scroll_handle.bounds().size;
1516
1517 view.update(cx, |view, cx| {
1518 view.top = px(20.);
1519 cx.notify();
1520 });
1521 draw(cx);
1522
1523 assert_eq!(scroll_handle.bounds().size, viewport_size);
1524 assert_eq!(scroll_handle.offset().x, px(-100.));
1525 }
1526
1527 struct FlexHarness {
1528 variant: TabVariant,
1529 }
1530
1531 impl Render for FlexHarness {
1532 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1533 div()
1534 .w(px(200.))
1535 .debug_selector(|| "flex-bar".into())
1536 .child(
1537 TabBar::new("flex-tabs")
1538 .w_full()
1539 .with_variant(self.variant)
1540 .selected_index(0)
1541 .child(
1542 Tab::new()
1543 .flex_1()
1544 .label("A")
1545 .debug_selector(|| "flex-tab-0".into()),
1546 )
1547 .child(
1548 Tab::new()
1549 .flex_1()
1550 .label("B")
1551 .debug_selector(|| "flex-tab-1".into()),
1552 ),
1553 )
1554 }
1555 }
1556
1557 #[gpui::test]
1558 fn flex_tabs_share_the_available_width(cx: &mut TestAppContext) {
1559 cx.update(crate::theme::init);
1560 for variant in [
1561 TabVariant::Tab,
1562 TabVariant::Outline,
1563 TabVariant::Segmented,
1564 TabVariant::Pill,
1565 TabVariant::Underline,
1566 ] {
1567 let (_, cx) = cx.add_window_view(move |_, _| FlexHarness { variant });
1568 draw(cx);
1569 draw(cx);
1570
1571 let bar = cx.debug_bounds("flex-bar").unwrap();
1572 let first = cx.debug_bounds("flex-tab-0").unwrap();
1573 let second = cx.debug_bounds("flex-tab-1").unwrap();
1574 assert_eq!(first.size.width, second.size.width, "{variant:?}");
1575 assert_eq!(
1577 first.left() - bar.left(),
1578 bar.right() - second.right(),
1579 "{variant:?}"
1580 );
1581 assert!(
1582 bar.right() - second.right() <= px(4.),
1583 "{variant:?}: tabs end at {:?} but the bar ends at {:?}",
1584 second.right(),
1585 bar.right()
1586 );
1587 }
1588 }
1589
1590 struct ClickRevealHarness {
1591 group_handler: bool,
1592 scroll_handle: Option<ScrollHandle>,
1593 }
1594
1595 impl Render for ClickRevealHarness {
1596 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1597 div()
1599 .w(px(100.))
1600 .debug_selector(|| "click-bar".into())
1601 .child(
1602 TabBar::new("click-reveal-tabs")
1603 .w_full()
1604 .when_some(self.scroll_handle.as_ref(), |tabs, handle| {
1605 tabs.track_scroll(handle)
1606 })
1607 .children((0..5).map(|ix| {
1608 Tab::new()
1609 .w(px(60.))
1610 .label(format!("Tab {ix}"))
1611 .debug_selector(move || format!("click-tab-{ix}"))
1612 .on_click(|_, _, _| {})
1613 }))
1614 .when(self.group_handler, |tabs| tabs.on_click(|_, _, _| {})),
1615 )
1616 }
1617 }
1618
1619 fn click_reveal_harness(
1620 cx: &mut TestAppContext,
1621 group_handler: bool,
1622 scroll_handle: Option<ScrollHandle>,
1623 reduce_motion: bool,
1624 ) -> &mut gpui::VisualTestContext {
1625 cx.update(|cx| {
1626 crate::theme::init(cx);
1627 cx.set_reduce_motion(reduce_motion);
1628 });
1629 let (_, cx) = cx.add_window_view(move |_, _| ClickRevealHarness {
1630 group_handler,
1631 scroll_handle,
1632 });
1633 draw(cx);
1634 cx
1635 }
1636
1637 fn next_frame(cx: &mut gpui::VisualTestContext) {
1638 cx.executor()
1639 .advance_clock(std::time::Duration::from_millis(16));
1640 cx.update(|window, cx| window.simulate_next_frame(cx));
1641 draw(cx);
1642 }
1643
1644 #[gpui::test]
1645 fn clicking_a_clipped_tab_reveals_it_and_part_of_the_next(cx: &mut TestAppContext) {
1646 for group_handler in [false, true] {
1647 let cx = click_reveal_harness(cx, group_handler, None, true);
1648 let bar = cx.debug_bounds("click-bar").unwrap();
1649 let tab = cx.debug_bounds("click-tab-1").unwrap();
1650 assert!(tab.right() > bar.right(), "tab 1 starts clipped");
1651
1652 cx.simulate_click(tab.center(), Modifiers::default());
1653 draw(cx);
1654
1655 let tab = cx.debug_bounds("click-tab-1").unwrap();
1656 let next = cx.debug_bounds("click-tab-2").unwrap();
1657 assert!(tab.left() >= bar.left() && tab.right() <= bar.right());
1658 assert_eq!(bar.right() - next.left(), px(32.), "group: {group_handler}");
1659 }
1660 }
1661
1662 #[gpui::test]
1663 fn clicking_the_last_tab_reveals_the_end_of_the_bar(cx: &mut TestAppContext) {
1664 let scroll_handle = ScrollHandle::new();
1665 let cx = click_reveal_harness(cx, true, Some(scroll_handle.clone()), true);
1666 scroll_handle.set_offset(gpui::point(px(-160.), px(0.)));
1667 draw(cx);
1668
1669 let tab = cx.debug_bounds("click-tab-4").unwrap();
1670 cx.simulate_click(
1671 tab.origin + gpui::point(px(10.), px(10.)),
1672 Modifiers::default(),
1673 );
1674 draw(cx);
1675
1676 assert_eq!(scroll_handle.offset().x, -scroll_handle.max_offset().x);
1677 }
1678
1679 #[gpui::test]
1680 fn reveal_animates_and_yields_to_manual_scrolling(cx: &mut TestAppContext) {
1681 let scroll_handle = ScrollHandle::new();
1682 let cx = click_reveal_harness(cx, true, Some(scroll_handle.clone()), false);
1683
1684 let tab = cx.debug_bounds("click-tab-1").unwrap();
1685 cx.simulate_click(tab.center(), Modifiers::default());
1686 draw(cx);
1687 next_frame(cx);
1688 let moving = scroll_handle.offset().x;
1689 assert!(
1690 moving < px(0.) && moving > px(-52.),
1691 "mid-flight at {moving:?}"
1692 );
1693
1694 wheel(
1696 cx,
1697 scroll_handle.bounds().center(),
1698 gpui::ScrollDelta::Lines(point(0., 1.)),
1699 gpui::TouchPhase::Moved,
1700 );
1701 let manual = scroll_handle.offset().x;
1702 assert!(manual > moving);
1703 let after_wheel = cx.debug_bounds("click-tab-1").unwrap();
1704 for _ in 0..30 {
1705 next_frame(cx);
1706 }
1707 assert_eq!(scroll_handle.offset().x, manual);
1708 assert_eq!(cx.debug_bounds("click-tab-1").unwrap(), after_wheel);
1709
1710 cx.simulate_click(
1712 tab.center() - gpui::point(px(10.), px(0.)),
1713 Modifiers::default(),
1714 );
1715 for _ in 0..60 {
1716 next_frame(cx);
1717 }
1718 assert_eq!(scroll_handle.offset().x, px(-52.));
1719 }
1720
1721 struct WheelHarness {
1722 scroll_handle: Option<ScrollHandle>,
1723 variant: TabVariant,
1724 }
1725
1726 fn wheel_tabs(handle: Option<&ScrollHandle>, variant: TabVariant, tabs: usize) -> TabBar {
1727 TabBar::new("wheel-tabs")
1728 .w_full()
1729 .with_variant(variant)
1730 .when_some(handle, |tabs, handle| tabs.track_scroll(handle))
1731 .children((0..tabs).map(|ix| {
1732 Tab::new()
1733 .w(px(60.))
1734 .label(format!("Tab {ix}"))
1735 .debug_selector(move || format!("wheel-tab-{ix}"))
1736 }))
1737 }
1738
1739 impl Render for WheelHarness {
1740 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1741 div()
1742 .w(px(160.))
1743 .debug_selector(|| "wheel-bar".into())
1744 .child(wheel_tabs(self.scroll_handle.as_ref(), self.variant, 6))
1745 }
1746 }
1747
1748 fn wheel(
1749 cx: &mut gpui::VisualTestContext,
1750 position: gpui::Point<Pixels>,
1751 delta: gpui::ScrollDelta,
1752 touch_phase: gpui::TouchPhase,
1753 ) {
1754 cx.simulate_event(gpui::ScrollEvent {
1755 position,
1756 delta,
1757 touch_phase,
1758 ..Default::default()
1759 });
1760 draw(cx);
1761 }
1762
1763 #[gpui::test]
1764 fn vertical_mouse_wheel_scrolls_each_variant_with_and_without_a_tracked_handle(
1765 cx: &mut TestAppContext,
1766 ) {
1767 cx.update(crate::theme::init);
1768 for variant in [
1769 TabVariant::Tab,
1770 TabVariant::Outline,
1771 TabVariant::Segmented,
1772 TabVariant::Pill,
1773 TabVariant::Underline,
1774 TabVariant::Folder,
1775 ] {
1776 for tracked in [false, true] {
1777 let scroll_handle = tracked.then(ScrollHandle::new);
1778 let (_, cx) = cx.add_window_view({
1779 let scroll_handle = scroll_handle.clone();
1780 move |_, _| WheelHarness {
1781 scroll_handle,
1782 variant,
1783 }
1784 });
1785 draw(cx);
1786 draw(cx);
1787 let bar = cx.debug_bounds("wheel-bar").unwrap();
1788 let first_before = cx.debug_bounds("wheel-tab-0").unwrap();
1789 let last_before = cx.debug_bounds("wheel-tab-5").unwrap();
1790 assert!(
1791 last_before.left() > bar.right(),
1792 "{variant:?}, tracked: {tracked}"
1793 );
1794
1795 wheel(
1796 cx,
1797 first_before.center(),
1798 gpui::ScrollDelta::Lines(point(0., -100.)),
1799 gpui::TouchPhase::Moved,
1800 );
1801 let first_after = cx.debug_bounds("wheel-tab-0").unwrap();
1802 let last_after = cx.debug_bounds("wheel-tab-5").unwrap();
1803 assert!(
1804 first_after.left() < first_before.left(),
1805 "{variant:?}, tracked: {tracked}, bar {bar:?}, first {first_before:?}, after {first_after:?}"
1806 );
1807 assert!(last_after.left() >= bar.left() && last_after.right() <= bar.right());
1808 if let Some(handle) = &scroll_handle {
1809 assert_eq!(handle.offset().x, -handle.max_offset().x);
1810 assert_eq!(handle.offset().y, px(0.));
1811 }
1812
1813 wheel(
1814 cx,
1815 first_before.center(),
1816 gpui::ScrollDelta::Lines(point(0., 100.)),
1817 gpui::TouchPhase::Moved,
1818 );
1819 assert_eq!(cx.debug_bounds("wheel-tab-0").unwrap(), first_before);
1820 if let Some(handle) = &scroll_handle {
1821 assert_eq!(handle.offset(), point(px(0.), px(0.)));
1822 }
1823 }
1824 }
1825 }
1826
1827 #[derive(Clone)]
1828 enum WheelParent {
1829 Div(ScrollHandle),
1830 List(gpui::ListState),
1831 Scrollable,
1832 }
1833
1834 impl WheelParent {
1835 fn offset(&self) -> Option<(usize, Pixels)> {
1836 match self {
1837 Self::Div(handle) => Some((0, -handle.offset().y)),
1838 Self::List(state) => {
1839 let offset = state.logical_scroll_top();
1840 Some((offset.item_ix, offset.offset_in_item))
1841 }
1842 Self::Scrollable => None,
1845 }
1846 }
1847 }
1848
1849 struct NestedWheelHarness {
1850 parent: WheelParent,
1851 scroll_handle: ScrollHandle,
1852 tabs: usize,
1853 }
1854
1855 impl Render for NestedWheelHarness {
1856 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1857 match &self.parent {
1858 WheelParent::Div(parent) => crate::v_flex()
1859 .id("wheel-parent")
1860 .w(px(160.))
1861 .h(px(100.))
1862 .overflow_y_scroll()
1863 .lock_scroll_axis()
1864 .track_scroll(parent)
1865 .child(div().w_full().h(px(60.)).flex_shrink_0().child(wheel_tabs(
1866 Some(&self.scroll_handle),
1867 TabVariant::Tab,
1868 self.tabs,
1869 )))
1870 .child(div().h(px(400.)).flex_shrink_0())
1871 .into_any_element(),
1872 WheelParent::Scrollable => crate::v_flex()
1873 .w(px(160.))
1874 .h(px(100.))
1875 .child(div().w_full().h(px(60.)).flex_shrink_0().child(wheel_tabs(
1876 Some(&self.scroll_handle),
1877 TabVariant::Tab,
1878 self.tabs,
1879 )))
1880 .child(div().h(px(400.)).flex_shrink_0())
1881 .overflow_y_scrollbar()
1882 .into_any_element(),
1883 WheelParent::List(parent) => {
1884 let handle = self.scroll_handle.clone();
1885 let tabs = self.tabs;
1886 div()
1887 .w(px(160.))
1888 .h(px(100.))
1889 .child(
1890 gpui::list(parent.clone(), move |ix, _, _| {
1891 if ix == 0 {
1892 div()
1893 .w_full()
1894 .h(px(60.))
1895 .child(wheel_tabs(Some(&handle), TabVariant::Tab, tabs))
1896 .into_any_element()
1897 } else {
1898 div().w_full().h(px(40.)).into_any_element()
1899 }
1900 })
1901 .w_full()
1902 .h_full(),
1903 )
1904 .into_any_element()
1905 }
1906 }
1907 }
1908 }
1909
1910 #[gpui::test]
1911 fn vertical_mouse_wheel_uses_tabs_before_scrolling_ancestors(cx: &mut TestAppContext) {
1912 cx.update(crate::theme::init);
1913 for parent_kind in 0..3 {
1914 for (tabs, at_end) in [(6, false), (6, true), (1, false)] {
1915 let scroll_handle = ScrollHandle::new();
1916 let parent = match parent_kind {
1917 0 => WheelParent::Div(ScrollHandle::new()),
1918 1 => WheelParent::List(
1919 gpui::ListState::new(10, gpui::ListAlignment::Top, px(0.)).measure_all(),
1920 ),
1921 _ => WheelParent::Scrollable,
1922 };
1923 let (_, cx) = cx.add_window_view({
1924 let scroll_handle = scroll_handle.clone();
1925 let parent = parent.clone();
1926 move |_, _| NestedWheelHarness {
1927 parent,
1928 scroll_handle,
1929 tabs,
1930 }
1931 });
1932 draw(cx);
1933 draw(cx);
1934 if let WheelParent::List(state) = &parent {
1935 assert!(state.max_offset_for_scrollbar().y > px(0.));
1936 }
1937 if at_end {
1938 scroll_handle.set_offset(point(-scroll_handle.max_offset().x, px(0.)));
1939 draw(cx);
1940 }
1941 let before_x = scroll_handle.offset().x;
1942 let first_before = cx.debug_bounds("wheel-tab-0").unwrap();
1943 let position = scroll_handle.bounds().center();
1944 assert_eq!(parent.offset().unwrap_or_default(), (0, px(0.)));
1945 wheel(
1946 cx,
1947 position,
1948 gpui::ScrollDelta::Lines(point(0., -1.)),
1949 gpui::TouchPhase::Moved,
1950 );
1951 let first_after = cx.debug_bounds("wheel-tab-0").unwrap();
1952 if tabs > 1 && !at_end {
1953 assert!(scroll_handle.offset().x < before_x);
1954 assert!(first_after.left() < first_before.left());
1955 assert_eq!(parent.offset().unwrap_or_default(), (0, px(0.)));
1956 assert_eq!(first_after.top(), first_before.top());
1957 } else {
1958 assert_eq!(scroll_handle.offset().x, before_x);
1959 if let Some(offset) = parent.offset() {
1960 assert_ne!(
1961 offset,
1962 (0, px(0.)),
1963 "parent {parent_kind}, tabs {tabs}, at_end {at_end}, before_x {before_x:?}, first_before {first_before:?}, after {first_after:?}"
1964 );
1965 }
1966 assert!(first_after.top() < first_before.top());
1967 }
1968 }
1969 }
1970 }
1971
1972 struct WheelLineHeightHarness {
1973 scroll_handle: ScrollHandle,
1974 font_size: Pixels,
1975 line_height: Pixels,
1976 }
1977
1978 impl Render for WheelLineHeightHarness {
1979 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1980 div()
1983 .w(px(160.))
1984 .h(px(64.))
1985 .text_size(self.font_size)
1986 .line_height(self.line_height)
1987 .child(wheel_tabs(Some(&self.scroll_handle), TabVariant::Tab, 6))
1988 }
1989 }
1990
1991 #[gpui::test]
1992 fn vertical_mouse_wheel_uses_the_scroll_viewports_inherited_line_height(
1993 cx: &mut TestAppContext,
1994 ) {
1995 cx.update(crate::theme::init);
1996 for (font_size, line_height) in [(px(12.), px(18.)), (px(24.), px(48.))] {
1997 let scroll_handle = ScrollHandle::new();
1998 let (_, cx) = cx.add_window_view({
1999 let scroll_handle = scroll_handle.clone();
2000 move |_, _| WheelLineHeightHarness {
2001 scroll_handle,
2002 font_size,
2003 line_height,
2004 }
2005 });
2006 draw(cx);
2007 draw(cx);
2008 let first_before = cx.debug_bounds("wheel-tab-0").unwrap();
2009 assert!(scroll_handle.max_offset().x > line_height);
2010 assert_eq!(scroll_handle.offset(), point(px(0.), px(0.)));
2011
2012 let position = first_before.center();
2015 wheel(
2016 cx,
2017 position,
2018 gpui::ScrollDelta::Lines(point(0., -1.)),
2019 gpui::TouchPhase::Moved,
2020 );
2021 assert_eq!(
2022 scroll_handle.offset(),
2023 point(-line_height, px(0.)),
2024 "font {font_size:?}, line height {line_height:?}"
2025 );
2026 let first_after = cx.debug_bounds("wheel-tab-0").unwrap();
2027 assert_eq!(first_after.left() - first_before.left(), -line_height);
2028 assert_eq!(first_after.top(), first_before.top());
2029
2030 wheel(
2031 cx,
2032 position,
2033 gpui::ScrollDelta::Lines(point(0., 1.)),
2034 gpui::TouchPhase::Moved,
2035 );
2036 assert_eq!(scroll_handle.offset(), point(px(0.), px(0.)));
2037 assert_eq!(cx.debug_bounds("wheel-tab-0").unwrap(), first_before);
2038 }
2039 }
2040
2041 struct WheelHitboxHarness {
2042 scroll_handle: ScrollHandle,
2043 occluded: bool,
2044 }
2045
2046 impl Render for WheelHitboxHarness {
2047 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2048 div()
2049 .relative()
2050 .w(px(240.))
2051 .h(px(64.))
2052 .child(
2053 wheel_tabs(Some(&self.scroll_handle), TabVariant::Tab, 6)
2054 .prefix(
2055 div()
2056 .w(px(40.))
2057 .h(px(32.))
2058 .debug_selector(|| "wheel-prefix".into())
2059 .child("P"),
2060 )
2061 .suffix(
2062 div()
2063 .w(px(40.))
2064 .h(px(32.))
2065 .debug_selector(|| "wheel-suffix".into())
2066 .child("S"),
2067 ),
2068 )
2069 .when(self.occluded, |this| {
2070 this.child(
2071 div()
2072 .absolute()
2073 .inset_0()
2074 .occlude()
2075 .debug_selector(|| "wheel-occluder".into()),
2076 )
2077 })
2078 }
2079 }
2080
2081 #[gpui::test]
2082 fn vertical_mouse_wheel_respects_the_viewport_and_occluding_surfaces(cx: &mut TestAppContext) {
2083 cx.update(crate::theme::init);
2084 let scroll_handle = ScrollHandle::new();
2085 let (view, cx) = cx.add_window_view({
2086 let scroll_handle = scroll_handle.clone();
2087 move |_, _| WheelHitboxHarness {
2088 scroll_handle,
2089 occluded: false,
2090 }
2091 });
2092 draw(cx);
2093 draw(cx);
2094 let first_before = cx.debug_bounds("wheel-tab-0").unwrap();
2095 assert!(scroll_handle.max_offset().x > px(0.));
2096 assert_eq!(scroll_handle.offset(), point(px(0.), px(0.)));
2097
2098 for selector in ["wheel-prefix", "wheel-suffix"] {
2099 let position = cx.debug_bounds(selector).unwrap().center();
2100 assert!(!scroll_handle.bounds().contains(&position));
2101 wheel(
2102 cx,
2103 position,
2104 gpui::ScrollDelta::Lines(point(0., -1.)),
2105 gpui::TouchPhase::Moved,
2106 );
2107 assert_eq!(scroll_handle.offset(), point(px(0.), px(0.)));
2108 assert_eq!(cx.debug_bounds("wheel-tab-0").unwrap(), first_before);
2109 }
2110
2111 view.update(cx, |view, cx| {
2112 view.occluded = true;
2113 cx.notify();
2114 });
2115 draw(cx);
2116 let position = scroll_handle.bounds().center();
2117 let occluder = cx.debug_bounds("wheel-occluder").unwrap();
2118 assert!(occluder.size.width > px(0.) && occluder.size.height > px(0.));
2119 assert!(occluder.contains(&position));
2120 wheel(
2121 cx,
2122 position,
2123 gpui::ScrollDelta::Lines(point(0., -1.)),
2124 gpui::TouchPhase::Moved,
2125 );
2126 assert_eq!(scroll_handle.offset(), point(px(0.), px(0.)));
2127 assert_eq!(cx.debug_bounds("wheel-tab-0").unwrap(), first_before);
2128
2129 view.update(cx, |view, cx| {
2130 view.occluded = false;
2131 cx.notify();
2132 });
2133 draw(cx);
2134 wheel(
2135 cx,
2136 position,
2137 gpui::ScrollDelta::Lines(point(0., -1.)),
2138 gpui::TouchPhase::Moved,
2139 );
2140 assert!(scroll_handle.offset().x < px(0.));
2141 let first_after = cx.debug_bounds("wheel-tab-0").unwrap();
2142 assert!(first_after.left() < first_before.left());
2143 assert_eq!(first_after.top(), first_before.top());
2144 }
2145
2146 struct LateBar {
2149 shown: bool,
2150 width: Pixels,
2151 }
2152
2153 impl Render for LateBar {
2154 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2155 div()
2156 .w(self.width)
2157 .overflow_hidden()
2158 .when(self.shown, |this| {
2159 this.child(
2160 TabBar::new("late-tabs")
2161 .underline()
2162 .selected_index(0)
2163 .child(Tab::new().label("First"))
2164 .child(Tab::new().label("Second")),
2165 )
2166 })
2167 }
2168 }
2169
2170 fn show_late_bar(cx: &mut TestAppContext, width: Pixels) -> &mut gpui::VisualTestContext {
2173 cx.update(crate::theme::init);
2174 let (view, cx) = cx.add_window_view(move |_, _| LateBar {
2175 shown: false,
2176 width,
2177 });
2178 draw(cx);
2179 view.update(cx, |bar, cx| {
2180 bar.shown = true;
2181 cx.notify();
2182 });
2183 draw(cx);
2184 cx
2185 }
2186
2187 fn painted_indicators(cx: &mut gpui::VisualTestContext) -> Vec<Bounds<Pixels>> {
2189 cx.update(|window, cx| {
2190 let primary: Background = cx.theme().tokens.primary.into();
2191 let scale_factor = window.scale_factor();
2192 window
2193 .painted_quads()
2194 .into_iter()
2195 .filter(|quad| quad.background == primary)
2196 .map(|quad| quad.bounds.map(|value| px(value.0 / scale_factor)))
2197 .filter(|bounds| bounds.size.height == px(2.))
2198 .collect()
2199 })
2200 }
2201
2202 #[gpui::test]
2206 fn a_bar_shown_later_draws_its_indicator_on_the_next_frame(cx: &mut TestAppContext) {
2207 let cx = show_late_bar(cx, px(300.));
2208 next_frame(cx);
2209 let indicators = painted_indicators(cx);
2210 assert_eq!(indicators.len(), 1, "{indicators:?}");
2211 assert!(indicators[0].size.width > px(0.), "{indicators:?}");
2212 assert!(indicators[0].right() <= px(150.), "{indicators:?}");
2213 assert_eq!(cx.update(|window, cx| window.simulate_next_frame(cx)), 0);
2214 }
2215
2216 #[gpui::test]
2218 fn a_bar_with_no_width_asks_for_no_frames(cx: &mut TestAppContext) {
2219 let cx = show_late_bar(cx, px(0.));
2220 next_frame(cx);
2221 assert_eq!(cx.update(|window, cx| window.simulate_next_frame(cx)), 0);
2222 }
2223}