gpui-component 0.6.0

GPUI Component: the styled component library of GPUI Kit, with 60+ desktop UI components for GPUI.
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
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
use std::{panic::Location, rc::Rc};

use crate::{InteractiveElementExt as _, StyledExt};

use super::{Scrollbar, ScrollbarAxis, ScrollbarHandle};
use gpui::{
    App, Div, Element, ElementId, InteractiveElement, IntoElement, Overflow, ParentElement,
    PointRefinement, RenderOnce, ScrollHandle, Stateful, StatefulInteractiveElement,
    StyleRefinement, Styled, Window, div, prelude::FluentBuilder,
};

/// A trait for elements that can be made scrollable with scrollbars.
///
/// The wrapped element is the scroll area itself, rather than being inserted as
/// a child of a new scroll area.
pub trait ScrollableElement: InteractiveElement + Styled + ParentElement + Element {
    /// Adds a scrollbar to the element.
    #[track_caller]
    fn scrollbar<H: ScrollbarHandle + Clone>(
        self,
        scroll_handle: &H,
        axis: impl Into<ScrollbarAxis>,
    ) -> Self {
        self.child(ScrollbarLayer {
            id: caller_id(),
            axis: axis.into(),
            scroll_handle: Rc::new(scroll_handle.clone()),
        })
    }

    /// Adds a vertical scrollbar to the element.
    #[track_caller]
    fn vertical_scrollbar<H: ScrollbarHandle + Clone>(self, scroll_handle: &H) -> Self {
        self.scrollbar(scroll_handle, ScrollbarAxis::Vertical)
    }

    /// Adds a horizontal scrollbar to the element.
    #[track_caller]
    fn horizontal_scrollbar<H: ScrollbarHandle + Clone>(self, scroll_handle: &H) -> Self {
        self.scrollbar(scroll_handle, ScrollbarAxis::Horizontal)
    }

    /// Almost equivalent to [`StatefulInteractiveElement::overflow_scroll`], but adds scrollbars.
    /// Preserves the source element as the scrollable container.
    #[track_caller]
    fn overflow_scrollbar(self) -> Scrollable<Self> {
        Scrollable::new(self, ScrollbarAxis::Both)
    }

    /// Almost equivalent to [`StatefulInteractiveElement::overflow_x_scroll`], but adds Horizontal scrollbar.
    /// Preserves the source element as the scrollable container.
    #[track_caller]
    fn overflow_x_scrollbar(self) -> Scrollable<Self> {
        Scrollable::new(self, ScrollbarAxis::Horizontal)
    }

    /// Almost equivalent to [`StatefulInteractiveElement::overflow_y_scroll`], but adds Vertical scrollbar.
    /// Preserves the source element as the scrollable container.
    #[track_caller]
    fn overflow_y_scrollbar(self) -> Scrollable<Self> {
        Scrollable::new(self, ScrollbarAxis::Vertical)
    }
}

/// A scrollable element wrapper that renders the original element as the scroll area and overlays scrollbars.
#[derive(IntoElement)]
pub struct Scrollable<E: InteractiveElement + Styled + ParentElement + Element> {
    id: ElementId,
    element: E,
    axis: ScrollbarAxis,
}

impl<E> Scrollable<E>
where
    E: InteractiveElement + Styled + ParentElement + Element,
{
    #[track_caller]
    fn new(element: E, axis: impl Into<ScrollbarAxis>) -> Self {
        Self {
            id: caller_id(),
            element,
            axis: axis.into(),
        }
    }

    /// Set a specific element id, default is the [`std::panic::Location::caller`].
    ///
    /// Only needed when one call site creates several scrollables, which would
    /// otherwise share a single scroll position.
    pub fn id(mut self, id: impl Into<ElementId>) -> Self {
        self.id = id.into();
        self
    }
}

impl<E> Styled for Scrollable<E>
where
    E: InteractiveElement + Styled + ParentElement + Element,
{
    fn style(&mut self) -> &mut StyleRefinement {
        self.element.style()
    }
}

impl<E> ParentElement for Scrollable<E>
where
    E: InteractiveElement + Styled + ParentElement + Element,
{
    fn extend(&mut self, elements: impl IntoIterator<Item = gpui::AnyElement>) {
        self.element.extend(elements)
    }
}

