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
// Copyright 2020 The Druid Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! A component for embedding in another widget to provide consistent and
//! extendable scrolling behavior

use std::time::Duration;

use crate::kurbo::{Point, Rect, Vec2};
use crate::theme;
use crate::widget::{Axis, Viewport};
use crate::{Env, Event, EventCtx, LifeCycle, LifeCycleCtx, PaintCtx, RenderContext, TimerToken};

#[derive(Default, Debug, Copy, Clone)]
/// Which scroll bars of a scroll area are currently enabled.
pub enum ScrollbarsEnabled {
    /// No scrollbars are enabled
    None,
    /// Scrolling on the x axis is allowed
    Horizontal,
    /// Scrolling on the y axis is allowed
    Vertical,
    /// Bidirectional scrolling is allowed
    #[default]
    Both,
}

impl ScrollbarsEnabled {
    fn is_enabled(self, axis: Axis) -> bool {
        matches!(
            (self, axis),
            (ScrollbarsEnabled::Both, _)
                | (ScrollbarsEnabled::Horizontal, Axis::Horizontal)
                | (ScrollbarsEnabled::Vertical, Axis::Vertical)
        )
    }

    fn is_none(self) -> bool {
        matches!(self, ScrollbarsEnabled::None)
    }

    /// Set whether the horizontal scrollbar is enabled.
    pub fn set_horizontal_scrollbar_enabled(&mut self, enabled: bool) {
        *self = match (*self, enabled) {
            (ScrollbarsEnabled::None, true) | (ScrollbarsEnabled::Horizontal, true) => {
                ScrollbarsEnabled::Horizontal
            }
            (ScrollbarsEnabled::Both, true) | (ScrollbarsEnabled::Vertical, true) => {
                ScrollbarsEnabled::Both
            }
            (ScrollbarsEnabled::None, false) | (ScrollbarsEnabled::Horizontal, false) => {
                ScrollbarsEnabled::None
            }
            (ScrollbarsEnabled::Vertical, false) | (ScrollbarsEnabled::Both, false) => {
                ScrollbarsEnabled::Vertical
            }
        }
    }

    /// Set whether the vertical scrollbar is enabled.
    pub fn set_vertical_scrollbar_enabled(&mut self, enabled: bool) {
        *self = match (*self, enabled) {
            (ScrollbarsEnabled::None, true) | (ScrollbarsEnabled::Vertical, true) => {
                ScrollbarsEnabled::Vertical
            }
            (ScrollbarsEnabled::Both, true) | (ScrollbarsEnabled::Horizontal, true) => {
                ScrollbarsEnabled::Both
            }
            (ScrollbarsEnabled::None, false) | (ScrollbarsEnabled::Vertical, false) => {
                ScrollbarsEnabled::None
            }
            (ScrollbarsEnabled::Horizontal, false) | (ScrollbarsEnabled::Both, false) => {
                ScrollbarsEnabled::Horizontal
            }
        }
    }
}

/// Denotes which scrollbar, if any, is currently being hovered over
/// by the mouse.
#[derive(Debug, Copy, Clone)]
pub enum BarHoveredState {
    /// Neither scrollbar is being hovered by the mouse.
    None,
    /// The vertical scrollbar is being hovered by the mouse.
    Vertical,
    /// The horizontal scrollbar is being hovered by the mouse.
    Horizontal,
}

impl BarHoveredState {
    /// Determines if any scrollbar is currently being hovered by the mouse.
    pub fn is_hovered(self) -> bool {
        matches!(
            self,
            BarHoveredState::Vertical | BarHoveredState::Horizontal
        )
    }
}

/// Denotes which scrollbar, if any, is currently being dragged.
#[derive(Debug, Copy, Clone)]
pub enum BarHeldState {
    /// Neither scrollbar is being dragged.
    None,
    /// Vertical scrollbar is being dragged. Contains an `f64` with
    /// the initial y-offset of the dragging input.
    Vertical(f64),
    /// Horizontal scrollbar is being dragged. Contains an `f64` with
    /// the initial x-offset of the dragging input.
    Horizontal(f64),
}

