logo
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
//! Navigate an endless amount of content with a scrollbar.
use crate::event::{self, Event};
use crate::layout;
use crate::mouse;
use crate::overlay;
use crate::renderer;
use crate::touch;
use crate::widget::Column;
use crate::{
    Alignment, Background, Clipboard, Color, Element, Layout, Length, Padding,
    Point, Rectangle, Shell, Size, Vector, Widget,
};

use std::{f32, u32};

pub use iced_style::scrollable::StyleSheet;

pub mod style {
    //! The styles of a [`Scrollable`].
    //!
    //! [`Scrollable`]: crate::widget::Scrollable
    pub use iced_style::scrollable::{Scrollbar, Scroller};
}

/// A widget that can vertically display an infinite amount of content with a
/// scrollbar.
#[allow(missing_debug_implementations)]
pub struct Scrollable<'a, Message, Renderer> {
    state: &'a mut State,
    height: Length,
    max_height: u32,
    scrollbar_width: u16,
    scrollbar_margin: u16,
    scroller_width: u16,
    content: Column<'a, Message, Renderer>,
    on_scroll: Option<Box<dyn Fn(f32) -> Message + 'a>>,
    style_sheet: Box<dyn StyleSheet + 'a>,
}

impl<'a, Message, Renderer: crate::Renderer> Scrollable<'a, Message, Renderer> {
    /// Creates a new [`Scrollable`] with the given [`State`].
    pub fn new(state: &'a mut State) -> Self {
        Scrollable {
            state,
            height: Length::Shrink,
            max_height: u32::MAX,
            scrollbar_width: 10,
            scrollbar_margin: 0,
            scroller_width: 10,
            content: Column::new(),
            on_scroll: None,
            style_sheet: Default::default(),
        }
    }

    /// Sets the vertical spacing _between_ elements.
    ///
    /// Custom margins per element do not exist in Iced. You should use this
    /// method instead! While less flexible, it helps you keep spacing between
    /// elements consistent.
    pub fn spacing(mut self, units: u16) -> Self {
        self.content = self.content.spacing(units);
        self
    }

    /// Sets the [`Padding`] of the [`Scrollable`].
    pub fn padding<P: Into<Padding>>(mut self, padding: P) -> Self {
        self.content = self.content.padding(padding);
        self
    }

    /// Sets the width of the [`Scrollable`].
    pub fn width(mut self, width: Length) -> Self {
        self.content = self.content.width(width);
        self
    }

    /// Sets the height of the [`Scrollable`].
    pub fn height(mut self, height: Length) -> Self {
        self.height = height;
        self
    }

    /// Sets the maximum width of the [`Scrollable`].
    pub fn max_width(mut self, max_width: u32) -> Self {
        self.content = self.content.max_width(max_width);
        self
    }

    /// Sets the maximum height of the [`Scrollable`] in pixels.
    pub fn max_height(mut self, max_height: u32) -> Self {
        self.max_height = max_height;
        self
    }

    /// Sets the horizontal alignment of the contents of the [`Scrollable`] .
    pub fn align_items(mut self, align_items: Alignment) -> Self {
        self.content = self.content.align_items(align_items);
        self
    }

    /// Sets the scrollbar width of the [`Scrollable`] .
    /// Silently enforces a minimum value of 1.
    pub fn scrollbar_width(mut self, scrollbar_width: u16) -> Self {
        self.scrollbar_width = scrollbar_width.max(1);
        self
    }

    /// Sets the scrollbar margin of the [`Scrollable`] .
    pub fn scrollbar_margin(mut self, scrollbar_margin: u16) -> Self {
        self.scrollbar_margin = scrollbar_margin;
        self
    }

    /// Sets the scroller width of the [`Scrollable`] .
    ///
    /// It silently enforces a minimum value of 1.
    pub fn scroller_width(mut self, scroller_width: u16) -> Self {
        self.scroller_width = scroller_width.max(1);
        self
    }

    /// Sets a function to call when the [`Scrollable`] is scrolled.
    ///
    /// The function takes the new relative offset of the [`Scrollable`]
    /// (e.g. `0` means top, while `1` means bottom).
    pub fn on_scroll(mut self, f: impl Fn(f32) -> Message + 'static) -> Self {
        self.on_scroll = Some(Box::new(f));
        self
    }