impl<E> InteractiveElement for Scrollable<E>
where
    E: InteractiveElement + Styled + ParentElement + Element,
{
    fn interactivity(&mut self) -> &mut gpui::Interactivity {
        self.element.interactivity()
    }
}

impl<E> RenderOnce for Scrollable<E>
where
    E: InteractiveElement + Styled + ParentElement + Element + 'static,
{
    fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let scroll_handle = scroll_handle_for(&self.id, window, cx);

        // Preserve the caller-requested size on the wrapper, while keeping the
        // caller's element as the actual scroll-tracked layout container.
        let root_style = root_style_from(&mut self.element, self.axis);

        let root_id = self.id.clone();
        let area_id = (self.id.clone(), "area");
        let content_id = (self.id.clone(), "content");
        let scrollbar_id = (self.id.clone(), "scrollbar");

        let content = self
            .element
            .id(content_id)
            .flex_none()
            .map(|this| match self.axis {
                ScrollbarAxis::Vertical => this.h_auto().min_h_full(),
                ScrollbarAxis::Horizontal => this.w_auto().min_w_full(),
                ScrollbarAxis::Both => this.size_auto().min_size_full(),
            });

        // Keep the scroll area in the normal flow: its content size must
        // propagate to auto-sized ancestors (e.g. a Dialog that grows with
        // its content). An absolutely positioned scroll area would collapse
        // such ancestors to zero height.
        let scroll_area = div()
            .id(area_id)
            .size_full()
            .flex()
            .track_scroll(&scroll_handle)
            .map(|this| match self.axis {
                ScrollbarAxis::Vertical => this.flex_col().overflow_y_scroll(),
                ScrollbarAxis::Horizontal => this.flex_row().overflow_x_scroll(),
                ScrollbarAxis::Both => this.overflow_scroll(),
            })
            // On a single-axis area gpui otherwise remaps the other axis' delta
            // onto ours, so a purely horizontal swipe scrolls this vertically.
            .lock_scroll_axis()
            .child(content);

        div()
            .id(root_id)
            .size_full()
            .refine_style(&root_style)
            .relative()
            .child(scroll_area)
            .child(render_scrollbar(
                scrollbar_id,
                &scroll_handle,
                self.axis,
                window,
                cx,
            ))
    }
}

impl ScrollableElement for Div {}
impl<E> ScrollableElement for Stateful<E>
where
    E: ParentElement + Styled + Element,
    Self: InteractiveElement,
{
}

#[derive(IntoElement)]
struct ScrollbarLayer<H: ScrollbarHandle + Clone> {
    id: ElementId,
    axis: ScrollbarAxis,
    scroll_handle: Rc<H>,
}

impl<H> RenderOnce for ScrollbarLayer<H>
where
    H: ScrollbarHandle + Clone + 'static,
{
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        render_scrollbar(self.id, self.scroll_handle.as_ref(), self.axis, window, cx)
    }
}

#[inline]
#[track_caller]
fn caller_id() -> ElementId {
    ElementId::CodeLocation(*Location::caller())
}

#[inline]
fn scroll_handle_for(id: &ElementId, window: &mut Window, cx: &mut App) -> ScrollHandle {
    window
        .use_keyed_state(id.clone(), cx, |_, _| ScrollHandle::default())
        .read(cx)
        .clone()
}

/// Copies the outer layout styles from the element, so the wrapper can
/// participate in the parent's layout the same way the source element would.
///
/// A flex item only drops its content-based automatic minimum size when its own
/// overflow is not [`Overflow::Visible`]; otherwise the item refuses to shrink
/// around its content. The scrolled overflow lives on the inner scroll area, so
/// the wrapper has to declare the scrolled axis clipped itself — without it a
/// scroll region used as a flex item pushes its siblings out of the container
/// instead of scrolling, and every call site has to remember `min_h_0()` /
/// `min_w_0()`.
///
/// [`Overflow::Hidden`] rather than a zero minimum: it is the axis' real
/// behavior, it leaves an explicit `min_size` from the caller in charge, and it
/// keeps the region's content size contributing to an auto-sized ancestor such
/// as a Dialog that grows with its body. The mask it installs matches the inner
/// scroll area's own mask, so nothing new is clipped.
#[inline]
fn root_style_from<E>(element: &mut E, axis: ScrollbarAxis) -> StyleRefinement
where
    E: Styled,
{
    let style = element.style();
    StyleRefinement {
        size: style.size.clone(),
        min_size: style.min_size.clone(),
        max_size: style.max_size.clone(),
        flex_grow: style.flex_grow,
        flex_shrink: style.flex_shrink,
        flex_basis: style.flex_basis,
        align_self: style.align_self,
        overflow: PointRefinement {
            x: axis.has_horizontal().then_some(Overflow::Hidden),
            y: axis.has_vertical().then_some(Overflow::Hidden),
        },
        ..Default::default()
    }
}

