Skip to main content

arc_ui/disclosure/
tabs.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/tabs/tabs.tsx` & `tabs.module.css`
3//!
4//! P1 Sample Component #2: `tabs`
5//!
6//! - Behavior & Accessibility: `gpui_kit::base::Tabs` + `gpui_kit::base::Tab` (`Role::TabList`,
7//!   `Role::Tab`, `aria_selected`, `aria_position_in_set`, roving focus, Left/Right/Home/End,
8//!   Enter/Space activation, disabled tab skipping).
9//! - Motion:
10//!   - Shared layout selection highlight (`layoutId = "selection"` scoped per `Tabs` instance):
11//!     glides position, width, height, and corner radius via `arc_motion::sample_shared_layout`
12//!     using `motion.spring.morph` (`visualDuration: 0.42s, bounce: 0`).
13//!   - Panel entrance: directional `x` (`direction * 8px → 0px`, `motion.spring.smooth`) +
14//!     `opacity` (`0 → 1`, `duration.standard` + `ease.enter`).
15//!   - Panel height morph: springs from outgoing panel height to incoming panel height via
16//!     `motion.spring.smooth`.
17//!   - Overflow scroll buttons (`ChevronLeft` / `ChevronRight`) + `35px` `EdgeFadeMask` quads.
18//!   - Reduced motion: selection pill snaps immediately; panel crossfades in place (`x = 0`, `120ms`).
19
20use std::{cell::RefCell, collections::HashMap, rc::Rc};
21
22use arc_motion::{
23    EdgeFadeMask, EdgeFadeSide, LayoutSnapshot, arc_spring, arc_transition, is_reduced_motion,
24    layout::layout_scope_key, motion_now, sample_shared_layout,
25};
26use arc_tokens::{
27    ActiveArcLocale as _, ActiveArcTheme as _, ControlHeights, Radii, Shadows, Spacing, Typography,
28};
29use gpui_kit::{
30    AnyElement, App, BorderStyle, Bounds, Edges, ElementId, Hsla, IntoElement, ParentElement,
31    Pixels, RenderOnce, SharedString, Styled, TestSupportExt as _, Window,
32    assets::IconName,
33    base::{Tab as BaseTab, Tabs as BaseTabs},
34    bounds, canvas, div, point,
35    prelude::*,
36    px, quad, size,
37};
38
39type ValueChangeHandler = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
40type ContentBuilder = Rc<dyn Fn(&mut Window, &mut App) -> AnyElement>;
41
42/// Trigger pill radius = `calc(var(--radius-control) - 2px)` = `6px` (shadcn TabsTrigger).
43const TRIGGER_RADIUS: Pixels = px(6.0);
44const TRIGGER_MIN_WIDTH: Pixels = px(72.0);
45const SCROLL_BUTTON_WIDTH: Pixels = px(28.0);
46const EDGE_FADE_EXTENT: Pixels = px(28.0);
47
48/// One tab trigger + panel definition inside [`Tabs`].
49pub struct TabItem {
50    pub value: SharedString,
51    pub label: SharedString,
52    pub disabled: bool,
53    pub content: Option<ContentBuilder>,
54}
55
56impl TabItem {
57    pub fn new(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
58        Self {
59            value: value.into(),
60            label: label.into(),
61            disabled: false,
62            content: None,
63        }
64    }
65
66    pub fn disabled(mut self, disabled: bool) -> Self {
67        self.disabled = disabled;
68        self
69    }
70
71    pub fn content<E: IntoElement + 'static>(
72        mut self,
73        render: impl Fn(&mut Window, &mut App) -> E + 'static,
74    ) -> Self {
75        self.content = Some(Rc::new(move |window, cx| {
76            render(window, cx).into_any_element()
77        }));
78        self
79    }
80}
81
82#[derive(Clone)]
83struct TabsInternalState {
84    uncontrolled_active: SharedString,
85    last_active: SharedString,
86    direction: f32,
87    scroll_offset: f32,
88    pending_reveal: bool,
89    panel_enter_at_secs: f64,
90    prev_panel_height: Option<f32>,
91    measured_tabs: Rc<RefCell<HashMap<SharedString, Bounds<Pixels>>>>,
92    list_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
93    viewport_width: Rc<RefCell<f32>>,
94    content_width: Rc<RefCell<f32>>,
95    panel_height: Rc<RefCell<f32>>,
96}
97
98impl TabsInternalState {
99    fn new(initial: SharedString, now: f64) -> Self {
100        Self {
101            uncontrolled_active: initial.clone(),
102            last_active: initial,
103            direction: 1.0,
104            scroll_offset: 0.0,
105            pending_reveal: false,
106            panel_enter_at_secs: now - 10.0,
107            prev_panel_height: None,
108            measured_tabs: Rc::new(RefCell::new(HashMap::new())),
109            list_bounds: Rc::new(RefCell::new(None)),
110            viewport_width: Rc::new(RefCell::new(0.0)),
111            content_width: Rc::new(RefCell::new(0.0)),
112            panel_height: Rc::new(RefCell::new(0.0)),
113        }
114    }
115}
116
117/// Compute target horizontal scroll offset to reveal a tab inside the viewport,
118/// keeping `36px` clearance away from active overflow scroll buttons (matches Arc `reveal`).
119fn compute_reveal_scroll(
120    tab_local_left: f32,
121    tab_local_right: f32,
122    current_scroll: f32,
123    viewport_width: f32,
124    content_width: f32,
125) -> Option<f32> {
126    let max_scroll = (content_width - viewport_width).max(0.0);
127    if max_scroll <= 1.0 || viewport_width <= 0.0 {
128        return None;
129    }
130    let clearance = f32::from(SCROLL_BUTTON_WIDTH) + 3.0;
131    let left_inset = if current_scroll > 1.0 { clearance } else { 4.0 };
132    let right_inset = if current_scroll < max_scroll - 1.0 {
133        clearance
134    } else {
135        4.0
136    };
137
138    if tab_local_left < current_scroll + left_inset {
139        let target = if tab_local_left <= 8.0 {
140            0.0
141        } else {
142            (tab_local_left - clearance).clamp(0.0, max_scroll)
143        };
144        if (target - current_scroll).abs() > 0.5 {
145            return Some(target);
146        }
147    } else if tab_local_right > current_scroll + viewport_width - right_inset {
148        let target = if content_width - tab_local_right <= 8.0 {
149            max_scroll
150        } else {
151            (tab_local_right - viewport_width + clearance).clamp(0.0, max_scroll)
152        };
153        if (target - current_scroll).abs() > 0.5 {
154            return Some(target);
155        }
156    }
157    None
158}
159
160/// Arc `Tabs` component with scoped FLIP shared-layout highlight pill, directional panel transitions,
161/// height morphing, and overflow scroll controls with edge-fade masks.
162#[derive(IntoElement)]
163pub struct Tabs {
164    id: ElementId,
165    value: Option<SharedString>,
166    default_value: Option<SharedString>,
167    items: Vec<TabItem>,
168    force_mount: bool,
169    max_width: Option<Pixels>,
170    on_value_change: Option<ValueChangeHandler>,
171}
172
173impl Tabs {
174    pub fn new(id: impl Into<ElementId>) -> Self {
175        Self {
176            id: id.into(),
177            value: None,
178            default_value: None,
179            items: Vec::new(),
180            force_mount: false,
181            max_width: None,
182            on_value_change: None,
183        }
184    }
185
186    /// Controlled active tab value. Omit to run uncontrolled seeded by [`Self::default_value`].
187    pub fn value(mut self, value: impl Into<SharedString>) -> Self {
188        self.value = Some(value.into());
189        self
190    }
191
192    pub fn default_value(mut self, value: impl Into<SharedString>) -> Self {
193        self.default_value = Some(value.into());
194        self
195    }
196
197    pub fn tab(mut self, item: TabItem) -> Self {
198        self.items.push(item);
199        self
200    }
201
202    pub fn tabs(mut self, items: impl IntoIterator<Item = TabItem>) -> Self {
203        self.items.extend(items);
204        self
205    }
206
207    /// Keep all tab panels mounted in layout (matches Radix `forceMount`).
208    pub fn force_mount(mut self, force_mount: bool) -> Self {
209        self.force_mount = force_mount;
210        self
211    }
212
213    /// Constrain the tab strip width to demonstrate or enable horizontal overflow scroll controls.
214    pub fn max_width(mut self, max_width: Pixels) -> Self {
215        self.max_width = Some(max_width);
216        self
217    }
218
219    pub fn on_value_change(
220        mut self,
221        handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
222    ) -> Self {
223        self.on_value_change = Some(Rc::new(handler));
224        self
225    }
226}
227
228impl RenderOnce for Tabs {
229    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
230        let theme = cx.arc_theme().clone();
231        let colors = theme.colors;
232        let motion = theme.motion;
233        let reduced = is_reduced_motion(cx);
234        let now = motion_now(cx);
235
236        let fallback_active = self
237            .default_value
238            .clone()
239            .or_else(|| {
240                self.items
241                    .iter()
242                    .find(|item| !item.disabled)
243                    .map(|item| item.value.clone())
244            })
245            .unwrap_or_default();
246
247        let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-tabs-state".into());
248        let state = window.use_keyed_state(state_id, cx, |_, _| {
249            TabsInternalState::new(fallback_active.clone(), now)
250        });
251
252        let snapshot = state.read(cx).clone();
253        let active = self
254            .value
255            .clone()
256            .unwrap_or_else(|| snapshot.uncontrolled_active.clone());
257
258        // Detect tab switch (both controlled & uncontrolled) to update direction and trigger panel entrance.
259        if snapshot.last_active != active {
260            let from_idx = self
261                .items
262                .iter()
263                .position(|i| i.value == snapshot.last_active);
264            let to_idx = self.items.iter().position(|i| i.value == active);
265            let direction = match (from_idx, to_idx) {
266                (Some(f), Some(t)) if f != t => {
267                    if t > f {
268                        1.0
269                    } else {
270                        -1.0
271                    }
272                }
273                _ => snapshot.direction,
274            };
275            let current_h = *snapshot.panel_height.borrow();
276            state.update(cx, |s, _| {
277                s.last_active = active.clone();
278                s.direction = direction;
279                s.pending_reveal = true;
280                s.panel_enter_at_secs = now;
281                if current_h > 0.0 {
282                    s.prev_panel_height = Some(current_h);
283                }
284            });
285        }
286
287        // Reveal active tab inside overflowing viewport once layout geometry is known.
288        {
289            let snap_now = state.read(cx).clone();
290            let vp_w = *snap_now.viewport_width.borrow();
291            let content_w = *snap_now.content_width.borrow();
292            if snap_now.pending_reveal
293                && vp_w > 0.0
294                && content_w > 0.0
295                && let Some(list_rect) = *snap_now.list_bounds.borrow()
296                && let Some(tab_rect) = snap_now.measured_tabs.borrow().get(&active).copied()
297            {
298                let tab_left = f32::from(tab_rect.origin.x - list_rect.origin.x);
299                let tab_right = tab_left + f32::from(tab_rect.size.width);
300                let reveal_target = compute_reveal_scroll(
301                    tab_left,
302                    tab_right,
303                    snap_now.scroll_offset,
304                    vp_w,
305                    content_w,
306                );
307                state.update(cx, |s, _| {
308                    s.pending_reveal = false;
309                    if let Some(next_scroll) = reveal_target {
310                        s.scroll_offset = next_scroll;
311                    }
312                });
313            }
314        }
315
316        let snapshot = state.read(cx).clone();
317        let direction = snapshot.direction;
318        let scope = layout_scope_key(&self.id);
319
320        // Compute overflow edges for scroll buttons and 35px gradient fade masks.
321        let vp_w = *snapshot.viewport_width.borrow();
322        let content_w = *snapshot.content_width.borrow();
323        let max_scroll = (content_w - vp_w).max(0.0);
324        let clamped_scroll = snapshot.scroll_offset.clamp(0.0, max_scroll);
325        if (clamped_scroll - snapshot.scroll_offset).abs() > 0.5 {
326            state.update(cx, |s, _| {
327                s.scroll_offset = clamped_scroll;
328            });
329        }
330        let overflow = content_w > vp_w + 1.0 && vp_w > 0.0;
331        let can_scroll_left = overflow && clamped_scroll > 1.0;
332        let can_scroll_right = overflow && clamped_scroll < max_scroll - 1.0;
333        let animated_scroll = arc_spring(
334            (self.id.clone(), "scroll-x"),
335            clamped_scroll,
336            motion.spring.smooth,
337            window,
338            cx,
339        );
340
341        let is_controlled = self.value.is_some();
342        let total_tabs = self.items.len();
343        let current_item_keys: Vec<SharedString> =
344            self.items.iter().map(|i| i.value.clone()).collect();
345
346        // Backdrop canvas: paints the FLIP shared-layout highlight pill in list-local coordinates
347        // (Arc `layoutScroll` parity: horizontal scrolling locks 1:1 without re-triggering FLIP).
348        let measured_for_pill = snapshot.measured_tabs.clone();
349        let list_bounds_ref = snapshot.list_bounds.clone();
350        let active_for_pill = active.clone();
351        let pill_scope = scope.clone();
352        let pill_bg = colors.surface;
353        let pill_border = colors.border;
354        let pill_shadows = Shadows::resting(theme.mode);
355        let morph_spec = motion.spring.morph;
356
357        let selection_backdrop = canvas(
358            move |list_rect, _, _| {
359                *list_bounds_ref.borrow_mut() = Some(list_rect);
360            },
361            move |list_rect, _, window, cx| {
362                let target_rect = measured_for_pill.borrow().get(&active_for_pill).copied();
363                let Some(rect) = target_rect else {
364                    // First layout frame: bounds will be populated right after triggers prepaint.
365                    window.request_animation_frame();
366                    return;
367                };
368                let local_rect = bounds(rect.origin - list_rect.origin, rect.size);
369                let target = LayoutSnapshot::uniform_radius(local_rect, TRIGGER_RADIUS);
370                let flip = sample_shared_layout(
371                    pill_scope.clone(),
372                    "selection",
373                    target,
374                    Some(morph_spec),
375                    window,
376                    cx,
377                );
378                let paint_bounds = bounds(list_rect.origin + flip.bounds.origin, flip.bounds.size);
379                window.paint_drop_shadows(paint_bounds, flip.corner_radii, &pill_shadows);
380                window.paint_quad(quad(
381                    paint_bounds,
382                    flip.corner_radii,
383                    pill_bg,
384                    Edges::all(px(1.0)),
385                    pill_border,
386                    BorderStyle::Solid,
387                ));
388            },
389        )
390        .absolute()
391        .inset_0();
392
393        // Build ARIA-compliant tab triggers using `gpui_kit::base::Tabs` + `BaseTab`.
394        let mut base_tabs = BaseTabs::new(ElementId::NamedChild(
395            self.id.clone().into(),
396            "tablist".into(),
397        ))
398        .relative()
399        .flex()
400        .flex_row()
401        .items_center()
402        .gap(Spacing::S1)
403        .p(Spacing::S1)
404        .ml(px(-animated_scroll))
405        .child(selection_backdrop);
406
407        for (index, item) in self.items.iter().enumerate() {
408            let item_value = item.value.clone();
409            let selected = active == item.value;
410            let disabled = item.disabled;
411            let tab_id = ElementId::NamedChild(
412                self.id.clone().into(),
413                SharedString::from(format!("tab-{}", item.value)),
414            );
415
416            let state_for_click = state.clone();
417            let on_value_change = self.on_value_change.clone();
418            let value_for_click = item_value.clone();
419            let measured_for_tab = snapshot.measured_tabs.clone();
420            let value_for_measure = item_value.clone();
421
422            let label_color = if selected {
423                colors.accent_strong
424            } else {
425                colors.text_muted
426            };
427
428            let measure_canvas = canvas(
429                move |tab_rect, _, _| {
430                    measured_for_tab
431                        .borrow_mut()
432                        .insert(value_for_measure.clone(), tab_rect);
433                },
434                |_, _, _, _| {},
435            )
436            .absolute()
437            .inset_0();
438
439            let tab_el = BaseTab::new(tab_id)
440                .selected(selected)
441                .disabled(disabled)
442                .accessibility_label(item.label.clone())
443                .set_position(index + 1, total_tabs)
444                .on_click(move |_, window, cx| {
445                    if !is_controlled {
446                        state_for_click.update(cx, |s, _| {
447                            s.uncontrolled_active = value_for_click.clone();
448                        });
449                    }
450                    if let Some(handler) = &on_value_change {
451                        handler(&value_for_click, window, cx);
452                    }
453                    window.refresh();
454                })
455                .relative()
456                .flex_none()
457                .min_w(TRIGGER_MIN_WIDTH)
458                .min_h(ControlHeights::SM)
459                .px(Spacing::S3)
460                .rounded(TRIGGER_RADIUS)
461                .text_size(Typography::TEXT_SM)
462                .text_color(label_color)
463                .when(!disabled && !selected, |this| {
464                    let fg = colors.foreground;
465                    this.hover(move |style| style.text_color(fg))
466                })
467                .when(disabled, |this| this.opacity(0.5))
468                .when(!disabled, |this| this.cursor_pointer())
469                .child(measure_canvas)
470                .child(item.label.clone());
471
472            base_tabs = base_tabs.child(tab_el);
473        }
474
475        // Viewport overlay: runs AFTER `base_tabs` and every tab's `measure_canvas` prepaint,
476        // so we can measure the true intrinsic tab strip span (`content_width`) without being
477        // clamped by Taffy's viewport box, and paint 35px gradient edge fades beside the buttons.
478        let vp_width_ref = snapshot.viewport_width.clone();
479        let content_width_for_vp = snapshot.content_width.clone();
480        let measured_for_vp = snapshot.measured_tabs.clone();
481        let list_bounds_for_vp = snapshot.list_bounds.clone();
482        let surface_muted = colors.surface_muted;
483        let viewport_overlay = canvas(
484            move |vp_rect, window, _| {
485                let next_vp = f32::from(vp_rect.size.width);
486                let measured = measured_for_vp.borrow();
487                let mut min_left = f32::INFINITY;
488                let mut max_right = f32::NEG_INFINITY;
489                for key in &current_item_keys {
490                    if let Some(tab_rect) = measured.get(key) {
491                        min_left = min_left.min(f32::from(tab_rect.origin.x));
492                        max_right =
493                            max_right.max(f32::from(tab_rect.origin.x + tab_rect.size.width));
494                    }
495                }
496                drop(measured);
497
498                let tabs_span =
499                    if min_left.is_finite() && max_right.is_finite() && max_right > min_left {
500                        (max_right - min_left) + f32::from(Spacing::S1) * 2.0
501                    } else {
502                        0.0
503                    };
504                let list_w = list_bounds_for_vp
505                    .borrow()
506                    .map_or(0.0, |r| f32::from(r.size.width));
507                let next_content = tabs_span.max(list_w);
508
509                let prev_vp = *vp_width_ref.borrow();
510                let prev_content = *content_width_for_vp.borrow();
511                *vp_width_ref.borrow_mut() = next_vp;
512                *content_width_for_vp.borrow_mut() = next_content;
513                if (next_vp - prev_vp).abs() > 0.5 || (next_content - prev_content).abs() > 0.5 {
514                    window.request_animation_frame();
515                }
516            },
517            move |vp_rect, _, window, _| {
518                let avail_w =
519                    (f32::from(vp_rect.size.width) - f32::from(SCROLL_BUTTON_WIDTH)).max(0.0);
520                if can_scroll_left && avail_w > 0.0 {
521                    let left_rect = bounds(
522                        point(vp_rect.origin.x + SCROLL_BUTTON_WIDTH, vp_rect.origin.y),
523                        size(px(avail_w), vp_rect.size.height),
524                    );
525                    EdgeFadeMask::new(EdgeFadeSide::Left, EDGE_FADE_EXTENT, surface_muted)
526                        .paint(left_rect, window);
527                }
528                if can_scroll_right && avail_w > 0.0 {
529                    let right_rect = bounds(vp_rect.origin, size(px(avail_w), vp_rect.size.height));
530                    EdgeFadeMask::new(EdgeFadeSide::Right, EDGE_FADE_EXTENT, surface_muted)
531                        .paint(right_rect, window);
532                }
533            },
534        )
535        .absolute()
536        .inset_0();
537
538        let state_wheel = state.clone();
539        let state_left = state.clone();
540        let state_right = state.clone();
541        let viewport_id = ElementId::NamedChild(self.id.clone().into(), "viewport".into());
542        let left_btn_id = ElementId::NamedChild(self.id.clone().into(), "scroll-left".into());
543        let right_btn_id = ElementId::NamedChild(self.id.clone().into(), "scroll-right".into());
544        let scroll_btn_hover_bg = colors.surface;
545
546        let ui_strings = cx.arc_locale().ui_strings();
547        let list_shell = div()
548            .relative()
549            .self_start()
550            .flex()
551            .flex_row()
552            .items_center()
553            .max_w_full()
554            .when_some(self.max_width, |this, mw| this.max_w(mw))
555            .overflow_hidden()
556            .border_1()
557            .border_color(colors.border)
558            .rounded(Radii::CONTROL)
559            .bg(colors.surface_muted)
560            .child(
561                div()
562                    .id(viewport_id)
563                    .relative()
564                    .min_w_0()
565                    .max_w_full()
566                    .overflow_hidden()
567                    .rounded(Radii::CONTROL)
568                    .on_scroll(move |event, window, cx| {
569                        let delta = event.delta.pixel_delta(px(24.0));
570                        let dx = f32::from(delta.x);
571                        let dy = f32::from(delta.y);
572                        let step = if dx.abs() > 0.5 {
573                            -dx
574                        } else if event.modifiers.shift {
575                            -dy
576                        } else {
577                            0.0
578                        };
579                        if step.abs() <= 0.5 {
580                            return;
581                        }
582                        let mut changed = false;
583                        state_wheel.update(cx, |s, _| {
584                            let vp = *s.viewport_width.borrow();
585                            let max_s = (*s.content_width.borrow() - vp).max(0.0);
586                            if max_s > 1.0 {
587                                let next = (s.scroll_offset + step).clamp(0.0, max_s);
588                                if (next - s.scroll_offset).abs() > 0.1 {
589                                    s.scroll_offset = next;
590                                    changed = true;
591                                }
592                            }
593                        });
594                        if changed || event.modifiers.shift {
595                            cx.stop_propagation();
596                            window.refresh();
597                        }
598                    })
599                    .child(base_tabs)
600                    .child(viewport_overlay),
601            )
602            .when(can_scroll_left, |this| {
603                this.child(
604                    div()
605                        .id(left_btn_id)
606                        .test_support()
607                        .aria_label(ui_strings.scroll_tabs_left)
608                        .absolute()
609                        .top_0()
610                        .bottom_0()
611                        .left_0()
612                        .w(SCROLL_BUTTON_WIDTH)
613                        .rounded_tl(Radii::CONTROL)
614                        .rounded_bl(Radii::CONTROL)
615                        .flex()
616                        .items_center()
617                        .justify_center()
618                        .bg(colors.surface_muted)
619                        .hover(move |s| s.bg(scroll_btn_hover_bg))
620                        .text_color(colors.foreground)
621                        .cursor_pointer()
622                        .on_click(move |_, window, cx| {
623                            state_left.update(cx, |s, _| {
624                                let step = (*s.viewport_width.borrow() * 0.75).max(80.0);
625                                s.scroll_offset = (s.scroll_offset - step).max(0.0);
626                            });
627                            window.refresh();
628                        })
629                        .child(IconName::ChevronLeft),
630                )
631            })
632            .when(can_scroll_right, |this| {
633                this.child(
634                    div()
635                        .id(right_btn_id)
636                        .test_support()
637                        .aria_label(ui_strings.scroll_tabs_right)
638                        .absolute()
639                        .top_0()
640                        .bottom_0()
641                        .right_0()
642                        .w(SCROLL_BUTTON_WIDTH)
643                        .rounded_tr(Radii::CONTROL)
644                        .rounded_br(Radii::CONTROL)
645                        .flex()
646                        .items_center()
647                        .justify_center()
648                        .bg(colors.surface_muted)
649                        .hover(move |s| s.bg(scroll_btn_hover_bg))
650                        .text_color(colors.foreground)
651                        .cursor_pointer()
652                        .on_click(move |_, window, cx| {
653                            state_right.update(cx, |s, _| {
654                                let vp = *s.viewport_width.borrow();
655                                let max_s = (*s.content_width.borrow() - vp).max(0.0);
656                                let step = (vp * 0.75).max(80.0);
657                                s.scroll_offset = (s.scroll_offset + step).min(max_s);
658                            });
659                            window.refresh();
660                        })
661                        .child(IconName::ChevronRight),
662                )
663            });
664
665        // Directional panel motion (`x: direction * 8 -> 0`, `opacity: 0 -> 1`, height morph).
666        let panel_elapsed = (now - snapshot.panel_enter_at_secs).max(0.0);
667        let enter_dur = if reduced {
668            motion.duration.instant
669        } else {
670            motion.duration.standard
671        };
672        let panel_opacity = if panel_elapsed < enter_dur.as_secs_f64() {
673            let t = (panel_elapsed / enter_dur.as_secs_f64()).clamp(0.0, 1.0) as f32;
674            window.request_animation_frame();
675            if reduced {
676                t
677            } else {
678                arc_motion::CubicBezier::from_spec(motion.ease.enter).sample(t)
679            }
680        } else {
681            1.0
682        };
683
684        let panel_x_start = if reduced { 0.0 } else { direction * 8.0 };
685        let panel_x = if reduced {
686            0.0
687        } else if panel_elapsed < 0.001 {
688            panel_x_start
689        } else {
690            let s = arc_motion::SpringSolver::new(
691                motion.spring.smooth,
692                f64::from(panel_x_start),
693                0.0,
694                0.0,
695            )
696            .sample(panel_elapsed);
697            if !s.settled {
698                window.request_animation_frame();
699            }
700            s.value
701        };
702
703        // Measure current panel height so subsequent switches can smoothly morph height.
704        let panel_height_ref = snapshot.panel_height.clone();
705        let target_panel_height = *panel_height_ref.borrow();
706        let morphed_height = if target_panel_height > 0.0 && snapshot.prev_panel_height.is_some() {
707            let h = arc_transition(
708                (self.id.clone(), "panel-height"),
709                target_panel_height,
710                motion.duration.standard,
711                motion.ease.standard,
712                window,
713                cx,
714            );
715            Some(h)
716        } else {
717            None
718        };
719
720        let mut root = div()
721            .id(self.id.clone())
722            .relative()
723            .flex()
724            .flex_col()
725            .items_start()
726            .w_full()
727            .child(list_shell);
728
729        if self.force_mount {
730            for item in self.items {
731                let is_active = item.value == active;
732                if let Some(builder) = item.content {
733                    let body = builder(window, cx);
734                    root = root.child(
735                        div()
736                            .w_full()
737                            .mt(Spacing::S4)
738                            .text_size(Typography::TEXT_SM)
739                            .text_color(colors.text_secondary)
740                            .when(!is_active, |this| this.hidden())
741                            .child(body),
742                    );
743                }
744            }
745        } else if let Some(active_item) = self.items.into_iter().find(|i| i.value == active)
746            && let Some(builder) = active_item.content
747        {
748            let body = builder(window, cx);
749            let h_measure = panel_height_ref.clone();
750            let height_probe = canvas(
751                move |rect, _, _| {
752                    *h_measure.borrow_mut() = f32::from(rect.size.height);
753                },
754                |_, _, _, _| {},
755            )
756            .absolute()
757            .inset_0();
758
759            root = root.child(
760                div()
761                    .relative()
762                    .w_full()
763                    .mt(Spacing::S4)
764                    .pl(px(panel_x.max(0.0)))
765                    .ml(px(panel_x.min(0.0)))
766                    .when_some(morphed_height, |this, h| {
767                        this.min_h(px(h)).overflow_hidden()
768                    })
769                    .opacity(panel_opacity)
770                    .text_size(Typography::TEXT_SM)
771                    .text_color(colors.text_secondary)
772                    .child(height_probe)
773                    .child(body),
774            );
775        }
776
777        let _ = Hsla::transparent_black();
778        let _ = bounds(point(px(0.0), px(0.0)), size(px(0.0), px(0.0)));
779        root
780    }
781}
782
783#[cfg(test)]
784mod tests {
785    use std::{cell::Cell, rc::Rc};
786
787    use arc_motion::{CurveTrace, LayoutRegistry, LayoutSnapshot, max_curve_error_pct};
788    use arc_tokens::{Accent, ArcMotionTokens, ThemeMode, install_arc_theme};
789    use gpui_kit::{
790        Context, MouseButton, Render, Role, TestAppContext, bounds, div, point, px, size,
791        test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
792    };
793
794    use super::*;
795
796    struct TabsHost {
797        active: SharedString,
798        changes: Rc<Cell<usize>>,
799    }
800
801    impl Render for TabsHost {
802        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
803            let changes = self.changes.clone();
804            div().w(px(480.0)).p(Spacing::S4).child(
805                Tabs::new("settings-tabs")
806                    .value(self.active.clone())
807                    .on_value_change(cx.listener(move |this, next: &SharedString, _, cx| {
808                        this.active = next.clone();
809                        changes.set(changes.get() + 1);
810                        cx.notify();
811                    }))
812                    .tab(
813                        TabItem::new("general", "General")
814                            .content(|_, _| div().child("General panel content")),
815                    )
816                    .tab(
817                        TabItem::new("security", "Security")
818                            .content(|_, _| div().child("Security panel content")),
819                    )
820                    .tab(
821                        TabItem::new("billing", "Billing")
822                            .disabled(true)
823                            .content(|_, _| div().child("Billing panel content")),
824                    ),
825            )
826        }
827    }
828
829    #[gpui_kit::test]
830    fn tabs_click_keyboard_navigation_and_disabled_skip(cx: &mut TestAppContext) {
831        cx.update(|cx| {
832            gpui_kit::init(cx);
833            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
834        });
835        let changes = Rc::new(Cell::new(0usize));
836        let (view, cx) = cx.add_window_view(|_, _| TabsHost {
837            active: "general".into(),
838            changes: changes.clone(),
839        });
840
841        cx.update(|window, cx| {
842            window.render_frame(cx);
843            let tabs = window.find_all_by_role(Role::Tab);
844            assert_eq!(tabs.len(), 3);
845
846            let general = window.find_by_label("General");
847            let security = window.find_by_label("Security");
848            let billing = window.find_by_label("Billing");
849            assert_eq!(general.selected(), Some(true));
850            assert_eq!(security.selected(), Some(false));
851            assert_eq!(billing.disabled(), Some(true));
852
853            // Click Security tab
854            let sec_pos = security.bounds().center();
855            window.pointer_down(sec_pos, MouseButton::Left, cx);
856            window.pointer_up(sec_pos, MouseButton::Left, cx);
857            assert_eq!(window.find_by_label("Security").selected(), Some(true));
858            assert_eq!(changes.get(), 1);
859
860            // Disabled Billing tab ignores click
861            let bill_pos = billing.bounds().center();
862            window.pointer_down(bill_pos, MouseButton::Left, cx);
863            window.pointer_up(bill_pos, MouseButton::Left, cx);
864            assert_eq!(window.find_by_label("Security").selected(), Some(true));
865            assert_eq!(changes.get(), 1);
866
867            // ArrowLeft moves focus back to General; Enter activates it
868            window.press("left", cx);
869            window.press("enter", cx);
870            assert_eq!(window.find_by_label("General").selected(), Some(true));
871            assert_eq!(changes.get(), 2);
872        });
873
874        assert_eq!(view.read_with(cx, |v, _| v.active.clone()), "general");
875    }
876
877    #[test]
878    fn tabs_shared_layout_pill_matches_morph_spring_within_5_percent() {
879        let spec = ArcMotionTokens::DEFAULT.spring.morph;
880        let mut reg = LayoutRegistry::default();
881        let a = LayoutSnapshot::uniform_radius(
882            bounds(point(px(4.0), px(4.0)), size(px(88.0), px(36.0))),
883            TRIGGER_RADIUS,
884        );
885        let b = LayoutSnapshot::uniform_radius(
886            bounds(point(px(96.0), px(4.0)), size(px(110.0), px(36.0))),
887            TRIGGER_RADIUS,
888        );
889        reg.sample("tabs", "selection", a, spec, 0.0, false);
890
891        let omega0 = std::f64::consts::TAU / (0.42 * 1.2);
892        let mut actual = CurveTrace::new("tabs", "selection_x");
893        let mut expected = CurveTrace::new("tabs", "selection_x");
894        for frame in 0..=45 {
895            let t_ms = frame as f64 * 16.0;
896            let t = t_ms / 1000.0;
897            let ref_x = 96.0 - (-omega0 * t).exp() * (92.0 + omega0 * 92.0 * t);
898            expected.push(t_ms, ref_x);
899            let sample = reg.sample("tabs", "selection", b, spec, t, false);
900            actual.push(t_ms, f64::from(f32::from(sample.bounds.origin.x)));
901        }
902        let err = max_curve_error_pct(&actual, &expected);
903        assert!(err < 5.0, "Tabs selection pill curve error {err:.3}% >= 5%");
904        assert!(
905            err < 1.0,
906            "Expected tight morph spring match, got {err:.3}%"
907        );
908    }
909
910    struct OverflowTabsHost {
911        active: SharedString,
912    }
913
914    impl Render for OverflowTabsHost {
915        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
916            div().w(px(480.0)).p(Spacing::S4).child(
917                Tabs::new("overflow-tabs")
918                    .max_width(px(320.0))
919                    .value(self.active.clone())
920                    .on_value_change(cx.listener(|this, next: &SharedString, _, cx| {
921                        this.active = next.clone();
922                        cx.notify();
923                    }))
924                    .tabs([
925                        TabItem::new("mon", "Monday"),
926                        TabItem::new("tue", "Tuesday"),
927                        TabItem::new("wed", "Wednesday"),
928                        TabItem::new("thu", "Thursday"),
929                        TabItem::new("fri", "Friday"),
930                        TabItem::new("sat", "Saturday"),
931                    ]),
932            )
933        }
934    }
935
936    #[gpui_kit::test]
937    fn tabs_overflow_shows_scroll_controls_and_reveals_active_tab(cx: &mut TestAppContext) {
938        cx.update(|cx| {
939            gpui_kit::init(cx);
940            install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
941            arc_tokens::set_locale(arc_tokens::Locale::EnUs, cx);
942        });
943        let (_view, cx) = cx.add_window_view(|_, _| OverflowTabsHost {
944            active: "mon".into(),
945        });
946
947        cx.update(|window, cx| {
948            // Frame 1 measures tab widths; frame 2 surfaces overflow scroll controls.
949            window.render_frame(cx);
950            window.render_frame(cx);
951
952            let right_btn = window.find_by_label("Scroll tabs right");
953            let right_pos = right_btn.bounds().center();
954            window.pointer_down(right_pos, MouseButton::Left, cx);
955            window.pointer_up(right_pos, MouseButton::Left, cx);
956            window.render_frame(cx);
957
958            // After scrolling right, the left scroll button must become available.
959            let left_btn = window.find_by_label("Scroll tabs left");
960            assert!(left_btn.bounds().size.width > px(0.0));
961        });
962    }
963}