/// Embeddable component exposing reusable scroll handling logic.
///
/// In most situations composing [`Scroll`] is a better idea
/// for general UI construction. However some cases are not covered by
/// composing those widgets, such as when a widget needs fine grained
/// control over its scrolling state or doesn't make sense to exist alone
/// without scrolling behavior.
///
/// `ScrollComponent` contains the input-handling and scrollbar-positioning logic used by
/// [`Scroll`].  It can be used to add this logic to a custom widget when the need arises.
///
/// It can be used like this:
/// - Store an instance of `ScrollComponent` in your widget's struct, and wrap the child widget to
///   be scrolled in a [`ClipBox`].
/// - Call [`event`] and [`lifecycle`] with all event and lifecycle events before propagating them
///   to children.
/// - Call [`handle_scroll`] with all events after handling / propagating them.
/// - Call [`draw_bars`] to draw the scrollbars.
///
/// Taking a look at the [`Scroll`] source code can be helpful. You can also do scrolling
/// without wrapping a child in a [`ClipBox`], but you will need to do certain event and
/// paint transformations yourself; see the [`ClipBox`] source code for an example.
///
/// [`Scroll`]: ../widget/struct.Scroll.html
/// [`List`]: ../widget/struct.List.html
/// [`ClipBox`]: ../widget/struct.ClipBox.html
/// [`event`]: struct.ScrollComponent.html#method.event
/// [`handle_scroll`]: struct.ScrollComponent.html#method.handle_scroll
/// [`draw_bars`]: #method.draw_bars
/// [`lifecycle`]: struct.ScrollComponent.html#method.lifecycle
#[derive(Debug, Copy, Clone)]
pub struct ScrollComponent {
    /// Current opacity for both scrollbars
    pub opacity: f64,
    /// ID for the timer which schedules scrollbar fade out
    pub timer_id: TimerToken,
    /// Which if any scrollbar is currently hovered by the mouse
    pub hovered: BarHoveredState,
    /// Which if any scrollbar is currently being dragged by the mouse
    pub held: BarHeldState,
    /// Which scrollbars are enabled
    pub enabled: ScrollbarsEnabled,
}

impl Default for ScrollComponent {
    fn default() -> Self {
        Self {
            opacity: 0.0,
            timer_id: TimerToken::INVALID,
            hovered: BarHoveredState::None,
            held: BarHeldState::None,
            enabled: ScrollbarsEnabled::Both,
        }
    }
}

impl ScrollComponent {
    /// Constructs a new [`ScrollComponent`](struct.ScrollComponent.html) for use.
    pub fn new() -> ScrollComponent {
        Default::default()
    }

    /// true if either scrollbar is currently held down/being dragged
    pub fn are_bars_held(&self) -> bool {
        !matches!(self.held, BarHeldState::None)
    }

    /// Makes the scrollbars visible, and resets the fade timer.
    pub fn reset_scrollbar_fade<F>(&mut self, request_timer: F, env: &Env)
    where
        F: FnOnce(Duration) -> TimerToken,
    {
        self.opacity = env.get(theme::SCROLLBAR_MAX_OPACITY);
        let fade_delay = env.get(theme::SCROLLBAR_FADE_DELAY);
        let deadline = Duration::from_millis(fade_delay);
        self.timer_id = request_timer(deadline);
    }

    /// Calculates the paint rect of the vertical scrollbar, or `None` if the vertical scrollbar is
    /// not visible.
    pub fn calc_vertical_bar_bounds(&self, port: &Viewport, env: &Env) -> Option<Rect> {
        self.calc_bar_bounds(Axis::Vertical, port, env)
    }

    /// Calculates the paint rect of the horizontal scrollbar, or `None` if the horizontal
    /// scrollbar is not visible.
    pub fn calc_horizontal_bar_bounds(&self, port: &Viewport, env: &Env) -> Option<Rect> {
        self.calc_bar_bounds(Axis::Horizontal, port, env)
    }