#[inline]
fn render_scrollbar<H: ScrollbarHandle + Clone>(
    id: impl Into<ElementId>,
    scroll_handle: &H,
    axis: ScrollbarAxis,
    window: &mut Window,
    cx: &mut App,
) -> Div {
    // Do not render scrollbar when inspector is picking elements,
    // to allow us to pick the background elements.
    let is_inspector_picking = window.is_inspector_picking(cx);
    if is_inspector_picking {
        return div();
    }

    div()
        .absolute()
        .inset_0()
        .debug_selector(|| "scrollbar-overlay".to_string())
        .child(
            Scrollbar::new(scroll_handle)
                .id(id)
                .axis(axis)
                .viewport_from_layout(),
        )
}

#[cfg(test)]
mod tests {
    use super::*;
    use gpui::{
        Context, Render, ScrollDelta, ScrollWheelEvent, TestAppContext, VisualTestContext, point,
        px,
    };

    fn draw(cx: &mut VisualTestContext) {
        cx.run_until_parked();
        cx.update(|window, cx| {
            _ = window.draw(cx);
        });
    }

    fn scroll(cx: &mut VisualTestContext, x: f32, y: f32, dx: f32, dy: f32) {
        cx.simulate_event(ScrollWheelEvent {
            position: point(px(x), px(y)),
            delta: ScrollDelta::Pixels(point(px(dx), px(dy))),
            ..Default::default()
        });
        draw(cx);
    }

    fn row(selector: &'static str, height: f32) -> Div {
        div()
            .h(px(height))
            .flex_shrink_0()
            .debug_selector(move || selector.to_string())
    }

    fn plain_row(height: f32) -> Div {
        div().h(px(height)).flex_shrink_0()
    }

    fn item(selector: &'static str, width: f32) -> Div {
        div()
            .w(px(width))
            .h(px(20.))
            .flex_shrink_0()
            .debug_selector(move || selector.to_string())
    }

    fn plain_item(width: f32) -> Div {
        div().w(px(width)).h(px(20.)).flex_shrink_0()
    }

    struct SizeFullChildTest;