    /// Sets the style of the [`Scrollable`] .
    pub fn style(
        mut self,
        style_sheet: impl Into<Box<dyn StyleSheet + 'a>>,
    ) -> Self {
        self.style_sheet = style_sheet.into();
        self
    }

    /// Adds an element to the [`Scrollable`].
    pub fn push<E>(mut self, child: E) -> Self
    where
        E: Into<Element<'a, Message, Renderer>>,
    {
        self.content = self.content.push(child);
        self
    }
}

/// Computes the layout of a [`Scrollable`].
pub fn layout<Renderer>(
    renderer: &Renderer,
    limits: &layout::Limits,
    width: Length,
    height: Length,
    layout_content: impl FnOnce(&Renderer, &layout::Limits) -> layout::Node,
) -> layout::Node {
    let limits = limits.width(width).height(height);

    let child_limits = layout::Limits::new(
        Size::new(limits.min().width, 0.0),
        Size::new(limits.max().width, f32::INFINITY),
    );

    let content = layout_content(renderer, &child_limits);
    let size = limits.resolve(content.size());

    layout::Node::with_children(size, vec![content])
}

/// Processes an [`Event`] and updates the [`State`] of a [`Scrollable`]
/// accordingly.
pub fn update<Message>(
    state: &mut State,
    event: Event,
    layout: Layout<'_>,
    cursor_position: Point,
    clipboard: &mut dyn Clipboard,
    shell: &mut Shell<'_, Message>,
    scrollbar_width: u16,
    scrollbar_margin: u16,
    scroller_width: u16,
    on_scroll: &Option<Box<dyn Fn(f32) -> Message + '_>>,
    update_content: impl FnOnce(
        Event,
        Layout<'_>,
        Point,
        &mut dyn Clipboard,
        &mut Shell<'_, Message>,
    ) -> event::Status,
) -> event::Status {
    let bounds = layout.bounds();
    let is_mouse_over = bounds.contains(cursor_position);

    let content = layout.children().next().unwrap();
    let content_bounds = content.bounds();

    let scrollbar = scrollbar(
        state,
        scrollbar_width,
        scrollbar_margin,
        scroller_width,
        bounds,
        content_bounds,
    );
    let is_mouse_over_scrollbar = scrollbar
        .as_ref()
        .map(|scrollbar| scrollbar.is_mouse_over(cursor_position))
        .unwrap_or(false);

    let event_status = {
        let cursor_position = if is_mouse_over && !is_mouse_over_scrollbar {
            Point::new(
                cursor_position.x,
                cursor_position.y + state.offset(bounds, content_bounds) as f32,
            )
        } else {
            // TODO: Make `cursor_position` an `Option<Point>` so we can encode
            // cursor availability.
            // This will probably happen naturally once we add multi-window
            // support.
            Point::new(cursor_position.x, -1.0)
        };

        update_content(
            event.clone(),
            content,
            cursor_position,
            clipboard,
            shell,
        )
    };

    if let event::Status::Captured = event_status {
        return event::Status::Captured;
    }

    if is_mouse_over {
        match event {
            Event::Mouse(mouse::Event::WheelScrolled { delta }) => {
                match delta {
                    mouse::ScrollDelta::Lines { y, .. } => {
                        // TODO: Configurable speed (?)
                        state.scroll(y * 60.0, bounds, content_bounds);
                    }
                    mouse::ScrollDelta::Pixels { y, .. } => {
                        state.scroll(y, bounds, content_bounds);
                    }
                }

                notify_on_scroll(
                    state,
                    on_scroll,
                    bounds,
                    content_bounds,
                    shell,
                );

                return event::Status::Captured;
            }
            Event::Touch(event) => {
                match event {
                    touch::Event::FingerPressed { .. } => {
                        state.scroll_box_touched_at = Some(cursor_position);
                    }
                    touch::Event::FingerMoved { .. } => {
                        if let Some(scroll_box_touched_at) =
                            state.scroll_box_touched_at
                        {
                            let delta =
                                cursor_position.y - scroll_box_touched_at.y;

                            state.scroll(delta, bounds, content_bounds);

                            state.scroll_box_touched_at = Some(cursor_position);

                            notify_on_scroll(
                                state,
                                on_scroll,
                                bounds,
                                content_bounds,
                                shell,
                            );
                        }
                    }
                    touch::Event::FingerLifted { .. }
                    | touch::Event::FingerLost { .. } => {
                        state.scroll_box_touched_at = None;
                    }
                }

                return event::Status::Captured;
            }
            _ => {}
        }
    }

    if state.is_scroller_grabbed() {
        match event {
            Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left))
            | Event::Touch(touch::Event::FingerLifted { .. })
            | Event::Touch(touch::Event::FingerLost { .. }) => {
                state.scroller_grabbed_at = None;

                return event::Status::Captured;
            }
            Event::Mouse(mouse::Event::CursorMoved { .. })
            | Event::Touch(touch::Event::FingerMoved { .. }) => {
                if let (Some(scrollbar), Some(scroller_grabbed_at)) =
                    (scrollbar, state.scroller_grabbed_at)
                {
                    state.scroll_to(
                        scrollbar.scroll_percentage(
                            scroller_grabbed_at,
                            cursor_position,
                        ),
                        bounds,
                        content_bounds,
                    );

                    notify_on_scroll(
                        state,
                        on_scroll,
                        bounds,
                        content_bounds,
                        shell,
                    );

                    return event::Status::Captured;
                }
            }
            _ => {}
        }
    } else if is_mouse_over_scrollbar {
        match event {
            Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left))
            | Event::Touch(touch::Event::FingerPressed { .. }) => {
                if let Some(scrollbar) = scrollbar {
                    if let Some(scroller_grabbed_at) =
                        scrollbar.grab_scroller(cursor_position)
                    {
                        state.scroll_to(
                            scrollbar.scroll_percentage(
                                scroller_grabbed_at,
                                cursor_position,
                            ),
                            bounds,
                            content_bounds,
                        );

                        state.scroller_grabbed_at = Some(scroller_grabbed_at);

                        notify_on_scroll(
                            state,
                            on_scroll,
                            bounds,
                            content_bounds,
                            shell,
                        );

                        return event::Status::Captured;
                    }
                }
            }
            _ => {}
        }
    }

    event::Status::Ignored
}