    fn calc_bar_bounds(&self, axis: Axis, port: &Viewport, env: &Env) -> Option<Rect> {
        let viewport_size = port.view_size;
        let content_size = port.content_size;
        let scroll_offset = port.view_origin.to_vec2();

        let viewport_major = axis.major(viewport_size);
        let content_major = axis.major(content_size);

        if viewport_major >= content_major {
            return None;
        }

        let bar_width = env.get(theme::SCROLLBAR_WIDTH);
        let bar_pad = env.get(theme::SCROLLBAR_PAD);
        let bar_min_size = env.get(theme::SCROLLBAR_MIN_SIZE);

        let percent_visible = viewport_major / content_major;
        let percent_scrolled = axis.major_vec(scroll_offset) / (content_major - viewport_major);

        let major_padding = if self.enabled.is_enabled(axis.cross()) {
            bar_pad + bar_pad + bar_width
        } else {
            bar_pad + bar_pad
        };
        let usable_space = viewport_major - major_padding;

        let length = (percent_visible * viewport_major).ceil();
        #[allow(clippy::manual_clamp)] // Usable space could be below the minimum bar size.
        let length = length.max(bar_min_size).min(usable_space);

        let left_x_offset = bar_pad + ((usable_space - length) * percent_scrolled).ceil();
        let right_x_offset = left_x_offset + length;

        let (x0, y0) = axis.pack(
            left_x_offset,
            axis.minor(viewport_size) - bar_width - bar_pad,
        );

        let (x1, y1) = axis.pack(right_x_offset, axis.minor(viewport_size) - bar_pad);

        if x0 >= x1 || y0 >= y1 {
            return None;
        }

        Some(Rect::new(x0, y0, x1, y1) + scroll_offset)
    }

    /// Draw scroll bars.
    pub fn draw_bars(&self, ctx: &mut PaintCtx, port: &Viewport, env: &Env) {
        let scroll_offset = port.view_origin.to_vec2();

        if self.enabled.is_none() || self.opacity <= 0.0 {
            return;
        }

        let brush = ctx
            .render_ctx
            .solid_brush(env.get(theme::SCROLLBAR_COLOR).with_alpha(self.opacity));
        let border_brush = ctx.render_ctx.solid_brush(
            env.get(theme::SCROLLBAR_BORDER_COLOR)
                .with_alpha(self.opacity),
        );

        let radius = env.get(theme::SCROLLBAR_RADIUS);
        let edge_width = env.get(theme::SCROLLBAR_EDGE_WIDTH);

        // Vertical bar
        if self.enabled.is_enabled(Axis::Vertical) {
            if let Some(bounds) = self.calc_vertical_bar_bounds(port, env) {
                let rect = (bounds - scroll_offset)
                    .inset(-edge_width / 2.0)
                    .to_rounded_rect(radius);
                ctx.render_ctx.fill(rect, &brush);
                ctx.render_ctx.stroke(rect, &border_brush, edge_width);
            }
        }

        // Horizontal bar
        if self.enabled.is_enabled(Axis::Horizontal) {
            if let Some(bounds) = self.calc_horizontal_bar_bounds(port, env) {
                let rect = (bounds - scroll_offset)
                    .inset(-edge_width / 2.0)
                    .to_rounded_rect(radius);
                ctx.render_ctx.fill(rect, &brush);
                ctx.render_ctx.stroke(rect, &border_brush, edge_width);
            }
        }
    }

    /// Tests if the specified point overlaps the vertical scrollbar
    ///
    /// Returns false if the vertical scrollbar is not visible
    pub fn point_hits_vertical_bar(&self, port: &Viewport, pos: Point, env: &Env) -> bool {
        if !self.enabled.is_enabled(Axis::Vertical) {
            return false;
        }
        let viewport_size = port.view_size;
        let scroll_offset = port.view_origin.to_vec2();

        if let Some(mut bounds) = self.calc_vertical_bar_bounds(port, env) {
            // Stretch hitbox to edge of widget
            bounds.x1 = scroll_offset.x + viewport_size.width;
            bounds.contains(pos)
        } else {
            false
        }
    }

