Skip to main content

cranpose_ui/modifier_nodes/
clickable.rs

1use std::{
2    cell::Cell,
3    hash::{Hash, Hasher},
4    rc::Rc,
5};
6
7use cranpose_foundation::{
8    DRAG_THRESHOLD, DelegatableNode, InvalidationKind, ModifierNode, ModifierNodeContext,
9    ModifierNodeElement, NodeCapabilities, NodeState, PointerEvent, PointerEventKind, PointerId,
10    PointerInputNode,
11};
12
13use crate::modifier::Point;
14
15/// Where a clickable's press stands.
16#[derive(Clone, Copy, Debug)]
17enum ClickPress {
18    Idle,
19    /// A pointer went down here, and the id of that pointer.
20    Pressed(Point, PointerId),
21    /// The press was cancelled, by a long press that took it among others:
22    /// its release does not click.
23    Cancelled,
24}
25
26/// Node that reports a click when a pointer goes down and up without moving farther than the drag
27/// threshold: the first pointer that goes down holds the press, and the others pass by until it
28/// lifts, so a second finger does not click, and each controller of a headset clicks with its own.
29/// Callbacks get positions in the node's local coordinates, in logical pixels.
30pub struct ClickableNode {
31    on_press: Option<Rc<dyn Fn(Point)>>,
32    on_click: Rc<dyn Fn(Point)>,
33    state: NodeState,
34    press_position: Rc<Cell<ClickPress>>,
35    cached_handler: Rc<dyn Fn(PointerEvent)>,
36}
37
38impl std::fmt::Debug for ClickableNode {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        f.debug_struct("ClickableNode").finish()
41    }
42}
43
44impl ClickableNode {
45    /// Creates a node that calls `on_click` with the position of the click.
46    pub fn new(on_click: impl Fn(Point) + 'static) -> Self {
47        Self::with_handler(Rc::new(on_click))
48    }
49
50    /// Creates a node that calls the shared callback `on_click` with the position of the click.
51    pub fn with_handler(on_click: Rc<dyn Fn(Point)>) -> Self {
52        Self::with_handlers(None, on_click)
53    }
54
55    /// Creates a node that calls `on_press`, when given, as the pointer goes down, and `on_click`
56    /// on a click. Both get the pointer position.
57    pub fn with_handlers(on_press: Option<Rc<dyn Fn(Point)>>, on_click: Rc<dyn Fn(Point)>) -> Self {
58        let press_position = Rc::new(Cell::new(ClickPress::Idle));
59        let cached_handler = Self::create_handler(
60            on_press.clone(),
61            Rc::clone(&on_click),
62            Rc::clone(&press_position),
63        );
64        Self {
65            on_press,
66            on_click,
67            state: NodeState::new(),
68            press_position,
69            cached_handler,
70        }
71    }
72
73    fn create_handler(
74        on_press: Option<Rc<dyn Fn(Point)>>,
75        on_click: Rc<dyn Fn(Point)>,
76        press_position: Rc<Cell<ClickPress>>,
77    ) -> Rc<dyn Fn(PointerEvent)> {
78        Rc::new(move |event: PointerEvent| {
79            if matches!(press_position.get(), ClickPress::Pressed(_, holder) if holder != event.id)
80            {
81                return;
82            }
83
84            if event.is_consumed() {
85                press_position.set(ClickPress::Idle);
86                return;
87            }
88
89            match event.kind {
90                PointerEventKind::Down => {
91                    press_position.set(ClickPress::Pressed(event.travelled_to(), event.id));
92                    if let Some(on_press) = on_press.as_ref() {
93                        on_press(event.position);
94                    }
95                }
96                PointerEventKind::Move => {}
97                PointerEventKind::Up => {
98                    let should_click = match press_position.replace(ClickPress::Idle) {
99                        ClickPress::Pressed(press_pos, _) => {
100                            let travelled_to = event.travelled_to();
101                            (travelled_to - press_pos).distance() <= DRAG_THRESHOLD
102                        }
103                        // A release with no press before it clicks for the
104                        // primary pointer only: another finger's release after
105                        // the first one clicked is not a click of its own.
106                        ClickPress::Idle => event.id.is_primary(),
107                        ClickPress::Cancelled => false,
108                    };
109
110                    if should_click {
111                        on_click(Point {
112                            x: event.position.x,
113                            y: event.position.y,
114                        });
115                        event.consume();
116                    }
117                }
118                PointerEventKind::Cancel => {
119                    press_position.set(ClickPress::Cancelled);
120                }
121                _ => {}
122            }
123        })
124    }
125
126    /// Returns the click callback.
127    pub fn handler(&self) -> Rc<dyn Fn(Point)> {
128        Rc::clone(&self.on_click)
129    }
130}
131
132impl DelegatableNode for ClickableNode {
133    fn node_state(&self) -> &NodeState {
134        &self.state
135    }
136}
137
138impl ModifierNode for ClickableNode {
139    fn on_attach(&mut self, context: &mut dyn ModifierNodeContext) {
140        context.invalidate(InvalidationKind::PointerInput);
141    }
142
143    fn as_pointer_input_node(&self) -> Option<&dyn PointerInputNode> {
144        Some(self)
145    }
146
147    fn as_pointer_input_node_mut(&mut self) -> Option<&mut dyn PointerInputNode> {
148        Some(self)
149    }
150}
151
152impl PointerInputNode for ClickableNode {
153    fn on_pointer_event(
154        &mut self,
155        _context: &mut dyn ModifierNodeContext,
156        event: &PointerEvent,
157    ) -> bool {
158        (self.cached_handler)(event.clone());
159        event.is_consumed()
160    }
161
162    fn hit_test(&self, _x: f32, _y: f32) -> bool {
163        true
164    }
165
166    fn pointer_input_handler(&self) -> Option<Rc<dyn Fn(PointerEvent)>> {
167        Some(Rc::clone(&self.cached_handler))
168    }
169}
170
171/// Element that creates and updates clickable nodes.
172#[derive(Clone)]
173pub struct ClickableElement {
174    on_press: Option<Rc<dyn Fn(Point)>>,
175    on_click: Rc<dyn Fn(Point)>,
176}
177
178impl ClickableElement {
179    /// Creates an element that calls `on_click` with the position of the click.
180    pub fn new(on_click: impl Fn(Point) + 'static) -> Self {
181        Self {
182            on_press: None,
183            on_click: Rc::new(on_click),
184        }
185    }
186
187    /// Creates an element that calls the shared callback `on_click` with the position of the click.
188    pub fn with_handler(on_click: Rc<dyn Fn(Point)>) -> Self {
189        Self {
190            on_press: None,
191            on_click,
192        }
193    }
194
195    /// Creates an element that calls `on_press` as the pointer goes down and `on_click` on a click.
196    /// Both get the pointer position.
197    pub fn with_handlers(on_press: Rc<dyn Fn(Point)>, on_click: Rc<dyn Fn(Point)>) -> Self {
198        Self {
199            on_press: Some(on_press),
200            on_click,
201        }
202    }
203}
204
205impl std::fmt::Debug for ClickableElement {
206    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
207        f.debug_struct("ClickableElement").finish()
208    }
209}
210
211impl PartialEq for ClickableElement {
212    fn eq(&self, _other: &Self) -> bool {
213        true
214    }
215}
216
217impl Eq for ClickableElement {}
218
219impl Hash for ClickableElement {
220    fn hash<H: Hasher>(&self, state: &mut H) {
221        "clickable".hash(state);
222    }
223}
224
225impl ModifierNodeElement for ClickableElement {
226    type Node = ClickableNode;
227
228    fn create(&self) -> Self::Node {
229        ClickableNode::with_handlers(self.on_press.clone(), Rc::clone(&self.on_click))
230    }
231
232    fn update(&self, node: &mut Self::Node) {
233        node.on_press.clone_from(&self.on_press);
234        node.on_click.clone_from(&self.on_click);
235        node.cached_handler = ClickableNode::create_handler(
236            node.on_press.clone(),
237            Rc::clone(&node.on_click),
238            Rc::clone(&node.press_position),
239        );
240    }
241
242    fn capabilities(&self) -> NodeCapabilities {
243        NodeCapabilities::POINTER_INPUT
244    }
245
246    fn always_update(&self) -> bool {
247        true
248    }
249}