arc-ui 0.4.0

Physics-first native Rust desktop UI component library & charts for GPUI (120+ interactive components ported from Arc).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/tabs/tabs.tsx` & `tabs.module.css`
//!
//! P1 Sample Component #2: `tabs`
//!
//! - Behavior & Accessibility: `gpui_kit::base::Tabs` + `gpui_kit::base::Tab` (`Role::TabList`,
//!   `Role::Tab`, `aria_selected`, `aria_position_in_set`, roving focus, Left/Right/Home/End,
//!   Enter/Space activation, disabled tab skipping).
//! - Motion:
//!   - Shared layout selection highlight (`layoutId = "selection"` scoped per `Tabs` instance):
//!     glides position, width, height, and corner radius via `arc_motion::sample_shared_layout`
//!     using `motion.spring.morph` (`visualDuration: 0.42s, bounce: 0`).
//!   - Panel entrance: directional `x` (`direction * 8px → 0px`, `motion.spring.smooth`) +
//!     `opacity` (`0 → 1`, `duration.standard` + `ease.enter`).
//!   - Panel height morph: springs from outgoing panel height to incoming panel height via
//!     `motion.spring.smooth`.
//!   - Overflow scroll buttons (`ChevronLeft` / `ChevronRight`) + `35px` `EdgeFadeMask` quads.
//!   - Reduced motion: selection pill snaps immediately; panel crossfades in place (`x = 0`, `120ms`).

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>;

/// Trigger pill radius = `calc(var(--radius-control) - 2px)` = `6px` (shadcn TabsTrigger).
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);

/// One tab trigger + panel definition inside [`Tabs`].
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)),
        }
    }
}

/// Compute target horizontal scroll offset to reveal a tab inside the viewport,
/// keeping `36px` clearance away from active overflow scroll buttons (matches Arc `reveal`).
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
}

/// Arc `Tabs` component with scoped FLIP shared-layout highlight pill, directional panel transitions,
/// height morphing, and overflow scroll controls with edge-fade masks.
#[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,
        }
    }

    /// Controlled active tab value. Omit to run uncontrolled seeded by [`Self::default_value`].
    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
    }

    /// Keep all tab panels mounted in layout (matches Radix `forceMount`).
    pub fn force_mount(mut self, force_mount: bool) -> Self {
        self.force_mount = force_mount;
        self
    }

    /// Constrain the tab strip width to demonstrate or enable horizontal overflow scroll controls.
    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());

        // Detect tab switch (both controlled & uncontrolled) to update direction and trigger panel entrance.
        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);
                }
            });
        }

        // Reveal active tab inside overflowing viewport once layout geometry is known.
        {
            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);

        // Compute overflow edges for scroll buttons and 35px gradient fade masks.
        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();

        // Backdrop canvas: paints the FLIP shared-layout highlight pill in list-local coordinates
        // (Arc `layoutScroll` parity: horizontal scrolling locks 1:1 without re-triggering FLIP).
        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 {
                    // First layout frame: bounds will be populated right after triggers prepaint.
                    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();

        // Build ARIA-compliant tab triggers using `gpui_kit::base::Tabs` + `BaseTab`.
        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);
        }

        // Viewport overlay: runs AFTER `base_tabs` and every tab's `measure_canvas` prepaint,
        // so we can measure the true intrinsic tab strip span (`content_width`) without being
        // clamped by Taffy's viewport box, and paint 35px gradient edge fades beside the buttons.
        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 &current_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),
                )
            });

        // Directional panel motion (`x: direction * 8 -> 0`, `opacity: 0 -> 1`, height morph).
        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
        };

        // Measure current panel height so subsequent switches can smoothly morph height.
        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));

            // Click Security tab
            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);

            // Disabled Billing tab ignores click
            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);

            // ArrowLeft moves focus back to General; Enter activates it
            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| {
            // Frame 1 measures tab widths; frame 2 surfaces overflow scroll controls.
            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);

            // After scrolling right, the left scroll button must become available.
            let left_btn = window.find_by_label("Scroll tabs left");
            assert!(left_btn.bounds().size.width > px(0.0));
        });
    }
}