    impl Render for SizeFullChildTest {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            div()
                .w(px(100.))
                .h(px(100.))
                .overflow_y_scrollbar()
                .child(
                    div()
                        .size_full()
                        .child(crate::v_flex().children((0..4).map(|ix| {
                            div().h(px(50.)).flex_shrink_0().when(ix == 3, |this| {
                                this.debug_selector(|| "last-row".to_string())
                            })
                        }))),
                )
        }
    }

    struct AutoHeightParentTest;

    impl Render for AutoHeightParentTest {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            // Mimics Dialog: the panel height is auto (content-driven), the
            // body is flex_1 + overflow_hidden, and the scrollable content
            // should give the panel its intrinsic height.
            // GPUI window roots with auto dimensions stretch to the viewport,
            // so keep the auto-height panel below an explicit viewport root.
            div().size_full().child(
                crate::v_flex()
                    .w(px(200.))
                    .child(
                        crate::v_flex().flex_1().overflow_hidden().child(
                            div().flex_1().overflow_hidden().child(
                                crate::v_flex()
                                    .size_full()
                                    .overflow_y_scrollbar()
                                    .child(plain_row(50.))
                                    .child(plain_row(50.)),
                            ),
                        ),
                    )
                    .child(row("auto-height-footer", 10.)),
            )
        }
    }

    struct MaxHeightParentTest;

    impl Render for MaxHeightParentTest {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            // Mimics a Dialog with `max_h`: the panel grows with content up
            // to the max height, then the body starts scrolling.
            crate::v_flex()
                .w(px(200.))
                .max_h(px(100.))
                .child(
                    crate::v_flex().flex_1().overflow_hidden().child(
                        div().flex_1().overflow_hidden().child(
                            crate::v_flex()
                                .size_full()
                                .overflow_y_scrollbar()
                                .child(plain_row(50.))
                                .child(plain_row(50.))
                                .child(row("max-height-last-row", 50.)),
                        ),
                    ),
                )
                .child(row("max-height-footer", 10.))
        }
    }

    #[gpui::test]
    fn auto_height_parent_gets_content_height(cx: &mut TestAppContext) {
        cx.update(crate::init);
        let (_, cx) = cx.add_window_view(|_, _| AutoHeightParentTest);
        let cx: &mut VisualTestContext = cx;
        draw(cx);

        // The two 50px rows should push the footer down to y = 100.
        let footer = cx.debug_bounds("auto-height-footer").unwrap();
        assert_eq!(footer.top(), px(100.));
    }

    #[gpui::test]
    fn max_height_parent_clamps_and_scrolls(cx: &mut TestAppContext) {
        cx.update(crate::init);
        let (_, cx) = cx.add_window_view(|_, _| MaxHeightParentTest);
        let cx: &mut VisualTestContext = cx;
        draw(cx);

        // Content (150) + footer (10) exceeds max_h(100): the footer is
        // pinned at the bottom and the body gets the remaining 90px viewport.
        let footer = cx.debug_bounds("max-height-footer").unwrap();
        assert_eq!(footer.top(), px(90.));

        let last_initial_y = cx.debug_bounds("max-height-last-row").unwrap().origin.y;
        scroll(cx, 10., 10., 0., -50.);
        assert!(cx.debug_bounds("max-height-last-row").unwrap().origin.y < last_initial_y);
    }

    struct FlexItemScrollableTest;

    impl Render for FlexItemScrollableTest {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            // A fixed-height column of header, flexible scroll area, footer.
            // The content is far taller than the room left for the area, so
            // the area must shrink into the remaining 60px and scroll.
            crate::v_flex()
                .w(px(100.))
                .h(px(100.))
                .child(row("flex-item-header", 20.))
                .child(
                    crate::v_flex()
                        .flex_1()
                        .overflow_y_scrollbar()
                        .children((0..6).map(|ix| {
                            div().h(px(50.)).flex_shrink_0().when(ix == 0, |this| {
                                this.debug_selector(|| "flex-item-first-row".to_string())
                            })
                        })),
                )
                .child(row("flex-item-footer", 20.))
        }
    }

    #[gpui::test]
    fn scrollable_flex_item_shrinks_below_its_content(cx: &mut TestAppContext) {
        cx.update(crate::init);
        let (_, cx) = cx.add_window_view(|_, _| FlexItemScrollableTest);
        let cx: &mut VisualTestContext = cx;
        draw(cx);

        // Header and footer stay inside the 100px column, so the area took
        // the 60px left over instead of its content height.
        assert_eq!(cx.debug_bounds("flex-item-header").unwrap().top(), px(0.));
        assert_eq!(cx.debug_bounds("flex-item-footer").unwrap().top(), px(80.));

        // And the shrunken area really scrolls.
        let initial_y = cx.debug_bounds("flex-item-first-row").unwrap().origin.y;
        scroll(cx, 10., 50., 0., -50.);
        assert!(cx.debug_bounds("flex-item-first-row").unwrap().origin.y < initial_y);
    }

    struct HorizontalFlexItemScrollableTest;

    impl Render for HorizontalFlexItemScrollableTest {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            crate::h_flex()
                .w(px(100.))
                .h(px(40.))
                .child(item("horizontal-flex-item-leading", 20.))
                .child(
                    crate::h_flex()
                        .flex_1()
                        .overflow_x_scrollbar()
                        .children((0..6).map(|ix| {
                            div()
                                .w(px(50.))
                                .h(px(20.))
                                .flex_shrink_0()
                                .when(ix == 0, |this| {
                                    this.debug_selector(|| {
                                        "horizontal-flex-item-first-item".to_string()
                                    })
                                })
                        })),
                )
                .child(item("horizontal-flex-item-trailing", 20.))
        }
    }

    #[gpui::test]
    fn horizontal_scrollable_flex_item_shrinks_below_its_content(cx: &mut TestAppContext) {
        cx.update(crate::init);
        let (_, cx) = cx.add_window_view(|_, _| HorizontalFlexItemScrollableTest);
        let cx: &mut VisualTestContext = cx;
        draw(cx);

        assert_eq!(
            cx.debug_bounds("horizontal-flex-item-leading")
                .unwrap()
                .left(),
            px(0.)
        );
        assert_eq!(
            cx.debug_bounds("horizontal-flex-item-trailing")
                .unwrap()
                .left(),
            px(80.)
        );

        let initial_x = cx
            .debug_bounds("horizontal-flex-item-first-item")
            .unwrap()
            .origin
            .x;
        scroll(cx, 50., 10., -50., 0.);
        assert!(
            cx.debug_bounds("horizontal-flex-item-first-item")
                .unwrap()
                .origin
                .x
                < initial_x
        );
    }

    struct ExplicitMinHeightScrollableTest;

    impl Render for ExplicitMinHeightScrollableTest {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            // An explicit `min_h` is the caller's decision and must survive.
            crate::v_flex()
                .w(px(100.))
                .h(px(100.))
                .child(row("explicit-min-header", 20.))
                .child(
                    crate::v_flex()
                        .flex_1()
                        .min_h(px(70.))
                        .overflow_y_scrollbar()
                        .children((0..6).map(|_| plain_row(50.))),
                )
                .child(row("explicit-min-footer", 20.))
        }
    }

    #[gpui::test]
    fn explicit_min_size_survives_the_scrollable_wrapper(cx: &mut TestAppContext) {
        cx.update(crate::init);
        let (_, cx) = cx.add_window_view(|_, _| ExplicitMinHeightScrollableTest);
        let cx: &mut VisualTestContext = cx;
        draw(cx);

        // The area cannot shrink past the requested 70px, so the footer is
        // pushed to 20 + 70 instead of being clamped into the column.
        assert_eq!(
            cx.debug_bounds("explicit-min-header").unwrap().top(),
            px(0.)
        );
        assert_eq!(
            cx.debug_bounds("explicit-min-footer").unwrap().top(),
            px(90.)
        );
    }

    struct GapLayoutTest;

    struct PaddedScrollbarOverlayTest;

    impl Render for PaddedScrollbarOverlayTest {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            crate::v_flex()
                .w(px(100.))
                .h(px(100.))
                .p(px(20.))
                .overflow_y_scrollbar()
                .children((0..4).map(|_| plain_row(50.)))
        }
    }

    #[gpui::test]
    fn scrollbar_overlay_ignores_content_padding(cx: &mut TestAppContext) {
        cx.update(crate::init);
        let (_, cx) = cx.add_window_view(|_, _| PaddedScrollbarOverlayTest);
        let cx: &mut VisualTestContext = cx;
        draw(cx);

        let overlay = cx.debug_bounds("scrollbar-overlay").unwrap();
        assert_eq!(overlay.origin, point(px(0.), px(0.)));
        assert_eq!(overlay.size, gpui::size(px(100.), px(100.)));
    }

    impl Render for GapLayoutTest {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            crate::v_flex()
                .w(px(100.))
                .h(px(100.))
                .gap(px(10.))
                .overflow_y_scrollbar()
                .child(row("first-row", 20.))
                .child(row("second-row", 20.))
        }
    }

    struct IssueGapRegressionTest;

    impl Render for IssueGapRegressionTest {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            div().w(px(100.)).h(px(100.)).child(
                crate::v_flex()
                    .flex_1()
                    .gap(px(30.))
                    .overflow_y_scrollbar()
                    .px(px(12.))
                    .pb(px(16.))
                    .children((0..5).map(|ix| {
                        div()
                            .h(px(20.))
                            .flex_shrink_0()
                            .when(ix == 0, |this| {
                                this.debug_selector(|| "issue-first-card".to_string())
                            })
                            .when(ix == 1, |this| {
                                this.debug_selector(|| "issue-second-card".to_string())
                            })
                            .when(ix == 4, |this| {
                                this.debug_selector(|| "issue-last-card".to_string())
                            })
                    })),
            )
        }
    }

    struct HorizontalGapLayoutTest;

    impl Render for HorizontalGapLayoutTest {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            crate::h_flex()
                .w(px(100.))
                .h(px(40.))
                .gap(px(10.))
                .overflow_x_scrollbar()
                .child(item("horizontal-first-item", 50.))
                .child(item("horizontal-second-item", 50.))
                .child(item("horizontal-last-item", 50.))
        }
    }

    struct OverflowScrollbarVerticalTest;

    impl Render for OverflowScrollbarVerticalTest {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            crate::v_flex()
                .w(px(100.))
                .h(px(100.))
                .gap(px(10.))
                .overflow_scrollbar()
                .child(row("both-axis-vertical-first-row", 50.))
                .child(row("both-axis-vertical-second-row", 50.))
                .child(row("both-axis-vertical-last-row", 50.))
        }
    }

    struct OverflowScrollbarHorizontalTest;

    impl Render for OverflowScrollbarHorizontalTest {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            crate::h_flex()
                .w(px(100.))
                .h(px(40.))
                .gap(px(10.))
                .overflow_scrollbar()
                .child(item("both-axis-horizontal-first-item", 50.))
                .child(item("both-axis-horizontal-second-item", 50.))
                .child(item("both-axis-horizontal-last-item", 50.))
        }
    }

    struct IndependentScrollablesTest;

    impl Render for IndependentScrollablesTest {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            crate::h_flex()
                .w(px(220.))
                .h(px(100.))
                .gap(px(20.))
                .child(
                    div().w(px(100.)).h(px(100.)).overflow_y_scrollbar().child(
                        crate::v_flex()
                            .child(plain_row(50.))
                            .child(plain_row(50.))
                            .child(row("left-scrollable-last-row", 50.)),
                    ),
                )
                .child(
                    div().w(px(100.)).h(px(100.)).overflow_y_scrollbar().child(
                        crate::v_flex()
                            .child(plain_row(50.))
                            .child(plain_row(50.))
                            .child(row("right-scrollable-last-row", 50.)),
                    ),
                )
        }
    }

    struct NoOverflowTest;

    impl Render for NoOverflowTest {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            crate::v_flex()
                .w(px(100.))
                .h(px(100.))
                .gap(px(10.))
                .overflow_y_scrollbar()
                .child(row("no-overflow-first-row", 20.))
                .child(row("no-overflow-second-row", 20.))
        }
    }

    #[gpui::test]
    fn vertical_scrollbar_scrolls_past_a_size_full_child(cx: &mut TestAppContext) {
        cx.update(crate::init);
        let (_, cx) = cx.add_window_view(|_, _| SizeFullChildTest);
        let cx: &mut VisualTestContext = cx;
        draw(cx);

        let initial_y = cx.debug_bounds("last-row").unwrap().origin.y;
        scroll(cx, 10., 10., 0., -50.);

        assert!(cx.debug_bounds("last-row").unwrap().origin.y < initial_y);
    }

    #[gpui::test]
    fn vertical_scrollbar_preserves_source_gap(cx: &mut TestAppContext) {
        cx.update(crate::init);
        let (_, cx) = cx.add_window_view(|_, _| GapLayoutTest);
        let cx: &mut VisualTestContext = cx;
        draw(cx);

        let first = cx.debug_bounds("first-row").unwrap();
        let second = cx.debug_bounds("second-row").unwrap();
        assert_eq!(second.top() - first.bottom(), px(10.));
    }

    #[gpui::test]
    fn overflow_y_scrollbar_preserves_gap_for_exact_issue_chain(cx: &mut TestAppContext) {
        cx.update(crate::init);
        let (_, cx) = cx.add_window_view(|_, _| IssueGapRegressionTest);
        let cx: &mut VisualTestContext = cx;
        draw(cx);

        let first = cx.debug_bounds("issue-first-card").unwrap();
        let second = cx.debug_bounds("issue-second-card").unwrap();
        let last_initial_y = cx.debug_bounds("issue-last-card").unwrap().origin.y;

        assert_eq!(second.top() - first.bottom(), px(30.));
        assert_eq!(first.left(), px(12.));

        scroll(cx, 10., 10., 0., -50.);

        let first_after_scroll = cx.debug_bounds("issue-first-card").unwrap();
        let second_after_scroll = cx.debug_bounds("issue-second-card").unwrap();
        let last_after_scroll_y = cx.debug_bounds("issue-last-card").unwrap().origin.y;

        assert_eq!(
            second_after_scroll.top() - first_after_scroll.bottom(),
            px(30.)
        );
        assert_eq!(first_after_scroll.left(), px(12.));
        assert!(last_after_scroll_y < last_initial_y);
    }

    #[gpui::test]
    fn horizontal_scrollbar_preserves_source_gap_and_scrolls(cx: &mut TestAppContext) {
        cx.update(crate::init);
        let (_, cx) = cx.add_window_view(|_, _| HorizontalGapLayoutTest);
        let cx: &mut VisualTestContext = cx;
        draw(cx);

        let first = cx.debug_bounds("horizontal-first-item").unwrap();
        let second = cx.debug_bounds("horizontal-second-item").unwrap();
        let last_initial_x = cx.debug_bounds("horizontal-last-item").unwrap().origin.x;

        assert_eq!(second.left() - first.right(), px(10.));

        scroll(cx, 10., 10., -50., 0.);

        let first_after_scroll = cx.debug_bounds("horizontal-first-item").unwrap();
        let second_after_scroll = cx.debug_bounds("horizontal-second-item").unwrap();
        let last_after_scroll_x = cx.debug_bounds("horizontal-last-item").unwrap().origin.x;

        assert_eq!(
            second_after_scroll.left() - first_after_scroll.right(),
            px(10.)
        );
        assert!(last_after_scroll_x < last_initial_x);
    }

    #[gpui::test]
    fn overflow_scrollbar_preserves_vertical_source_gap(cx: &mut TestAppContext) {
        cx.update(crate::init);
        let (_, cx) = cx.add_window_view(|_, _| OverflowScrollbarVerticalTest);
        let cx: &mut VisualTestContext = cx;
        draw(cx);

        let first = cx.debug_bounds("both-axis-vertical-first-row").unwrap();
        let second = cx.debug_bounds("both-axis-vertical-second-row").unwrap();

        assert_eq!(second.top() - first.bottom(), px(10.));
    }

    #[gpui::test]
    fn overflow_scrollbar_preserves_gap_and_scrolls_horizontally(cx: &mut TestAppContext) {
        cx.update(crate::init);
        let (_, cx) = cx.add_window_view(|_, _| OverflowScrollbarHorizontalTest);
        let cx: &mut VisualTestContext = cx;
        draw(cx);

        let first = cx.debug_bounds("both-axis-horizontal-first-item").unwrap();
        let second = cx.debug_bounds("both-axis-horizontal-second-item").unwrap();
        let last_initial_x = cx
            .debug_bounds("both-axis-horizontal-last-item")
            .unwrap()
            .origin
            .x;

        assert_eq!(second.left() - first.right(), px(10.));

        scroll(cx, 10., 10., -50., 0.);

        let first_after_scroll = cx.debug_bounds("both-axis-horizontal-first-item").unwrap();
        let second_after_scroll = cx.debug_bounds("both-axis-horizontal-second-item").unwrap();
        let last_after_scroll_x = cx
            .debug_bounds("both-axis-horizontal-last-item")
            .unwrap()
            .origin
            .x;

        assert_eq!(
            second_after_scroll.left() - first_after_scroll.right(),
            px(10.)
        );
        assert!(last_after_scroll_x < last_initial_x);
    }

    #[gpui::test]
    fn multiple_scrollables_keep_independent_scroll_state(cx: &mut TestAppContext) {
        cx.update(crate::init);
        let (_, cx) = cx.add_window_view(|_, _| IndependentScrollablesTest);
        let cx: &mut VisualTestContext = cx;
        draw(cx);

        let left_initial = cx.debug_bounds("left-scrollable-last-row").unwrap();
        let right_initial = cx.debug_bounds("right-scrollable-last-row").unwrap();

        scroll(cx, 10., 10., 0., -50.);

        let left_after_scroll = cx.debug_bounds("left-scrollable-last-row").unwrap();
        let right_after_scroll = cx.debug_bounds("right-scrollable-last-row").unwrap();

        assert!(left_after_scroll.top() < left_initial.top());
        assert_eq!(right_after_scroll.top(), right_initial.top());
    }

    #[gpui::test]
    fn vertical_scrollbar_does_not_scroll_when_content_does_not_overflow(cx: &mut TestAppContext) {
        cx.update(crate::init);
        let (_, cx) = cx.add_window_view(|_, _| NoOverflowTest);
        let cx: &mut VisualTestContext = cx;
        draw(cx);

        let first = cx.debug_bounds("no-overflow-first-row").unwrap();
        let second = cx.debug_bounds("no-overflow-second-row").unwrap();

        assert_eq!(second.top() - first.bottom(), px(10.));

        scroll(cx, 10., 10., 0., -50.);

        let first_after_scroll = cx.debug_bounds("no-overflow-first-row").unwrap();
        let second_after_scroll = cx.debug_bounds("no-overflow-second-row").unwrap();

        assert_eq!(first_after_scroll.top(), first.top());
        assert_eq!(second_after_scroll.top(), second.top());
        assert_eq!(
            second_after_scroll.top() - first_after_scroll.bottom(),
            px(10.)
        );
    }

    #[gpui::test]
    fn horizontal_scrollbar_does_not_scroll_when_content_does_not_overflow(
        cx: &mut TestAppContext,
    ) {
        struct HorizontalNoOverflowTest;

        impl Render for HorizontalNoOverflowTest {
            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
                crate::h_flex()
                    .w(px(100.))
                    .h(px(40.))
                    .gap(px(10.))
                    .overflow_x_scrollbar()
                    .child(item("no-overflow-first-item", 20.))
                    .child(item("no-overflow-second-item", 20.))
                    .child(plain_item(20.))
            }
        }

        cx.update(crate::init);
        let (_, cx) = cx.add_window_view(|_, _| HorizontalNoOverflowTest);
        let cx: &mut VisualTestContext = cx;
        draw(cx);

        let first = cx.debug_bounds("no-overflow-first-item").unwrap();
        let second = cx.debug_bounds("no-overflow-second-item").unwrap();

        assert_eq!(second.left() - first.right(), px(10.));

        scroll(cx, 10., 10., -50., 0.);

        let first_after_scroll = cx.debug_bounds("no-overflow-first-item").unwrap();
        let second_after_scroll = cx.debug_bounds("no-overflow-second-item").unwrap();

        assert_eq!(first_after_scroll.left(), first.left());
        assert_eq!(second_after_scroll.left(), second.left());
        assert_eq!(
            second_after_scroll.left() - first_after_scroll.right(),
            px(10.)
        );
    }
    struct IndependentDynamicScrollablesTest;

    impl Render for IndependentDynamicScrollablesTest {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            crate::v_flex().w(px(100.)).children((0..2).map(|ix| {
                crate::h_flex()
                    .w(px(100.))
                    .h(px(40.))
                    .overflow_x_scrollbar()
                    .id(format!("dynamic-scroll-{ix}"))
                    .child(
                        div()
                            .w(px(200.))
                            .h(px(20.))
                            .flex_shrink_0()
                            .when(ix == 0, |this| {
                                this.debug_selector(|| "dynamic-scroll-first".to_string())
                            })
                            .when(ix == 1, |this| {
                                this.debug_selector(|| "dynamic-scroll-second".to_string())
                            }),
                    )
            }))
        }
    }

    #[gpui::test]
    fn dynamic_scrollables_with_unique_scroll_ids_keep_independent_state(cx: &mut TestAppContext) {
        cx.update(crate::init);

        let (_, cx) = cx.add_window_view(|_, _| IndependentDynamicScrollablesTest);
        let cx: &mut VisualTestContext = cx;

        draw(cx);

        let first_initial = cx.debug_bounds("dynamic-scroll-first").unwrap();

        let second_initial = cx.debug_bounds("dynamic-scroll-second").unwrap();

        // Scroll horizontally inside the first row.
        scroll(cx, 10., 10., -50., 0.);

        let first_after_scroll = cx.debug_bounds("dynamic-scroll-first").unwrap();

        let second_after_scroll = cx.debug_bounds("dynamic-scroll-second").unwrap();

        // First scrollable should move horizontally.
        assert!(first_after_scroll.left() < first_initial.left());

        // Second scrollable must keep its own independent scroll state.
        assert_eq!(second_after_scroll.left(), second_initial.left());
    }
}