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
use dioxus_core::ScopeState;
use dioxus_hooks::UseRef;
use fermi::AtomState;

#[derive(Clone)]
pub enum StateMode {
    Ref(UseRef<i32>),
    Atom(AtomState<i32>)
}

impl StateMode {
    pub fn scroll(&self, pos: i32) {
        match self {
            Self::Ref(state_ref) => state_ref.set(pos),
            Self::Atom(state_atom) => state_atom.set(pos)
        }
    }

    pub fn read(&self) -> i32 {
        match self {
            Self::Ref(state_ref) => *state_ref.read(),
            Self::Atom(state_atom) => *state_atom.current()
        }
    }
}

impl From<&UseRef<i32>> for StateMode {
    fn from(value: &UseRef<i32>) -> Self {
        StateMode::Ref(value.clone())
    }
}

impl From<&AtomState<i32>> for StateMode {
    fn from(value: &AtomState<i32>) -> Self {
        StateMode::Atom(value.clone())
    }
}

#[derive(Clone)]
pub enum ScrollController {
    Vertical(StateMode),
    Horizontal(StateMode),
    Both {
        vertical: StateMode,
        horizontal: StateMode
    }
}

impl ScrollController {
    pub fn new_vertical(mode: StateMode) -> Self {
        Self::Vertical(mode)
    }

    pub fn new_horizontal(mode: StateMode) -> Self {
        Self::Horizontal(mode)
    }

    pub fn new_both(vertical: StateMode, horizontal: StateMode) -> Self {
        Self::Both {
             vertical,
             horizontal
        }
    }

    pub fn scroll_y(&self, pos: i32) {
        match &self {
            ScrollController::Vertical(state) => state.scroll(pos),
            ScrollController::Both { vertical, .. } => vertical.scroll(pos),
            _ => {}
        }
    }

    pub fn scroll_x(&self, pos: i32) {
        match &self {
            ScrollController::Horizontal(state) => state.scroll(pos),
            ScrollController::Both { horizontal, .. } => horizontal.scroll(pos),
            _ => {}
        }
    }

    pub fn read_y(&self) -> i32 {
        match &self {
            ScrollController::Vertical(state) => state.read(),
            ScrollController::Both { vertical, .. } => vertical.read(),
            _ => 0
        }
    }
    
    pub fn read_x(&self) -> i32 {
        match &self {
            ScrollController::Horizontal(state) => state.read(),
            ScrollController::Both { horizontal, .. } => horizontal.read(),
            _ => 0
        }
    }
}

pub fn use_scroll_controller(cx: &ScopeState, cb: impl FnOnce() -> ScrollController) -> &ScrollController {
    cx.use_hook(cb)
}