    /// Tests if the specified point overlaps the horizontal scrollbar
    ///
    /// Returns false if the horizontal scrollbar is not visible
    pub fn point_hits_horizontal_bar(&self, port: &Viewport, pos: Point, env: &Env) -> bool {
        if !self.enabled.is_enabled(Axis::Horizontal) {
            return false;
        }
        let viewport_size = port.view_size;
        let scroll_offset = port.view_origin.to_vec2();

        if let Some(mut bounds) = self.calc_horizontal_bar_bounds(port, env) {
            // Stretch hitbox to edge of widget
            bounds.y1 = scroll_offset.y + viewport_size.height;
            bounds.contains(pos)
        } else {
            false
        }
    }

    /// Checks if the event applies to the scroll behavior, uses it, and marks it handled
    ///
    /// Make sure to call on every event
    pub fn event(&mut self, port: &mut Viewport, ctx: &mut EventCtx, event: &Event, env: &Env) {
        let viewport_size = port.view_size;
        let content_size = port.content_size;
        let scroll_offset = port.view_origin.to_vec2();

        let scrollbar_is_hovered = match event {
            Event::MouseMove(e) | Event::MouseUp(e) | Event::MouseDown(e) => {
                let offset_pos = e.pos + scroll_offset;
                self.point_hits_vertical_bar(port, offset_pos, env)
                    || self.point_hits_horizontal_bar(port, offset_pos, env)
            }
            _ => false,
        };

        if self.are_bars_held() {
            // if we're dragging a scrollbar
            match event {
                Event::MouseMove(event) => {
                    match self.held {
                        BarHeldState::Vertical(offset) => {
                            let scale_y = viewport_size.height / content_size.height;
                            let bounds = self
                                .calc_vertical_bar_bounds(port, env)
                                .unwrap_or(Rect::ZERO);
                            let mouse_y = event.pos.y + scroll_offset.y;
                            let delta = mouse_y - bounds.y0 - offset;
                            port.pan_by(Vec2::new(0f64, (delta / scale_y).ceil()));
                            ctx.set_handled();
                        }
                        BarHeldState::Horizontal(offset) => {
                            let scale_x = viewport_size.width / content_size.width;
                            let bounds = self
                                .calc_horizontal_bar_bounds(port, env)
                                .unwrap_or(Rect::ZERO);
                            let mouse_x = event.pos.x + scroll_offset.x;
                            let delta = mouse_x - bounds.x0 - offset;
                            port.pan_by(Vec2::new((delta / scale_x).ceil(), 0f64));
                            ctx.set_handled();
                        }
                        _ => (),
                    }
                    ctx.request_paint();
                }
                Event::MouseUp(_) => {
                    self.held = BarHeldState::None;
                    ctx.set_active(false);

                    if !scrollbar_is_hovered {
                        self.hovered = BarHoveredState::None;
                        self.reset_scrollbar_fade(|d| ctx.request_timer(d), env);
                    }

                    ctx.set_handled();
                }
                _ => (), // other events are a noop
            }
        } else if scrollbar_is_hovered {
            // if we're over a scrollbar but not dragging
            match event {
                Event::MouseMove(event) => {
                    let offset_pos = event.pos + scroll_offset;
                    if self.point_hits_vertical_bar(port, offset_pos, env) {
                        self.hovered = BarHoveredState::Vertical;
                    } else if self.point_hits_horizontal_bar(port, offset_pos, env) {
                        self.hovered = BarHoveredState::Horizontal;
                    } else {
                        unreachable!();
                    }

                    self.opacity = env.get(theme::SCROLLBAR_MAX_OPACITY);
                    self.timer_id = TimerToken::INVALID; // Cancel any fade out in progress
                    ctx.request_paint();
                    ctx.set_handled();
                }
                Event::MouseDown(event) => {
                    let pos = event.pos + scroll_offset;

                    if self.point_hits_vertical_bar(port, pos, env) {
                        ctx.set_active(true);
                        self.held = BarHeldState::Vertical(
                            // The bounds must be non-empty, because the point hits the scrollbar.
                            pos.y - self.calc_vertical_bar_bounds(port, env).unwrap().y0,
                        );
                    } else if self.point_hits_horizontal_bar(port, pos, env) {
                        ctx.set_active(true);
                        self.held = BarHeldState::Horizontal(
                            // The bounds must be non-empty, because the point hits the scrollbar.
                            pos.x - self.calc_horizontal_bar_bounds(port, env).unwrap().x0,
                        );
                    } else {
                        unreachable!();
                    }

                    ctx.set_handled();
                }
                // if the mouse was downed elsewhere, moved over a scroll bar and released: noop.
                Event::MouseUp(_) => (),
                _ => unreachable!(),
            }
        } else {
            match event {
                Event::MouseMove(_) => {
                    // if we have just stopped hovering
                    if self.hovered.is_hovered() && !scrollbar_is_hovered {
                        self.hovered = BarHoveredState::None;
                        self.reset_scrollbar_fade(|d| ctx.request_timer(d), env);
                    }
                }
                Event::Timer(id) if *id == self.timer_id => {
                    // Schedule scroll bars animation
                    ctx.request_anim_frame();
                    self.timer_id = TimerToken::INVALID;
                    ctx.set_handled();
                }
                Event::AnimFrame(interval) => {
                    // Guard by the timer id being invalid, otherwise the scroll bars would fade
                    // immediately if some other widget started animating.
                    if self.timer_id == TimerToken::INVALID {
                        // Animate scroll bars opacity
                        let diff = 2.0 * (*interval as f64) * 1e-9;
                        self.opacity -= diff;
                        if self.opacity > 0.0 {
                            ctx.request_anim_frame();
                        }

                        if let Some(bounds) = self.calc_horizontal_bar_bounds(port, env) {
                            ctx.request_paint_rect(bounds - scroll_offset);
                        }
                        if let Some(bounds) = self.calc_vertical_bar_bounds(port, env) {
                            ctx.request_paint_rect(bounds - scroll_offset);
                        }
                    }
                }

                _ => (),
            }
        }
    }