/// Computes the current [`mouse::Interaction`] of a [`Scrollable`].
pub fn mouse_interaction(
    state: &State,
    layout: Layout<'_>,
    cursor_position: Point,
    scrollbar_width: u16,
    scrollbar_margin: u16,
    scroller_width: u16,
    content_interaction: impl FnOnce(
        Layout<'_>,
        Point,
        &Rectangle,
    ) -> mouse::Interaction,
) -> mouse::Interaction {
    let bounds = layout.bounds();
    let content_layout = layout.children().next().unwrap();
    let content_bounds = content_layout.bounds();
    let scrollbar = scrollbar(
        state,
        scrollbar_width,
        scrollbar_margin,
        scroller_width,
        bounds,
        content_bounds,
    );

    let is_mouse_over = bounds.contains(cursor_position);
    let is_mouse_over_scrollbar = scrollbar
        .as_ref()
        .map(|scrollbar| scrollbar.is_mouse_over(cursor_position))
        .unwrap_or(false);

    if is_mouse_over_scrollbar || state.is_scroller_grabbed() {
        mouse::Interaction::Idle
    } else {
        let offset = state.offset(bounds, content_bounds);

        let cursor_position = if is_mouse_over && !is_mouse_over_scrollbar {
            Point::new(cursor_position.x, cursor_position.y + offset as f32)
        } else {
            Point::new(cursor_position.x, -1.0)
        };

        content_interaction(
            content_layout,
            cursor_position,
            &Rectangle {
                y: bounds.y + offset as f32,
                ..bounds
            },
        )
    }
}

