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
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/scroll-area/scroll-area.tsx` & `.module.css`
//!
//! P3 Component #13: `scroll-area`
//!
//! - Scroll container (`Vertical | Horizontal | Both`) with proportional edge fade overlays
//!   (`fade_length = min(fade, scroll_distance)`, default `fade = 28px`) that grow in from `0px`
//!   over the first pixels of scroll and vanish cleanly at each boundary.
//! - Thin overlay scrollbar tracks (`11px` hit area, `5px` resting pill thumb thickening to `7px`
//!   on track hover or thumb drag) with minimum thumb length `MIN_THUMB = 28px`.
//! - Visibility modes:
//!   - `ScrollbarsVisibility::Auto`: appears on scroll, hover, or drag and lingers for
//!     `hide_delay_secs` (default `0.90s`) before fading out over `duration.considered (320ms)`.
//!   - `ScrollbarsVisibility::Always`: stays visible whenever content overflows.
//! - Supports pointer thumb dragging (`1:1` track-to-scroll ratio), track click paging (`90%` of
//!   viewport extent), wheel scrolling (including vertical-wheel-to-horizontal translation when
//!   `wheel_to_horizontal = true`), and keyboard navigation (`ArrowUp`/`ArrowDown`/`ArrowLeft`/
//!   `ArrowRight`, `PageUp`/`PageDown`, `Home`/`End`).

use std::{cell::RefCell, rc::Rc};

use arc_motion::{arc_spring, is_reduced_motion, motion_now};
use arc_tokens::{ActiveArcTheme as _, Radii};
use gpui_kit::{
    AnyElement, App, Bounds, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
    MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement, Pixels, RenderOnce, Role,
    ScrollDelta, ScrollEvent, SharedString, Styled, TestSupportExt as _, Window, canvas, div,
    linear_color_stop, linear_gradient, prelude::*, px,
};

/// Minimum scrollbar thumb length in `px` (`28px`).
pub const SCROLL_AREA_MIN_THUMB: f32 = 28.0;
/// Default edge fade length in `px` (`28px`).
pub const SCROLL_AREA_DEFAULT_FADE: f32 = 28.0;
/// Default linger delay before auto-hiding scrollbars after scrolling stops (`0.90s`).
pub const SCROLL_AREA_DEFAULT_HIDE_DELAY_SECS: f64 = 0.90;

/// Scroll axes enabled on [`ScrollArea`].
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum ScrollAreaOrientation {
    #[default]
    Vertical,
    Horizontal,
    Both,
}

/// Overlay scrollbar visibility policy for [`ScrollArea`].
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum ScrollbarsVisibility {
    /// Shows scrollbars while scrolling, dragging, or hovering, then fades away after `hide_delay`.
    #[default]
    Auto,
    /// Keeps scrollbars visible whenever content overflows.
    Always,
}

/// Which edges currently have content extending beyond them.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct ScrollAreaEdges {
    pub top: bool,
    pub bottom: bool,
    pub left: bool,
    pub right: bool,
}

/// Computes the track end inset (`px`) needed so an overlay scrollbar sitting `3px` from the
/// side edge never pokes outside a container with corner radius `corner_radius_px`.
pub fn scroll_area_track_inset(corner_radius_px: f32) -> f32 {
    let r = corner_radius_px.max(0.0);
    if r <= 3.0 { 3.0 } else { r.ceil().max(6.0) }
}

/// Computes `(thumb_size, thumb_offset)` along a track of `track_len` given `scroll`,
/// `client_len`, and `content_len`. Returns `None` when content does not overflow.
pub fn scroll_area_thumb_metrics(
    scroll: f32,
    client_len: f32,
    content_len: f32,
    track_len: f32,
) -> Option<(f32, f32)> {
    let max_scroll = (content_len - client_len).max(0.0);
    if max_scroll <= 0.5 || track_len <= 1.0 || content_len <= 1.0 {
        return None;
    }
    let size = (track_len * (client_len / content_len))
        .max(SCROLL_AREA_MIN_THUMB)
        .min(track_len);
    let ratio = (scroll.clamp(0.0, max_scroll)) / max_scroll;
    let offset = (track_len - size) * ratio;
    Some((size, offset))
}

/// Computes proportional edge fade lengths `(start_fade_px, end_fade_px)` along one axis given
/// `scroll`, `max_scroll`, and configured `fade_cap`.
///
/// Each fade is as long as the content hidden past that edge, clamped to `fade_cap`, so it grows
/// in smoothly over the first `fade_cap` pixels of scroll.
pub fn scroll_area_edge_fades(scroll: f32, max_scroll: f32, fade_cap: f32) -> (f32, f32) {
    if fade_cap <= 0.0 || max_scroll <= 0.5 {
        return (0.0, 0.0);
    }
    let clamped = scroll.clamp(0.0, max_scroll);
    let start = clamped.min(fade_cap);
    let end = (max_scroll - clamped).max(0.0).min(fade_cap);
    (start, end)
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum DragAxis {
    Y,
    X,
}

type EdgeCallback = Rc<dyn Fn(&ScrollAreaEdges, &mut Window, &mut App)>;

#[derive(Clone)]
struct ScrollAreaInternal {
    scroll_top: f32,
    scroll_left: f32,
    last_scroll_at: f64,
    root_hovered: bool,
    track_y_hovered: bool,
    track_x_hovered: bool,
    dragging: Option<DragAxis>,
    drag_start_coord: f32,
    drag_start_scroll: f32,
    drag_ratio: f32,
    last_edges: ScrollAreaEdges,
    viewport_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
    content_size: Rc<RefCell<(f32, f32)>>,
    focus_handle: FocusHandle,
}

impl ScrollAreaInternal {
    fn new(now: f64, focus_handle: FocusHandle) -> Self {
        Self {
            scroll_top: 0.0,
            scroll_left: 0.0,
            last_scroll_at: now - 10.0,
            root_hovered: false,
            track_y_hovered: false,
            track_x_hovered: false,
            dragging: None,
            drag_start_coord: 0.0,
            drag_start_scroll: 0.0,
            drag_ratio: 1.0,
            last_edges: ScrollAreaEdges::default(),
            viewport_bounds: Rc::new(RefCell::new(None)),
            content_size: Rc::new(RefCell::new((320.0, 480.0))),
            focus_handle,
        }
    }
}

/// Arc `ScrollArea` — custom scroll container with proportional edge fades, auto-lingering thin
/// overlay scrollbars that thicken on hover/drag, and wheel-to-horizontal translation.
#[derive(IntoElement)]
pub struct ScrollArea {
    id: ElementId,
    orientation: ScrollAreaOrientation,
    fade: f32,
    corner_radius: f32,
    scrollbars: ScrollbarsVisibility,
    hide_delay_secs: f64,
    max_height: Option<f32>,
    max_width: Option<f32>,
    content_width: Option<f32>,
    content_height: Option<f32>,
    wheel_to_horizontal: bool,
    label: Option<SharedString>,
    surface_color: Option<Hsla>,
    on_edge_change: Option<EdgeCallback>,
    body: Option<AnyElement>,
}

impl ScrollArea {
    pub fn new(id: impl Into<ElementId>, content: impl IntoElement) -> Self {
        Self {
            id: id.into(),
            orientation: ScrollAreaOrientation::Vertical,
            fade: SCROLL_AREA_DEFAULT_FADE,
            corner_radius: f32::from(Radii::CONTROL),
            scrollbars: ScrollbarsVisibility::Auto,
            hide_delay_secs: SCROLL_AREA_DEFAULT_HIDE_DELAY_SECS,
            max_height: None,
            max_width: None,
            content_width: None,
            content_height: None,
            wheel_to_horizontal: true,
            label: None,
            surface_color: None,
            on_edge_change: None,
            body: Some(content.into_any_element()),
        }
    }

    pub fn orientation(mut self, orientation: ScrollAreaOrientation) -> Self {
        self.orientation = orientation;
        self
    }

    /// Corner radius of the surrounding container (`px`), used to inset overlay scrollbar tracks so
    /// their ends never protrude past rounded corners.
    pub fn corner_radius(mut self, radius: impl Into<Pixels>) -> Self {
        self.corner_radius = f32::from(radius.into()).max(0.0);
        self
    }

    /// Edge fade length in `px` (`0.0` disables edge fades).
    pub fn fade(mut self, fade_px: f32) -> Self {
        self.fade = fade_px.max(0.0);
        self
    }

    pub fn scrollbars(mut self, scrollbars: ScrollbarsVisibility) -> Self {
        self.scrollbars = scrollbars;
        self
    }

    /// How long scrollbars linger after scrolling stops, in milliseconds (default `900`).
    pub fn hide_delay_ms(mut self, ms: u64) -> Self {
        self.hide_delay_secs = (ms as f64) / 1000.0;
        self
    }

    pub fn max_height(mut self, max_height_px: f32) -> Self {
        self.max_height = Some(max_height_px.max(60.0));
        self
    }

    pub fn max_width(mut self, max_width_px: f32) -> Self {
        self.max_width = Some(max_width_px.max(120.0));
        self
    }

    /// Optional explicit content dimensions `(width, height)` for horizontal or 2D canvases.
    pub fn content_size(mut self, width: Option<f32>, height: Option<f32>) -> Self {
        self.content_width = width;
        self.content_height = height;
        self
    }

    pub fn wheel_to_horizontal(mut self, enabled: bool) -> Self {
        self.wheel_to_horizontal = enabled;
        self
    }

    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
        self.label = Some(label.into());
        self
    }

    pub fn surface_color(mut self, color: Hsla) -> Self {
        self.surface_color = Some(color);
        self
    }

    pub fn on_edge_change(
        mut self,
        handler: impl Fn(&ScrollAreaEdges, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_edge_change = Some(Rc::new(handler));
        self
    }
}

impl RenderOnce for ScrollArea {
    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 state_id =
            ElementId::NamedChild(self.id.clone().into(), "__arc-scroll-area-state".into());
        let internal = window.use_keyed_state(state_id, cx, |_, cx| {
            ScrollAreaInternal::new(now, cx.focus_handle())
        });

        let snap = internal.read(cx).clone();
        let vertical = self.orientation != ScrollAreaOrientation::Horizontal;
        let horizontal = self.orientation != ScrollAreaOrientation::Vertical;

        let vp_rect = *snap.viewport_bounds.borrow();
        let client_w = vp_rect
            .map(|b| f32::from(b.size.width))
            .or(self.max_width)
            .unwrap_or(480.0)
            .max(60.0);
        let client_h = vp_rect
            .map(|b| f32::from(b.size.height))
            .or(self.max_height)
            .unwrap_or(240.0)
            .max(60.0);

        let (measured_w, measured_h) = *snap.content_size.borrow();
        let content_w = self.content_width.unwrap_or(measured_w).max(client_w);
        let content_h = self.content_height.unwrap_or(measured_h).max(client_h);

        let max_y = if vertical {
            (content_h - client_h).max(0.0)
        } else {
            0.0
        };
        let max_x = if horizontal {
            (content_w - client_w).max(0.0)
        } else {
            0.0
        };

        let scroll_y = snap.scroll_top.clamp(0.0, max_y);
        let scroll_x = snap.scroll_left.clamp(0.0, max_x);

        let edges = ScrollAreaEdges {
            top: vertical && scroll_y > 0.5,
            bottom: vertical && (max_y - scroll_y) > 0.5,
            left: horizontal && scroll_x > 0.5,
            right: horizontal && (max_x - scroll_x) > 0.5,
        };
        if edges != snap.last_edges {
            internal.update(cx, |s, _| {
                s.last_edges = edges;
            });
            if let Some(cb) = self.on_edge_change.clone() {
                window.defer(cx, move |window, cx| {
                    cb(&edges, window, cx);
                });
            }
        }

        let scrolling_active = (now - snap.last_scroll_at) < self.hide_delay_secs;
        if scrolling_active {
            window.request_animation_frame();
        }

        let bars_visible = self.scrollbars == ScrollbarsVisibility::Always
            || snap.root_hovered
            || snap.dragging.is_some()
            || scrolling_active;
        let bar_alpha = if reduced {
            if bars_visible { 1.0 } else { 0.0 }
        } else {
            arc_spring(
                (self.id.clone(), "bar-alpha"),
                if bars_visible { 1.0 } else { 0.0 },
                motion.spring.snappy,
                window,
                cx,
            )
        };

        let (fade_top, fade_bottom) = if vertical {
            scroll_area_edge_fades(scroll_y, max_y, self.fade)
        } else {
            (0.0, 0.0)
        };
        let (fade_left, fade_right) = if horizontal {
            scroll_area_edge_fades(scroll_x, max_x, self.fade)
        } else {
            (0.0, 0.0)
        };

        let both_axes = self.orientation == ScrollAreaOrientation::Both;
        let corner_inset = scroll_area_track_inset(self.corner_radius);
        let track_y_start = corner_inset;
        let track_y_end = if both_axes {
            corner_inset.max(13.0)
        } else {
            corner_inset
        };
        let track_x_start = corner_inset;
        let track_x_end = if both_axes {
            corner_inset.max(13.0)
        } else {
            corner_inset
        };
        let track_y_len = (client_h - track_y_start - track_y_end).max(28.0);
        let track_x_len = (client_w - track_x_start - track_x_end).max(28.0);

        let thumb_y = if vertical {
            scroll_area_thumb_metrics(scroll_y, client_h, content_h, track_y_len)
        } else {
            None
        };
        let thumb_x = if horizontal {
            scroll_area_thumb_metrics(scroll_x, client_w, content_w, track_x_len)
        } else {
            None
        };

        let vp_ref = snap.viewport_bounds.clone();
        let vp_ref_paint = snap.viewport_bounds.clone();
        let drag_state = snap.dragging;
        let int_win = internal.clone();
        let viewport_probe = canvas(
            move |rect, _, _| {
                *vp_ref.borrow_mut() = Some(rect);
            },
            move |rect, _, window, _| {
                let prev = *vp_ref_paint.borrow();
                if prev.is_none_or(|b| {
                    (f32::from(b.size.width) - f32::from(rect.size.width)).abs() > 0.5
                        || (f32::from(b.size.height) - f32::from(rect.size.height)).abs() > 0.5
                }) {
                    *vp_ref_paint.borrow_mut() = Some(rect);
                    window.request_animation_frame();
                }
                if let Some(axis) = drag_state {
                    let st_move = int_win.clone();
                    window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
                        if !phase.bubble() {
                            return;
                        }
                        let t = motion_now(cx);
                        let coord = match axis {
                            DragAxis::Y => f32::from(event.position.y),
                            DragAxis::X => f32::from(event.position.x),
                        };
                        st_move.update(cx, |s, _| {
                            let delta = (coord - s.drag_start_coord) * s.drag_ratio;
                            match axis {
                                DragAxis::Y => {
                                    s.scroll_top = (s.drag_start_scroll + delta).clamp(0.0, max_y);
                                }
                                DragAxis::X => {
                                    s.scroll_left = (s.drag_start_scroll + delta).clamp(0.0, max_x);
                                }
                            }
                            s.last_scroll_at = t;
                        });
                        window.refresh();
                    });

                    let st_up = int_win.clone();
                    window.on_mouse_event(move |_: &MouseUpEvent, phase, window, cx| {
                        if !phase.bubble() {
                            return;
                        }
                        let t = motion_now(cx);
                        st_up.update(cx, |s, _| {
                            s.dragging = None;
                            s.last_scroll_at = t;
                        });
                        window.refresh();
                    });
                }
            },
        )
        .absolute()
        .inset_0();

        let content_ref = snap.content_size.clone();
        let content_probe = canvas(
            move |rect, _, _| {
                let w = f32::from(rect.size.width);
                let h = f32::from(rect.size.height);
                if w > 4.0 && h > 4.0 {
                    *content_ref.borrow_mut() = (w, h);
                }
            },
            |_, _, _, _| {},
        )
        .absolute()
        .inset_0();

        let mut inner = div()
            .relative()
            .flex_none()
            .top(px(-scroll_y))
            .left(px(-scroll_x))
            .child(content_probe);
        if let Some(cw) = self.content_width {
            inner = inner.w(px(cw));
        } else if !horizontal {
            inner = inner.w_full();
        } else {
            inner = inner.min_w_full();
        }
        if let Some(ch) = self.content_height {
            inner = inner.h(px(ch));
        }
        if let Some(body) = self.body {
            inner = inner.child(body);
        }

        let fade_color = self.surface_color.unwrap_or(colors.surface);

        let int_hover = internal.clone();
        let int_wheel = internal.clone();
        let int_key = internal.clone();
        let focus_click = snap.focus_handle.clone();
        let orient = self.orientation;
        let wheel_horiz = self.wheel_to_horizontal;

        let mut root = div()
            .id(self.id.clone())
            .test_support()
            .track_focus(&snap.focus_handle)
            .relative()
            .w_full()
            .overflow_hidden()
            .when_some(self.max_height, |d, h| d.h(px(h)))
            .when_some(self.max_width, |d, w| d.max_w(px(w)))
            .when_some(self.label, |d, lbl| d.role(Role::Region).aria_label(lbl))
            .on_hover(move |hovered, window, cx| {
                int_hover.update(cx, |s, _| {
                    s.root_hovered = *hovered;
                });
                window.refresh();
            })
            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
                focus_click.focus(window, cx);
            })
            .on_scroll(move |event: &ScrollEvent, window, cx| {
                let (dx, dy) = match event.delta {
                    ScrollDelta::Pixels(pt) => (-f32::from(pt.x), -f32::from(pt.y)),
                    ScrollDelta::Lines(pt) => (-pt.x * 28.0, -pt.y * 28.0),
                };
                let shift = event.modifiers.shift;
                let t = motion_now(cx);
                let mut should_stop = false;
                int_wheel.update(cx, |s, _| {
                    let prev_top = s.scroll_top;
                    let prev_left = s.scroll_left;
                    let use_horizontal = (orient == ScrollAreaOrientation::Horizontal
                        && (wheel_horiz || shift))
                        || (horizontal && shift);

                    if use_horizontal && dx.abs() < dy.abs() {
                        s.scroll_left = (s.scroll_left + dy).clamp(0.0, max_x);
                        should_stop =
                            shift || max_x > 0.5 || (s.scroll_left - prev_left).abs() > 0.01;
                    } else if shift && !horizontal {
                        should_stop = true;
                    } else {
                        if vertical {
                            s.scroll_top = (s.scroll_top + dy).clamp(0.0, max_y);
                            if max_y > 0.5 || (s.scroll_top - prev_top).abs() > 0.01 {
                                should_stop = true;
                            }
                        }
                        if horizontal {
                            s.scroll_left = (s.scroll_left + dx).clamp(0.0, max_x);
                            if shift || max_x > 0.5 || (s.scroll_left - prev_left).abs() > 0.01 {
                                should_stop = true;
                            }
                        }
                    }
                    s.last_scroll_at = t;
                });
                if should_stop {
                    cx.stop_propagation();
                }
                window.refresh();
            })
            .on_key_down(move |event: &KeyDownEvent, window, cx| {
                let key = event.keystroke.key.as_str();
                let t = motion_now(cx);
                let mut handled = true;
                int_key.update(cx, |s, _| {
                    match key {
                        "down" | "arrowdown" if vertical => {
                            s.scroll_top = (s.scroll_top + 36.0).clamp(0.0, max_y);
                        }
                        "up" | "arrowup" if vertical => {
                            s.scroll_top = (s.scroll_top - 36.0).clamp(0.0, max_y);
                        }
                        "right" | "arrowright" if horizontal => {
                            s.scroll_left = (s.scroll_left + 36.0).clamp(0.0, max_x);
                        }
                        "left" | "arrowleft" if horizontal => {
                            s.scroll_left = (s.scroll_left - 36.0).clamp(0.0, max_x);
                        }
                        "pagedown" if vertical => {
                            s.scroll_top = (s.scroll_top + client_h * 0.9).clamp(0.0, max_y);
                        }
                        "pageup" if vertical => {
                            s.scroll_top = (s.scroll_top - client_h * 0.9).clamp(0.0, max_y);
                        }
                        "home" => {
                            if vertical {
                                s.scroll_top = 0.0;
                            } else if horizontal {
                                s.scroll_left = 0.0;
                            }
                        }
                        "end" => {
                            if vertical {
                                s.scroll_top = max_y;
                            } else if horizontal {
                                s.scroll_left = max_x;
                            }
                        }
                        _ => {
                            handled = false;
                        }
                    }
                    if handled {
                        s.last_scroll_at = t;
                    }
                });
                if handled {
                    window.refresh();
                }
            })
            .child(viewport_probe)
            .child(inner);

        if fade_top > 0.5 {
            root = root.child(
                div()
                    .absolute()
                    .top_0()
                    .left_0()
                    .right_0()
                    .h(px(fade_top))
                    .bg(linear_gradient(
                        180.0,
                        linear_color_stop(fade_color, 0.0),
                        linear_color_stop(fade_color.opacity(0.0), 1.0),
                    )),
            );
        }
        if fade_bottom > 0.5 {
            root = root.child(
                div()
                    .absolute()
                    .bottom_0()
                    .left_0()
                    .right_0()
                    .h(px(fade_bottom))
                    .bg(linear_gradient(
                        180.0,
                        linear_color_stop(fade_color.opacity(0.0), 0.0),
                        linear_color_stop(fade_color, 1.0),
                    )),
            );
        }
        if fade_left > 0.5 {
            root = root.child(
                div()
                    .absolute()
                    .top_0()
                    .bottom_0()
                    .left_0()
                    .w(px(fade_left))
                    .bg(linear_gradient(
                        90.0,
                        linear_color_stop(fade_color, 0.0),
                        linear_color_stop(fade_color.opacity(0.0), 1.0),
                    )),
            );
        }
        if fade_right > 0.5 {
            root = root.child(
                div()
                    .absolute()
                    .top_0()
                    .bottom_0()
                    .right_0()
                    .w(px(fade_right))
                    .bg(linear_gradient(
                        90.0,
                        linear_color_stop(fade_color.opacity(0.0), 0.0),
                        linear_color_stop(fade_color, 1.0),
                    )),
            );
        }

        // Vertical overlay scrollbar
        if let Some((thumb_h, thumb_y_off)) = thumb_y {
            let active_y = snap.track_y_hovered || snap.dragging == Some(DragAxis::Y);
            let pill_w = if active_y { 7.0 } else { 5.0 };
            let pill_right = if active_y { 2.0 } else { 3.0 };
            let pill_color = colors
                .foreground
                .opacity((if active_y { 0.46 } else { 0.30 }) * bar_alpha);

            let int_y_hover = internal.clone();
            let int_y_thumb = internal.clone();
            let int_y_track = internal.clone();
            let vp_for_y = snap.viewport_bounds.clone();

            root = root.child(
                div()
                    .id(ElementId::NamedChild(
                        self.id.clone().into(),
                        "track-y".into(),
                    ))
                    .test_support()
                    .absolute()
                    .top(px(track_y_start))
                    .right(px(1.0))
                    .bottom(px(track_y_end))
                    .w(px(11.0))
                    .overflow_hidden()
                    .cursor_pointer()
                    .on_hover(move |hovered, window, cx| {
                        int_y_hover.update(cx, |s, _| {
                            s.track_y_hovered = *hovered;
                        });
                        window.refresh();
                    })
                    .on_mouse_down(
                        MouseButton::Left,
                        move |event: &MouseDownEvent, window, cx| {
                            if let Some(vp) = *vp_for_y.borrow() {
                                let local_y = f32::from(event.position.y)
                                    - f32::from(vp.origin.y)
                                    - track_y_start;
                                if local_y < thumb_y_off || local_y > thumb_y_off + thumb_h {
                                    let dir = if local_y < thumb_y_off { -1.0 } else { 1.0 };
                                    let t = motion_now(cx);
                                    int_y_track.update(cx, |s, _| {
                                        s.scroll_top =
                                            (s.scroll_top + client_h * 0.9 * dir).clamp(0.0, max_y);
                                        s.last_scroll_at = t;
                                    });
                                    window.refresh();
                                }
                            }
                        },
                    )
                    .child(
                        div()
                            .id(ElementId::NamedChild(
                                self.id.clone().into(),
                                "thumb-y".into(),
                            ))
                            .test_support()
                            .absolute()
                            .top(px(thumb_y_off))
                            .right(px(pill_right))
                            .w(px(pill_w))
                            .h(px(thumb_h))
                            .rounded(Radii::PILL)
                            .bg(pill_color)
                            .on_mouse_down(
                                MouseButton::Left,
                                move |event: &MouseDownEvent, window, cx| {
                                    let t = motion_now(cx);
                                    let ratio = max_y / (track_y_len - thumb_h).max(1.0);
                                    int_y_thumb.update(cx, |s, _| {
                                        s.dragging = Some(DragAxis::Y);
                                        s.drag_start_coord = f32::from(event.position.y);
                                        s.drag_start_scroll = s.scroll_top;
                                        s.drag_ratio = ratio;
                                        s.last_scroll_at = t;
                                    });
                                    window.refresh();
                                },
                            ),
                    ),
            );
        }

        // Horizontal overlay scrollbar
        if let Some((thumb_w, thumb_x_off)) = thumb_x {
            let active_x = snap.track_x_hovered || snap.dragging == Some(DragAxis::X);
            let pill_h = if active_x { 7.0 } else { 5.0 };
            let pill_bottom = if active_x { 2.0 } else { 3.0 };
            let pill_color = colors
                .foreground
                .opacity((if active_x { 0.46 } else { 0.30 }) * bar_alpha);

            let int_x_hover = internal.clone();
            let int_x_thumb = internal.clone();
            let int_x_track = internal.clone();
            let vp_for_x = snap.viewport_bounds.clone();

            root = root.child(
                div()
                    .id(ElementId::NamedChild(
                        self.id.clone().into(),
                        "track-x".into(),
                    ))
                    .test_support()
                    .absolute()
                    .left(px(track_x_start))
                    .right(px(track_x_end))
                    .bottom(px(1.0))
                    .h(px(11.0))
                    .overflow_hidden()
                    .cursor_pointer()
                    .on_hover(move |hovered, window, cx| {
                        int_x_hover.update(cx, |s, _| {
                            s.track_x_hovered = *hovered;
                        });
                        window.refresh();
                    })
                    .on_mouse_down(
                        MouseButton::Left,
                        move |event: &MouseDownEvent, window, cx| {
                            if let Some(vp) = *vp_for_x.borrow() {
                                let local_x = f32::from(event.position.x)
                                    - f32::from(vp.origin.x)
                                    - track_x_start;
                                if local_x < thumb_x_off || local_x > thumb_x_off + thumb_w {
                                    let dir = if local_x < thumb_x_off { -1.0 } else { 1.0 };
                                    let t = motion_now(cx);
                                    int_x_track.update(cx, |s, _| {
                                        s.scroll_left = (s.scroll_left + client_w * 0.9 * dir)
                                            .clamp(0.0, max_x);
                                        s.last_scroll_at = t;
                                    });
                                    window.refresh();
                                }
                            }
                        },
                    )
                    .child(
                        div()
                            .id(ElementId::NamedChild(
                                self.id.clone().into(),
                                "thumb-x".into(),
                            ))
                            .test_support()
                            .absolute()
                            .left(px(thumb_x_off))
                            .bottom(px(pill_bottom))
                            .w(px(thumb_w))
                            .h(px(pill_h))
                            .rounded(Radii::PILL)
                            .bg(pill_color)
                            .on_mouse_down(
                                MouseButton::Left,
                                move |event: &MouseDownEvent, window, cx| {
                                    let t = motion_now(cx);
                                    let ratio = max_x / (track_x_len - thumb_w).max(1.0);
                                    int_x_thumb.update(cx, |s, _| {
                                        s.dragging = Some(DragAxis::X);
                                        s.drag_start_coord = f32::from(event.position.x);
                                        s.drag_start_scroll = s.scroll_left;
                                        s.drag_ratio = ratio;
                                        s.last_scroll_at = t;
                                    });
                                    window.refresh();
                                },
                            ),
                    ),
            );
        }

        root
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn scroll_area_thumb_metrics_respects_min_thumb_and_bounds() {
        // Not overflowing -> None
        assert!(scroll_area_thumb_metrics(0.0, 300.0, 280.0, 294.0).is_none());

        // 50% scrolled through 2x content -> half track thumb, centered at end when at max
        let (size, off0) = scroll_area_thumb_metrics(0.0, 200.0, 400.0, 200.0).unwrap();
        assert!((size - 100.0).abs() < 1e-4);
        assert!(off0.abs() < 1e-4);

        let (_, off_end) = scroll_area_thumb_metrics(200.0, 200.0, 400.0, 200.0).unwrap();
        assert!((off_end - 100.0).abs() < 1e-4);

        // Huge content clamps thumb to MIN_THUMB (28px)
        let (tiny_size, _) = scroll_area_thumb_metrics(0.0, 200.0, 10_000.0, 200.0).unwrap();
        assert!((tiny_size - SCROLL_AREA_MIN_THUMB).abs() < 1e-4);
    }

    #[test]
    fn scroll_area_edge_fades_grow_proportionally_up_to_cap() {
        let (top0, bot0) = scroll_area_edge_fades(0.0, 300.0, 28.0);
        assert!(top0.abs() < 1e-4);
        assert!((bot0 - 28.0).abs() < 1e-4);

        let (top10, bot10) = scroll_area_edge_fades(10.0, 300.0, 28.0);
        assert!((top10 - 10.0).abs() < 1e-4);
        assert!((bot10 - 28.0).abs() < 1e-4);

        let (top_end, bot_end) = scroll_area_edge_fades(300.0, 300.0, 28.0);
        assert!((top_end - 28.0).abs() < 1e-4);
        assert!(bot_end.abs() < 1e-4);
    }

    #[test]
    fn scroll_area_track_inset_clears_rounded_corners() {
        assert!((scroll_area_track_inset(0.0) - 3.0).abs() < 1e-4);
        assert!((scroll_area_track_inset(18.0) - 18.0).abs() < 1e-4);
        assert!((scroll_area_track_inset(34.0) - 34.0).abs() < 1e-4);
    }
}