    /// Applies mousewheel scrolling if the event has not already been handled
    pub fn handle_scroll(
        &mut self,
        port: &mut Viewport,
        ctx: &mut EventCtx,
        event: &Event,
        env: &Env,
    ) {
        if !ctx.is_handled() {
            if let Event::Wheel(mouse) = event {
                if port.pan_by(mouse.wheel_delta) {
                    ctx.request_paint();
                    ctx.set_handled();
                    self.reset_scrollbar_fade(|d| ctx.request_timer(d), env);
                }
            }
        }
    }

    /// Perform any necessary action prompted by a lifecycle event
    ///
    /// Make sure to call on every lifecycle event
    pub fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, env: &Env) {
        match event {
            LifeCycle::Size(_) => {
                // Show the scrollbars any time our size changes
                self.reset_scrollbar_fade(|d| ctx.request_timer(d), env);
            }
            LifeCycle::HotChanged(false) => {
                if self.hovered.is_hovered() {
                    self.hovered = BarHoveredState::None;
                    self.reset_scrollbar_fade(|d| ctx.request_timer(d), env);
                }
            }
            _ => (),
        }
    }
}

#[cfg(test)]
mod tests {
    use float_cmp::assert_approx_eq;

    use super::*;
    use crate::kurbo::Size;

    const TEST_SCROLLBAR_WIDTH: f64 = 11.0;
    const TEST_SCROLLBAR_PAD: f64 = 3.0;
    const TEST_SCROLLBAR_MIN_SIZE: f64 = 17.0;