/// Draws a [`Scrollable`].
pub fn draw<Renderer>(
    state: &State,
    renderer: &mut Renderer,
    layout: Layout<'_>,
    cursor_position: Point,
    scrollbar_width: u16,
    scrollbar_margin: u16,
    scroller_width: u16,
    style_sheet: &dyn StyleSheet,
    draw_content: impl FnOnce(&mut Renderer, Layout<'_>, Point, &Rectangle),
) where
    Renderer: crate::Renderer,
{
    let bounds = layout.bounds();
    let content_layout = layout.children().next().unwrap();
    let content_bounds = content_layout.bounds();
    let offset = state.offset(bounds, content_bounds);
    let scrollbar = scrollbar(
        state,
        scrollbar_width,
        scrollbar_margin,
        scroller_width,
        bounds,
        content_bounds,
    );

    let is_mouse_over = bounds.contains(cursor_position);
    let is_mouse_over_scrollbar = scrollbar
        .as_ref()
        .map(|scrollbar| scrollbar.is_mouse_over(cursor_position))
        .unwrap_or(false);

    let cursor_position = if is_mouse_over && !is_mouse_over_scrollbar {
        Point::new(cursor_position.x, cursor_position.y + offset as f32)
    } else {
        Point::new(cursor_position.x, -1.0)
    };

    if let Some(scrollbar) = scrollbar {
        renderer.with_layer(bounds, |renderer| {
            renderer.with_translation(
                Vector::new(0.0, -(offset as f32)),
                |renderer| {
                    draw_content(
                        renderer,
                        content_layout,
                        cursor_position,
                        &Rectangle {
                            y: bounds.y + offset as f32,
                            ..bounds
                        },
                    );
                },
            );
        });

        let style = if state.is_scroller_grabbed() {
            style_sheet.dragging()
        } else if is_mouse_over_scrollbar {
            style_sheet.hovered()
        } else {
            style_sheet.active()
        };

        let is_scrollbar_visible =
            style.background.is_some() || style.border_width > 0.0;

        renderer.with_layer(
            Rectangle {
                width: bounds.width + 2.0,
                height: bounds.height + 2.0,
                ..bounds
            },
            |renderer| {
                if is_scrollbar_visible {
                    renderer.fill_quad(
                        renderer::Quad {
                            bounds: scrollbar.bounds,
                            border_radius: style.border_radius,
                            border_width: style.border_width,
                            border_color: style.border_color,
                        },
                        style
                            .background
                            .unwrap_or(Background::Color(Color::TRANSPARENT)),
                    );
                }

                if is_mouse_over
                    || state.is_scroller_grabbed()
                    || is_scrollbar_visible
                {
                    renderer.fill_quad(
                        renderer::Quad {
                            bounds: scrollbar.scroller.bounds,
                            border_radius: style.scroller.border_radius,
                            border_width: style.scroller.border_width,
                            border_color: style.scroller.border_color,
                        },
                        style.scroller.color,
                    );
                }
            },
        );
    } else {
        draw_content(
            renderer,
            content_layout,
            cursor_position,
            &Rectangle {
                y: bounds.y + offset as f32,
                ..bounds
            },
        );
    }
}

fn scrollbar(
    state: &State,
    scrollbar_width: u16,
    scrollbar_margin: u16,
    scroller_width: u16,
    bounds: Rectangle,
    content_bounds: Rectangle,
) -> Option<Scrollbar> {
    let offset = state.offset(bounds, content_bounds);

    if content_bounds.height > bounds.height {
        let outer_width =
            scrollbar_width.max(scroller_width) + 2 * scrollbar_margin;

        let outer_bounds = Rectangle {
            x: bounds.x + bounds.width - outer_width as f32,
            y: bounds.y,
            width: outer_width as f32,
            height: bounds.height,
        };

        let scrollbar_bounds = Rectangle {
            x: bounds.x + bounds.width
                - f32::from(outer_width / 2 + scrollbar_width / 2),
            y: bounds.y,
            width: scrollbar_width as f32,
            height: bounds.height,
        };

        let ratio = bounds.height / content_bounds.height;
        let scroller_height = bounds.height * ratio;
        let y_offset = offset as f32 * ratio;

        let scroller_bounds = Rectangle {
            x: bounds.x + bounds.width
                - f32::from(outer_width / 2 + scroller_width / 2),
            y: scrollbar_bounds.y + y_offset,
            width: scroller_width as f32,
            height: scroller_height,
        };

        Some(Scrollbar {
            outer_bounds,
            bounds: scrollbar_bounds,
            scroller: Scroller {
                bounds: scroller_bounds,
            },
        })
    } else {
        None
    }
}

fn notify_on_scroll<Message>(
    state: &State,
    on_scroll: &Option<Box<dyn Fn(f32) -> Message + '_>>,
    bounds: Rectangle,
    content_bounds: Rectangle,
    shell: &mut Shell<'_, Message>,
) {
    if content_bounds.height <= bounds.height {
        return;
    }

    if let Some(on_scroll) = on_scroll {
        shell.publish(on_scroll(
            state.offset.absolute(bounds, content_bounds)
                / (content_bounds.height - bounds.height),
        ));
    }
}

impl<'a, Message, Renderer> Widget<Message, Renderer>
    for Scrollable<'a, Message, Renderer>
where
    Renderer: crate::Renderer,
{
    fn width(&self) -> Length {
        Widget::<Message, Renderer>::width(&self.content)
    }

    fn height(&self) -> Length {
        self.height
    }

    fn layout(
        &self,
        renderer: &Renderer,
        limits: &layout::Limits,
    ) -> layout::Node {
        layout(
            renderer,
            limits,
            Widget::<Message, Renderer>::width(self),
            self.height,
            |renderer, limits| self.content.layout(renderer, limits),
        )
    }

    fn on_event(
        &mut self,
        event: Event,
        layout: Layout<'_>,
        cursor_position: Point,
        renderer: &Renderer,
        clipboard: &mut dyn Clipboard,
        shell: &mut Shell<'_, Message>,
    ) -> event::Status {
        update(
            &mut self.state,
            event,
            layout,
            cursor_position,
            clipboard,
            shell,
            self.scrollbar_width,
            self.scrollbar_margin,
            self.scroller_width,
            &self.on_scroll,
            |event, layout, cursor_position, clipboard, shell| {
                self.content.on_event(
                    event,
                    layout,
                    cursor_position,
                    renderer,
                    clipboard,
                    shell,
                )
            },
        )
    }

    fn mouse_interaction(
        &self,
        layout: Layout<'_>,
        cursor_position: Point,
        _viewport: &Rectangle,
        renderer: &Renderer,
    ) -> mouse::Interaction {
        mouse_interaction(
            &self.state,
            layout,
            cursor_position,
            self.scrollbar_width,
            self.scrollbar_margin,
            self.scroller_width,
            |layout, cursor_position, viewport| {
                self.content.mouse_interaction(
                    layout,
                    cursor_position,
                    viewport,
                    renderer,
                )
            },
        )
    }

    fn draw(
        &self,
        renderer: &mut Renderer,
        style: &renderer::Style,
        layout: Layout<'_>,
        cursor_position: Point,
        _viewport: &Rectangle,
    ) {
        draw(
            &self.state,
            renderer,
            layout,
            cursor_position,
            self.scrollbar_width,
            self.scrollbar_margin,
            self.scroller_width,
            self.style_sheet.as_ref(),
            |renderer, layout, cursor_position, viewport| {
                self.content.draw(
                    renderer,
                    style,
                    layout,
                    cursor_position,
                    viewport,
                )
            },
        )
    }

    fn overlay(
        &mut self,
        layout: Layout<'_>,
        renderer: &Renderer,
    ) -> Option<overlay::Element<'_, Message, Renderer>> {
        let Self { content, state, .. } = self;

        content
            .overlay(layout.children().next().unwrap(), renderer)
            .map(|overlay| {
                let bounds = layout.bounds();
                let content_layout = layout.children().next().unwrap();
                let content_bounds = content_layout.bounds();
                let offset = state.offset(bounds, content_bounds);

                overlay.translate(Vector::new(0.0, -(offset as f32)))
            })
    }
}

