use std::{cell::RefCell, collections::HashMap, rc::Rc};
use arc_motion::{
EdgeFadeMask, EdgeFadeSide, LayoutSnapshot, arc_spring, arc_transition, is_reduced_motion,
layout::layout_scope_key, motion_now, sample_shared_layout,
};
use arc_tokens::{
ActiveArcLocale as _, ActiveArcTheme as _, ControlHeights, Radii, Shadows, Spacing, Typography,
};
use gpui_kit::{
AnyElement, App, BorderStyle, Bounds, Edges, ElementId, Hsla, IntoElement, ParentElement,
Pixels, RenderOnce, SharedString, Styled, TestSupportExt as _, Window,
assets::IconName,
base::{Tab as BaseTab, Tabs as BaseTabs},
bounds, canvas, div, point,
prelude::*,
px, quad, size,
};
type ValueChangeHandler = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
type ContentBuilder = Rc<dyn Fn(&mut Window, &mut App) -> AnyElement>;
const TRIGGER_RADIUS: Pixels = px(6.0);
const TRIGGER_MIN_WIDTH: Pixels = px(72.0);
const SCROLL_BUTTON_WIDTH: Pixels = px(28.0);
const EDGE_FADE_EXTENT: Pixels = px(28.0);
pub struct TabItem {
pub value: SharedString,
pub label: SharedString,
pub disabled: bool,
pub content: Option<ContentBuilder>,
}
impl TabItem {
pub fn new(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
Self {
value: value.into(),
label: label.into(),
disabled: false,
content: None,
}
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn content<E: IntoElement + 'static>(
mut self,
render: impl Fn(&mut Window, &mut App) -> E + 'static,
) -> Self {
self.content = Some(Rc::new(move |window, cx| {
render(window, cx).into_any_element()
}));
self
}
}
#[derive(Clone)]
struct TabsInternalState {
uncontrolled_active: SharedString,
last_active: SharedString,
direction: f32,
scroll_offset: f32,
pending_reveal: bool,
panel_enter_at_secs: f64,
prev_panel_height: Option<f32>,
measured_tabs: Rc<RefCell<HashMap<SharedString, Bounds<Pixels>>>>,
list_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
viewport_width: Rc<RefCell<f32>>,
content_width: Rc<RefCell<f32>>,
panel_height: Rc<RefCell<f32>>,
}
impl TabsInternalState {
fn new(initial: SharedString, now: f64) -> Self {
Self {
uncontrolled_active: initial.clone(),
last_active: initial,
direction: 1.0,
scroll_offset: 0.0,
pending_reveal: false,
panel_enter_at_secs: now - 10.0,
prev_panel_height: None,
measured_tabs: Rc::new(RefCell::new(HashMap::new())),
list_bounds: Rc::new(RefCell::new(None)),
viewport_width: Rc::new(RefCell::new(0.0)),
content_width: Rc::new(RefCell::new(0.0)),
panel_height: Rc::new(RefCell::new(0.0)),
}
}
}
fn compute_reveal_scroll(
tab_local_left: f32,
tab_local_right: f32,
current_scroll: f32,
viewport_width: f32,
content_width: f32,
) -> Option<f32> {
let max_scroll = (content_width - viewport_width).max(0.0);
if max_scroll <= 1.0 || viewport_width <= 0.0 {
return None;
}
let clearance = f32::from(SCROLL_BUTTON_WIDTH) + 3.0;
let left_inset = if current_scroll > 1.0 { clearance } else { 4.0 };
let right_inset = if current_scroll < max_scroll - 1.0 {
clearance
} else {
4.0
};
if tab_local_left < current_scroll + left_inset {
let target = if tab_local_left <= 8.0 {
0.0
} else {
(tab_local_left - clearance).clamp(0.0, max_scroll)
};
if (target - current_scroll).abs() > 0.5 {
return Some(target);
}
} else if tab_local_right > current_scroll + viewport_width - right_inset {
let target = if content_width - tab_local_right <= 8.0 {
max_scroll
} else {
(tab_local_right - viewport_width + clearance).clamp(0.0, max_scroll)
};
if (target - current_scroll).abs() > 0.5 {
return Some(target);
}
}
None
}
#[derive(IntoElement)]
pub struct Tabs {
id: ElementId,
value: Option<SharedString>,
default_value: Option<SharedString>,
items: Vec<TabItem>,
force_mount: bool,
max_width: Option<Pixels>,
on_value_change: Option<ValueChangeHandler>,
}
impl Tabs {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
value: None,
default_value: None,
items: Vec::new(),
force_mount: false,
max_width: None,
on_value_change: None,
}
}
pub fn value(mut self, value: impl Into<SharedString>) -> Self {
self.value = Some(value.into());
self
}
pub fn default_value(mut self, value: impl Into<SharedString>) -> Self {
self.default_value = Some(value.into());
self
}
pub fn tab(mut self, item: TabItem) -> Self {
self.items.push(item);
self
}
pub fn tabs(mut self, items: impl IntoIterator<Item = TabItem>) -> Self {
self.items.extend(items);
self
}
pub fn force_mount(mut self, force_mount: bool) -> Self {
self.force_mount = force_mount;
self
}
pub fn max_width(mut self, max_width: Pixels) -> Self {
self.max_width = Some(max_width);
self
}
pub fn on_value_change(
mut self,
handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
) -> Self {
self.on_value_change = Some(Rc::new(handler));
self
}
}
impl RenderOnce for Tabs {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.arc_theme().clone();
let colors = theme.colors;
let motion = theme.motion;
let reduced = is_reduced_motion(cx);
let now = motion_now(cx);
let fallback_active = self
.default_value
.clone()
.or_else(|| {
self.items
.iter()
.find(|item| !item.disabled)
.map(|item| item.value.clone())
})
.unwrap_or_default();
let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-tabs-state".into());
let state = window.use_keyed_state(state_id, cx, |_, _| {
TabsInternalState::new(fallback_active.clone(), now)
});
let snapshot = state.read(cx).clone();
let active = self
.value
.clone()
.unwrap_or_else(|| snapshot.uncontrolled_active.clone());
if snapshot.last_active != active {
let from_idx = self
.items
.iter()
.position(|i| i.value == snapshot.last_active);
let to_idx = self.items.iter().position(|i| i.value == active);
let direction = match (from_idx, to_idx) {
(Some(f), Some(t)) if f != t => {
if t > f {
1.0
} else {
-1.0
}
}
_ => snapshot.direction,
};
let current_h = *snapshot.panel_height.borrow();
state.update(cx, |s, _| {
s.last_active = active.clone();
s.direction = direction;
s.pending_reveal = true;
s.panel_enter_at_secs = now;
if current_h > 0.0 {
s.prev_panel_height = Some(current_h);
}
});
}
{
let snap_now = state.read(cx).clone();
let vp_w = *snap_now.viewport_width.borrow();
let content_w = *snap_now.content_width.borrow();
if snap_now.pending_reveal
&& vp_w > 0.0
&& content_w > 0.0
&& let Some(list_rect) = *snap_now.list_bounds.borrow()
&& let Some(tab_rect) = snap_now.measured_tabs.borrow().get(&active).copied()
{
let tab_left = f32::from(tab_rect.origin.x - list_rect.origin.x);
let tab_right = tab_left + f32::from(tab_rect.size.width);
let reveal_target = compute_reveal_scroll(
tab_left,
tab_right,
snap_now.scroll_offset,
vp_w,
content_w,
);
state.update(cx, |s, _| {
s.pending_reveal = false;
if let Some(next_scroll) = reveal_target {
s.scroll_offset = next_scroll;
}
});
}
}
let snapshot = state.read(cx).clone();
let direction = snapshot.direction;
let scope = layout_scope_key(&self.id);
let vp_w = *snapshot.viewport_width.borrow();
let content_w = *snapshot.content_width.borrow();
let max_scroll = (content_w - vp_w).max(0.0);
let clamped_scroll = snapshot.scroll_offset.clamp(0.0, max_scroll);
if (clamped_scroll - snapshot.scroll_offset).abs() > 0.5 {
state.update(cx, |s, _| {
s.scroll_offset = clamped_scroll;
});
}
let overflow = content_w > vp_w + 1.0 && vp_w > 0.0;
let can_scroll_left = overflow && clamped_scroll > 1.0;
let can_scroll_right = overflow && clamped_scroll < max_scroll - 1.0;
let animated_scroll = arc_spring(
(self.id.clone(), "scroll-x"),
clamped_scroll,
motion.spring.smooth,
window,
cx,
);
let is_controlled = self.value.is_some();
let total_tabs = self.items.len();
let current_item_keys: Vec<SharedString> =
self.items.iter().map(|i| i.value.clone()).collect();
let measured_for_pill = snapshot.measured_tabs.clone();
let list_bounds_ref = snapshot.list_bounds.clone();
let active_for_pill = active.clone();
let pill_scope = scope.clone();
let pill_bg = colors.surface;
let pill_border = colors.border;
let pill_shadows = Shadows::resting(theme.mode);
let morph_spec = motion.spring.morph;
let selection_backdrop = canvas(
move |list_rect, _, _| {
*list_bounds_ref.borrow_mut() = Some(list_rect);
},
move |list_rect, _, window, cx| {
let target_rect = measured_for_pill.borrow().get(&active_for_pill).copied();
let Some(rect) = target_rect else {
window.request_animation_frame();
return;
};
let local_rect = bounds(rect.origin - list_rect.origin, rect.size);
let target = LayoutSnapshot::uniform_radius(local_rect, TRIGGER_RADIUS);
let flip = sample_shared_layout(
pill_scope.clone(),
"selection",
target,
Some(morph_spec),
window,
cx,
);
let paint_bounds = bounds(list_rect.origin + flip.bounds.origin, flip.bounds.size);
window.paint_drop_shadows(paint_bounds, flip.corner_radii, &pill_shadows);
window.paint_quad(quad(
paint_bounds,
flip.corner_radii,
pill_bg,
Edges::all(px(1.0)),
pill_border,
BorderStyle::Solid,
));
},
)
.absolute()
.inset_0();
let mut base_tabs = BaseTabs::new(ElementId::NamedChild(
self.id.clone().into(),
"tablist".into(),
))
.relative()
.flex()
.flex_row()
.items_center()
.gap(Spacing::S1)
.p(Spacing::S1)
.ml(px(-animated_scroll))
.child(selection_backdrop);
for (index, item) in self.items.iter().enumerate() {
let item_value = item.value.clone();
let selected = active == item.value;
let disabled = item.disabled;
let tab_id = ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("tab-{}", item.value)),
);
let state_for_click = state.clone();
let on_value_change = self.on_value_change.clone();
let value_for_click = item_value.clone();
let measured_for_tab = snapshot.measured_tabs.clone();
let value_for_measure = item_value.clone();
let label_color = if selected {
colors.accent_strong
} else {
colors.text_muted
};
let measure_canvas = canvas(
move |tab_rect, _, _| {
measured_for_tab
.borrow_mut()
.insert(value_for_measure.clone(), tab_rect);
},
|_, _, _, _| {},
)
.absolute()
.inset_0();
let tab_el = BaseTab::new(tab_id)
.selected(selected)
.disabled(disabled)
.accessibility_label(item.label.clone())
.set_position(index + 1, total_tabs)
.on_click(move |_, window, cx| {
if !is_controlled {
state_for_click.update(cx, |s, _| {
s.uncontrolled_active = value_for_click.clone();
});
}
if let Some(handler) = &on_value_change {
handler(&value_for_click, window, cx);
}
window.refresh();
})
.relative()
.flex_none()
.min_w(TRIGGER_MIN_WIDTH)
.min_h(ControlHeights::SM)
.px(Spacing::S3)
.rounded(TRIGGER_RADIUS)
.text_size(Typography::TEXT_SM)
.text_color(label_color)
.when(!disabled && !selected, |this| {
let fg = colors.foreground;
this.hover(move |style| style.text_color(fg))
})
.when(disabled, |this| this.opacity(0.5))
.when(!disabled, |this| this.cursor_pointer())
.child(measure_canvas)
.child(item.label.clone());
base_tabs = base_tabs.child(tab_el);
}
let vp_width_ref = snapshot.viewport_width.clone();
let content_width_for_vp = snapshot.content_width.clone();
let measured_for_vp = snapshot.measured_tabs.clone();
let list_bounds_for_vp = snapshot.list_bounds.clone();
let surface_muted = colors.surface_muted;
let viewport_overlay = canvas(
move |vp_rect, window, _| {
let next_vp = f32::from(vp_rect.size.width);
let measured = measured_for_vp.borrow();
let mut min_left = f32::INFINITY;
let mut max_right = f32::NEG_INFINITY;
for key in ¤t_item_keys {
if let Some(tab_rect) = measured.get(key) {
min_left = min_left.min(f32::from(tab_rect.origin.x));
max_right =
max_right.max(f32::from(tab_rect.origin.x + tab_rect.size.width));
}
}
drop(measured);
let tabs_span =
if min_left.is_finite() && max_right.is_finite() && max_right > min_left {
(max_right - min_left) + f32::from(Spacing::S1) * 2.0
} else {
0.0
};
let list_w = list_bounds_for_vp
.borrow()
.map_or(0.0, |r| f32::from(r.size.width));
let next_content = tabs_span.max(list_w);
let prev_vp = *vp_width_ref.borrow();
let prev_content = *content_width_for_vp.borrow();
*vp_width_ref.borrow_mut() = next_vp;
*content_width_for_vp.borrow_mut() = next_content;
if (next_vp - prev_vp).abs() > 0.5 || (next_content - prev_content).abs() > 0.5 {
window.request_animation_frame();
}
},
move |vp_rect, _, window, _| {
let avail_w =
(f32::from(vp_rect.size.width) - f32::from(SCROLL_BUTTON_WIDTH)).max(0.0);
if can_scroll_left && avail_w > 0.0 {
let left_rect = bounds(
point(vp_rect.origin.x + SCROLL_BUTTON_WIDTH, vp_rect.origin.y),
size(px(avail_w), vp_rect.size.height),
);
EdgeFadeMask::new(EdgeFadeSide::Left, EDGE_FADE_EXTENT, surface_muted)
.paint(left_rect, window);
}
if can_scroll_right && avail_w > 0.0 {
let right_rect = bounds(vp_rect.origin, size(px(avail_w), vp_rect.size.height));
EdgeFadeMask::new(EdgeFadeSide::Right, EDGE_FADE_EXTENT, surface_muted)
.paint(right_rect, window);
}
},
)
.absolute()
.inset_0();
let state_wheel = state.clone();
let state_left = state.clone();
let state_right = state.clone();
let viewport_id = ElementId::NamedChild(self.id.clone().into(), "viewport".into());
let left_btn_id = ElementId::NamedChild(self.id.clone().into(), "scroll-left".into());
let right_btn_id = ElementId::NamedChild(self.id.clone().into(), "scroll-right".into());
let scroll_btn_hover_bg = colors.surface;
let ui_strings = cx.arc_locale().ui_strings();
let list_shell = div()
.relative()
.self_start()
.flex()
.flex_row()
.items_center()
.max_w_full()
.when_some(self.max_width, |this, mw| this.max_w(mw))
.overflow_hidden()
.border_1()
.border_color(colors.border)
.rounded(Radii::CONTROL)
.bg(colors.surface_muted)
.child(
div()
.id(viewport_id)
.relative()
.min_w_0()
.max_w_full()
.overflow_hidden()
.rounded(Radii::CONTROL)
.on_scroll(move |event, window, cx| {
let delta = event.delta.pixel_delta(px(24.0));
let dx = f32::from(delta.x);
let dy = f32::from(delta.y);
let step = if dx.abs() > 0.5 {
-dx
} else if event.modifiers.shift {
-dy
} else {
0.0
};
if step.abs() <= 0.5 {
return;
}
let mut changed = false;
state_wheel.update(cx, |s, _| {
let vp = *s.viewport_width.borrow();
let max_s = (*s.content_width.borrow() - vp).max(0.0);
if max_s > 1.0 {
let next = (s.scroll_offset + step).clamp(0.0, max_s);
if (next - s.scroll_offset).abs() > 0.1 {
s.scroll_offset = next;
changed = true;
}
}
});
if changed || event.modifiers.shift {
cx.stop_propagation();
window.refresh();
}
})
.child(base_tabs)
.child(viewport_overlay),
)
.when(can_scroll_left, |this| {
this.child(
div()
.id(left_btn_id)
.test_support()
.aria_label(ui_strings.scroll_tabs_left)
.absolute()
.top_0()
.bottom_0()
.left_0()
.w(SCROLL_BUTTON_WIDTH)
.rounded_tl(Radii::CONTROL)
.rounded_bl(Radii::CONTROL)
.flex()
.items_center()
.justify_center()
.bg(colors.surface_muted)
.hover(move |s| s.bg(scroll_btn_hover_bg))
.text_color(colors.foreground)
.cursor_pointer()
.on_click(move |_, window, cx| {
state_left.update(cx, |s, _| {
let step = (*s.viewport_width.borrow() * 0.75).max(80.0);
s.scroll_offset = (s.scroll_offset - step).max(0.0);
});
window.refresh();
})
.child(IconName::ChevronLeft),
)
})
.when(can_scroll_right, |this| {
this.child(
div()
.id(right_btn_id)
.test_support()
.aria_label(ui_strings.scroll_tabs_right)
.absolute()
.top_0()
.bottom_0()
.right_0()
.w(SCROLL_BUTTON_WIDTH)
.rounded_tr(Radii::CONTROL)
.rounded_br(Radii::CONTROL)
.flex()
.items_center()
.justify_center()
.bg(colors.surface_muted)
.hover(move |s| s.bg(scroll_btn_hover_bg))
.text_color(colors.foreground)
.cursor_pointer()
.on_click(move |_, window, cx| {
state_right.update(cx, |s, _| {
let vp = *s.viewport_width.borrow();
let max_s = (*s.content_width.borrow() - vp).max(0.0);
let step = (vp * 0.75).max(80.0);
s.scroll_offset = (s.scroll_offset + step).min(max_s);
});
window.refresh();
})
.child(IconName::ChevronRight),
)
});
let panel_elapsed = (now - snapshot.panel_enter_at_secs).max(0.0);
let enter_dur = if reduced {
motion.duration.instant
} else {
motion.duration.standard
};
let panel_opacity = if panel_elapsed < enter_dur.as_secs_f64() {
let t = (panel_elapsed / enter_dur.as_secs_f64()).clamp(0.0, 1.0) as f32;
window.request_animation_frame();
if reduced {
t
} else {
arc_motion::CubicBezier::from_spec(motion.ease.enter).sample(t)
}
} else {
1.0
};
let panel_x_start = if reduced { 0.0 } else { direction * 8.0 };
let panel_x = if reduced {
0.0
} else if panel_elapsed < 0.001 {
panel_x_start
} else {
let s = arc_motion::SpringSolver::new(
motion.spring.smooth,
f64::from(panel_x_start),
0.0,
0.0,
)
.sample(panel_elapsed);
if !s.settled {
window.request_animation_frame();
}
s.value
};
let panel_height_ref = snapshot.panel_height.clone();
let target_panel_height = *panel_height_ref.borrow();
let morphed_height = if target_panel_height > 0.0 && snapshot.prev_panel_height.is_some() {
let h = arc_transition(
(self.id.clone(), "panel-height"),
target_panel_height,
motion.duration.standard,
motion.ease.standard,
window,
cx,
);
Some(h)
} else {
None
};
let mut root = div()
.id(self.id.clone())
.relative()
.flex()
.flex_col()
.items_start()
.w_full()
.child(list_shell);
if self.force_mount {
for item in self.items {
let is_active = item.value == active;
if let Some(builder) = item.content {
let body = builder(window, cx);
root = root.child(
div()
.w_full()
.mt(Spacing::S4)
.text_size(Typography::TEXT_SM)
.text_color(colors.text_secondary)
.when(!is_active, |this| this.hidden())
.child(body),
);
}
}
} else if let Some(active_item) = self.items.into_iter().find(|i| i.value == active)
&& let Some(builder) = active_item.content
{
let body = builder(window, cx);
let h_measure = panel_height_ref.clone();
let height_probe = canvas(
move |rect, _, _| {
*h_measure.borrow_mut() = f32::from(rect.size.height);
},
|_, _, _, _| {},
)
.absolute()
.inset_0();
root = root.child(
div()
.relative()
.w_full()
.mt(Spacing::S4)
.pl(px(panel_x.max(0.0)))
.ml(px(panel_x.min(0.0)))
.when_some(morphed_height, |this, h| {
this.min_h(px(h)).overflow_hidden()
})
.opacity(panel_opacity)
.text_size(Typography::TEXT_SM)
.text_color(colors.text_secondary)
.child(height_probe)
.child(body),
);
}
let _ = Hsla::transparent_black();
let _ = bounds(point(px(0.0), px(0.0)), size(px(0.0), px(0.0)));
root
}
}
#[cfg(test)]
mod tests {
use std::{cell::Cell, rc::Rc};
use arc_motion::{CurveTrace, LayoutRegistry, LayoutSnapshot, max_curve_error_pct};
use arc_tokens::{Accent, ArcMotionTokens, ThemeMode, install_arc_theme};
use gpui_kit::{
Context, MouseButton, Render, Role, TestAppContext, bounds, div, point, px, size,
test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
};
use super::*;
struct TabsHost {
active: SharedString,
changes: Rc<Cell<usize>>,
}
impl Render for TabsHost {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let changes = self.changes.clone();
div().w(px(480.0)).p(Spacing::S4).child(
Tabs::new("settings-tabs")
.value(self.active.clone())
.on_value_change(cx.listener(move |this, next: &SharedString, _, cx| {
this.active = next.clone();
changes.set(changes.get() + 1);
cx.notify();
}))
.tab(
TabItem::new("general", "General")
.content(|_, _| div().child("General panel content")),
)
.tab(
TabItem::new("security", "Security")
.content(|_, _| div().child("Security panel content")),
)
.tab(
TabItem::new("billing", "Billing")
.disabled(true)
.content(|_, _| div().child("Billing panel content")),
),
)
}
}
#[gpui_kit::test]
fn tabs_click_keyboard_navigation_and_disabled_skip(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
});
let changes = Rc::new(Cell::new(0usize));
let (view, cx) = cx.add_window_view(|_, _| TabsHost {
active: "general".into(),
changes: changes.clone(),
});
cx.update(|window, cx| {
window.render_frame(cx);
let tabs = window.find_all_by_role(Role::Tab);
assert_eq!(tabs.len(), 3);
let general = window.find_by_label("General");
let security = window.find_by_label("Security");
let billing = window.find_by_label("Billing");
assert_eq!(general.selected(), Some(true));
assert_eq!(security.selected(), Some(false));
assert_eq!(billing.disabled(), Some(true));
let sec_pos = security.bounds().center();
window.pointer_down(sec_pos, MouseButton::Left, cx);
window.pointer_up(sec_pos, MouseButton::Left, cx);
assert_eq!(window.find_by_label("Security").selected(), Some(true));
assert_eq!(changes.get(), 1);
let bill_pos = billing.bounds().center();
window.pointer_down(bill_pos, MouseButton::Left, cx);
window.pointer_up(bill_pos, MouseButton::Left, cx);
assert_eq!(window.find_by_label("Security").selected(), Some(true));
assert_eq!(changes.get(), 1);
window.press("left", cx);
window.press("enter", cx);
assert_eq!(window.find_by_label("General").selected(), Some(true));
assert_eq!(changes.get(), 2);
});
assert_eq!(view.read_with(cx, |v, _| v.active.clone()), "general");
}
#[test]
fn tabs_shared_layout_pill_matches_morph_spring_within_5_percent() {
let spec = ArcMotionTokens::DEFAULT.spring.morph;
let mut reg = LayoutRegistry::default();
let a = LayoutSnapshot::uniform_radius(
bounds(point(px(4.0), px(4.0)), size(px(88.0), px(36.0))),
TRIGGER_RADIUS,
);
let b = LayoutSnapshot::uniform_radius(
bounds(point(px(96.0), px(4.0)), size(px(110.0), px(36.0))),
TRIGGER_RADIUS,
);
reg.sample("tabs", "selection", a, spec, 0.0, false);
let omega0 = std::f64::consts::TAU / (0.42 * 1.2);
let mut actual = CurveTrace::new("tabs", "selection_x");
let mut expected = CurveTrace::new("tabs", "selection_x");
for frame in 0..=45 {
let t_ms = frame as f64 * 16.0;
let t = t_ms / 1000.0;
let ref_x = 96.0 - (-omega0 * t).exp() * (92.0 + omega0 * 92.0 * t);
expected.push(t_ms, ref_x);
let sample = reg.sample("tabs", "selection", b, spec, t, false);
actual.push(t_ms, f64::from(f32::from(sample.bounds.origin.x)));
}
let err = max_curve_error_pct(&actual, &expected);
assert!(err < 5.0, "Tabs selection pill curve error {err:.3}% >= 5%");
assert!(
err < 1.0,
"Expected tight morph spring match, got {err:.3}%"
);
}
struct OverflowTabsHost {
active: SharedString,
}
impl Render for OverflowTabsHost {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div().w(px(480.0)).p(Spacing::S4).child(
Tabs::new("overflow-tabs")
.max_width(px(320.0))
.value(self.active.clone())
.on_value_change(cx.listener(|this, next: &SharedString, _, cx| {
this.active = next.clone();
cx.notify();
}))
.tabs([
TabItem::new("mon", "Monday"),
TabItem::new("tue", "Tuesday"),
TabItem::new("wed", "Wednesday"),
TabItem::new("thu", "Thursday"),
TabItem::new("fri", "Friday"),
TabItem::new("sat", "Saturday"),
]),
)
}
}
#[gpui_kit::test]
fn tabs_overflow_shows_scroll_controls_and_reveals_active_tab(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
arc_tokens::set_locale(arc_tokens::Locale::EnUs, cx);
});
let (_view, cx) = cx.add_window_view(|_, _| OverflowTabsHost {
active: "mon".into(),
});
cx.update(|window, cx| {
window.render_frame(cx);
window.render_frame(cx);
let right_btn = window.find_by_label("Scroll tabs right");
let right_pos = right_btn.bounds().center();
window.pointer_down(right_pos, MouseButton::Left, cx);
window.pointer_up(right_pos, MouseButton::Left, cx);
window.render_frame(cx);
let left_btn = window.find_by_label("Scroll tabs left");
assert!(left_btn.bounds().size.width > px(0.0));
});
}
}