    #[test]
    fn scrollbar_layout() {
        let mut scroll_component = ScrollComponent::new();
        scroll_component.enabled = ScrollbarsEnabled::Vertical;
        let viewport = Viewport {
            content_size: Size::new(100.0, 100.0),
            view_origin: (0.0, 25.0).into(),
            view_size: (100.0, 50.0).into(),
        };

        let scrollbar_rect = scroll_component
            .calc_vertical_bar_bounds(&viewport, &test_env())
            .unwrap();

        assert!(
            rect_contains(
                viewport.view_rect().inset(TEST_SCROLLBAR_PAD),
                scrollbar_rect
            ),
            "scrollbar should be contained by viewport"
        );
        assert_eq!(scrollbar_rect, Rect::new(86.0, 38.0, 97.0, 63.0));
    }

    #[test]
    fn scrollbar_layout_at_start() {
        let mut scroll_component = ScrollComponent::new();
        scroll_component.enabled = ScrollbarsEnabled::Vertical;
        let viewport = Viewport {
            content_size: Size::new(100.0, 100.0),
            view_origin: Point::ZERO,
            view_size: (100.0, 50.0).into(),
        };

        let scrollbar_rect = scroll_component
            .calc_vertical_bar_bounds(&viewport, &test_env())
            .unwrap();

        assert!(
            rect_contains(
                viewport.view_rect().inset(TEST_SCROLLBAR_PAD),
                scrollbar_rect
            ),
            "scrollbar should be contained by viewport"
        );
        // scrollbar should be at start of viewport
        assert_approx_eq!(
            f64,
            scrollbar_rect.y0,
            viewport.view_rect().y0 + TEST_SCROLLBAR_PAD
        );
        assert_eq!(scrollbar_rect, Rect::new(86.0, 3.0, 97.0, 28.0));
    }

    #[test]
    fn scrollbar_layout_at_end() {
        let mut scroll_component = ScrollComponent::new();
        scroll_component.enabled = ScrollbarsEnabled::Vertical;
        let viewport = Viewport {
            content_size: Size::new(100.0, 100.0),
            view_origin: (0.0, 50.0).into(),
            view_size: (100.0, 50.0).into(),
        };

        let scrollbar_rect = scroll_component
            .calc_vertical_bar_bounds(&viewport, &test_env())
            .unwrap();

        assert!(
            rect_contains(
                viewport.view_rect().inset(TEST_SCROLLBAR_PAD),
                scrollbar_rect
            ),
            "scrollbar should be contained by viewport"
        );
        // scrollbar should be at end of viewport
        assert_approx_eq!(
            f64,
            scrollbar_rect.y1,
            viewport.view_rect().y1 - TEST_SCROLLBAR_PAD
        );
        assert_eq!(scrollbar_rect, Rect::new(86.0, 72.0, 97.0, 97.0));
    }

    #[test]
    fn scrollbar_layout_change_viewport_position() {
        let mut scroll_component = ScrollComponent::new();
        scroll_component.enabled = ScrollbarsEnabled::Vertical;
        let mut viewport = Viewport {
            content_size: Size::new(100.0, 100.0),
            view_origin: (0.0, 25.0).into(),
            view_size: (100.0, 50.0).into(),
        };

        let scrollbar_rect_1 = scroll_component
            .calc_vertical_bar_bounds(&viewport, &test_env())
            .unwrap();

        viewport.view_origin += Vec2::new(0.0, 15.0);

        let scrollbar_rect_2 = scroll_component
            .calc_vertical_bar_bounds(&viewport, &test_env())
            .unwrap();

        assert_eq!(
            scrollbar_rect_1.size(),
            scrollbar_rect_2.size(),
            "moving the viewport should not change scrollbar size"
        );
    }