/// The local state of a [`Scrollable`].
#[derive(Debug, Clone, Copy)]
pub struct State {
    scroller_grabbed_at: Option<f32>,
    scroll_box_touched_at: Option<Point>,
    offset: Offset,
}

impl Default for State {
    fn default() -> Self {
        Self {
            scroller_grabbed_at: None,
            scroll_box_touched_at: None,
            offset: Offset::Absolute(0.0),
        }
    }
}

/// The local state of a [`Scrollable`].
#[derive(Debug, Clone, Copy)]
enum Offset {
    Absolute(f32),
    Relative(f32),
}

impl Offset {
    fn absolute(self, bounds: Rectangle, content_bounds: Rectangle) -> f32 {
        match self {
            Self::Absolute(absolute) => {
                let hidden_content =
                    (content_bounds.height - bounds.height).max(0.0);

                absolute.min(hidden_content)
            }
            Self::Relative(percentage) => {
                ((content_bounds.height - bounds.height) * percentage).max(0.0)
            }
        }
    }
}

impl State {
    /// Creates a new [`State`] with the scrollbar located at the top.
    pub fn new() -> Self {
        State::default()
    }

    /// Apply a scrolling offset to the current [`State`], given the bounds of
    /// the [`Scrollable`] and its contents.
    pub fn scroll(
        &mut self,
        delta_y: f32,
        bounds: Rectangle,
        content_bounds: Rectangle,
    ) {
        if bounds.height >= content_bounds.height {
            return;
        }

        self.offset = Offset::Absolute(
            (self.offset.absolute(bounds, content_bounds) - delta_y)
                .max(0.0)
                .min((content_bounds.height - bounds.height) as f32),
        );
    }

