Skip to main content

strata_ui/
scrollbar.rs

1//! Declarative `<ScrollView>` and `<Scrollbar>` Components with Kinetic Physics.
2
3#![allow(non_snake_case)]
4
5use strata_dom::{NodeBlueprint, View};
6use strata_macro::{component, rsx};
7pub use strata_render::kinetic_scroll::{KineticScrollController, ScrollAxis};
8
9/// Scrollbar track orientation.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
11pub enum ScrollbarOrientation {
12    #[default]
13    Vertical,
14    Horizontal,
15}
16
17/// Interactive Sleek Semi-Transparent Scrollbar.
18#[component]
19pub fn Scrollbar(
20    orientation: Option<ScrollbarOrientation>,
21    scroll_ratio: Option<f32>,
22    thumb_ratio: Option<f32>,
23    opacity: Option<f32>,
24    class: Option<&'static str>,
25) -> View {
26    let ori = orientation.unwrap_or_default();
27    let ratio = scroll_ratio.unwrap_or(0.0).clamp(0.0, 1.0);
28    let t_ratio = thumb_ratio.unwrap_or(0.2).clamp(0.05, 1.0);
29    let alpha = opacity.unwrap_or(1.0).clamp(0.0, 1.0);
30    let custom = class.unwrap_or("");
31
32    match ori {
33        ScrollbarOrientation::Vertical => {
34            let thumb_pct = t_ratio * 100.0;
35            let travel_pct = (1.0 - t_ratio) * ratio * 100.0;
36            rsx! {
37                <div class={format!("absolute right-1 top-1 bottom-1 w-2 rounded-full pointer-events-none transition-opacity duration-200 {}", custom)}>
38                    <div class={format!("w-full rounded-full bg-neutral-600/60 hover:bg-neutral-500/80 transition-colors pointer-events-auto cursor-pointer")} />
39                </div>
40            }
41        }
42        ScrollbarOrientation::Horizontal => {
43            rsx! {
44                <div class={format!("absolute left-1 right-1 bottom-1 h-2 rounded-full pointer-events-none transition-opacity duration-200 {}", custom)}>
45                    <div class={format!("h-full rounded-full bg-neutral-600/60 hover:bg-neutral-500/80 transition-colors pointer-events-auto cursor-pointer")} />
46                </div>
47            }
48        }
49    }
50}
51
52/// Smooth Kinetic Inertial Scroll View Container.
53#[component]
54pub fn ScrollView(
55    children: Option<Vec<NodeBlueprint>>,
56    class: Option<&'static str>,
57    show_scrollbar: Option<bool>,
58) -> View {
59    let custom = class.unwrap_or("");
60    let with_bar = show_scrollbar.unwrap_or(true);
61
62    rsx! {
63        <div class={format!("relative overflow-hidden flex flex-col {}", custom)}>
64            <div class="flex-1 overflow-hidden">
65                {children.unwrap_or_default()}
66            </div>
67            {if with_bar {
68                rsx! { <Scrollbar orientation={ScrollbarOrientation::Vertical} /> }
69            } else {
70                rsx! { <></> }
71            }}
72        </div>
73    }
74}