    #[test]
    fn scrollbar_layout_padding_for_other_bar() {
        let mut scroll_component = ScrollComponent::new();
        scroll_component.enabled = ScrollbarsEnabled::Both;
        let viewport = Viewport {
            content_size: Size::new(100.0, 100.0),
            view_origin: (0.0, 50.0).into(),
            view_size: (100.0, 50.0).into(),
        };

        let scrollbar_rect = scroll_component
            .calc_vertical_bar_bounds(&viewport, &test_env())
            .unwrap();

        assert!(
            rect_contains(
                viewport.view_rect().inset(TEST_SCROLLBAR_PAD),
                scrollbar_rect
            ),
            "scrollbar should be contained by viewport"
        );
        assert!(
            scrollbar_rect.y1 + TEST_SCROLLBAR_WIDTH <= viewport.view_rect().y1,
            "vertical scrollbar should leave space for the horizontal scrollbar when both enabled"
        );
        assert_eq!(scrollbar_rect, Rect::new(86.0, 61.0, 97.0, 86.0));
    }

    #[test]
    fn scrollbar_layout_min_bar_size() {
        let mut scroll_component = ScrollComponent::new();
        scroll_component.enabled = ScrollbarsEnabled::Vertical;
        let viewport = Viewport {
            content_size: Size::new(100.0, 1000.0),
            view_origin: (0.0, 25.0).into(),
            view_size: (100.0, 50.0).into(),
        };

        let scrollbar_rect = scroll_component
            .calc_vertical_bar_bounds(&viewport, &test_env())
            .unwrap();

        assert!(
            rect_contains(
                viewport.view_rect().inset(TEST_SCROLLBAR_PAD),
                scrollbar_rect
            ),
            "scrollbar should be contained by viewport"
        );
        // scrollbar should use SCROLLBAR_MIN_SIZE when content is much bigger than viewport
        assert_approx_eq!(f64, scrollbar_rect.height(), TEST_SCROLLBAR_MIN_SIZE);
        assert_eq!(scrollbar_rect, Rect::new(86.0, 29.0, 97.0, 46.0));
    }

    #[test]
    fn scrollbar_layout_viewport_too_small_for_min_bar_size() {
        let mut scroll_component = ScrollComponent::new();
        scroll_component.enabled = ScrollbarsEnabled::Vertical;
        let viewport = Viewport {
            content_size: Size::new(100.0, 100.0),
            view_origin: (0.0, 25.0).into(),
            view_size: (100.0, 10.0).into(),
        };

        let scrollbar_rect = scroll_component
            .calc_vertical_bar_bounds(&viewport, &test_env())
            .unwrap();

        assert!(
            rect_contains(
                viewport.view_rect().inset(TEST_SCROLLBAR_PAD),
                scrollbar_rect
            ),
            "scrollbar should be contained by viewport"
        );
        // scrollbar should fill viewport if too small for SCROLLBAR_MIN_SIZE
        assert_approx_eq!(
            f64,
            scrollbar_rect.y0,
            viewport.view_rect().y0 + TEST_SCROLLBAR_PAD
        );
        assert_approx_eq!(
            f64,
            scrollbar_rect.y1,
            viewport.view_rect().y1 - TEST_SCROLLBAR_PAD
        );
    }

    #[test]
    fn scrollbar_layout_viewport_too_small_for_bar() {
        let mut scroll_component = ScrollComponent::new();
        scroll_component.enabled = ScrollbarsEnabled::Vertical;
        let viewport = Viewport {
            content_size: Size::new(100.0, 100.0),
            view_origin: (0.0, 25.0).into(),
            view_size: (100.0, 3.0).into(),
        };

        let scrollbar_rect = scroll_component.calc_vertical_bar_bounds(&viewport, &test_env());

        assert_eq!(
            scrollbar_rect, None,
            "scrollbar should not be drawn if viewport is too small"
        );
    }

    fn rect_contains(outer: Rect, inner: Rect) -> bool {
        outer.union(inner) == outer
    }

    fn test_env() -> Env {
        Env::empty()
            .adding(theme::SCROLLBAR_WIDTH, TEST_SCROLLBAR_WIDTH)
            .adding(theme::SCROLLBAR_PAD, TEST_SCROLLBAR_PAD)
            .adding(theme::SCROLLBAR_MIN_SIZE, TEST_SCROLLBAR_MIN_SIZE)
    }
}