    /// Scrolls the [`Scrollable`] to a relative amount.
    ///
    /// `0` represents scrollbar at the top, while `1` represents scrollbar at
    /// the bottom.
    pub fn scroll_to(
        &mut self,
        percentage: f32,
        bounds: Rectangle,
        content_bounds: Rectangle,
    ) {
        self.snap_to(percentage);
        self.unsnap(bounds, content_bounds);
    }

    /// Snaps the scroll position to a relative amount.
    ///
    /// `0` represents scrollbar at the top, while `1` represents scrollbar at
    /// the bottom.
    pub fn snap_to(&mut self, percentage: f32) {
        self.offset = Offset::Relative(percentage.max(0.0).min(1.0));
    }

    /// Unsnaps the current scroll position, if snapped, given the bounds of the
    /// [`Scrollable`] and its contents.
    pub fn unsnap(&mut self, bounds: Rectangle, content_bounds: Rectangle) {
        self.offset =
            Offset::Absolute(self.offset.absolute(bounds, content_bounds));
    }

    /// Returns the current scrolling offset of the [`State`], given the bounds
    /// of the [`Scrollable`] and its contents.
    pub fn offset(&self, bounds: Rectangle, content_bounds: Rectangle) -> u32 {
        self.offset.absolute(bounds, content_bounds) as u32
    }

    /// Returns whether the scroller is currently grabbed or not.
    pub fn is_scroller_grabbed(&self) -> bool {
        self.scroller_grabbed_at.is_some()
    }

    /// Returns whether the scroll box is currently touched or not.
    pub fn is_scroll_box_touched(&self) -> bool {
        self.scroll_box_touched_at.is_some()
    }
}

/// The scrollbar of a [`Scrollable`].
#[derive(Debug)]
struct Scrollbar {
    /// The outer bounds of the scrollable, including the [`Scrollbar`] and
    /// [`Scroller`].
    outer_bounds: Rectangle,

    /// The bounds of the [`Scrollbar`].
    bounds: Rectangle,

    /// The bounds of the [`Scroller`].
    scroller: Scroller,
}

impl Scrollbar {
    fn is_mouse_over(&self, cursor_position: Point) -> bool {
        self.outer_bounds.contains(cursor_position)
    }

    fn grab_scroller(&self, cursor_position: Point) -> Option<f32> {
        if self.outer_bounds.contains(cursor_position) {
            Some(if self.scroller.bounds.contains(cursor_position) {
                (cursor_position.y - self.scroller.bounds.y)
                    / self.scroller.bounds.height
            } else {
                0.5
            })
        } else {
            None
        }
    }

    fn scroll_percentage(
        &self,
        grabbed_at: f32,
        cursor_position: Point,
    ) -> f32 {
        (cursor_position.y
            - self.bounds.y
            - self.scroller.bounds.height * grabbed_at)
            / (self.bounds.height - self.scroller.bounds.height)
    }
}

/// The handle of a [`Scrollbar`].
#[derive(Debug, Clone, Copy)]
struct Scroller {
    /// The bounds of the [`Scroller`].
    bounds: Rectangle,
}

impl<'a, Message, Renderer> From<Scrollable<'a, Message, Renderer>>
    for Element<'a, Message, Renderer>
where
    Renderer: 'a + crate::Renderer,
    Message: 'a,
{
    fn from(
        scrollable: Scrollable<'a, Message, Renderer>,
    ) -> Element<'a, Message, Renderer> {
        Element::new(scrollable)
    }
}