Skip to main content

cranpose_ui/modifier_nodes/
clickable.rs

1use std::{
2    cell::{Cell, RefCell},
3    hash::{Hash, Hasher},
4    rc::Rc,
5};
6
7use cranpose_core::NodeId;
8use cranpose_foundation::{
9    DRAG_THRESHOLD, DelegatableNode, InvalidationKind, ModifierNode, ModifierNodeContext,
10    ModifierNodeElement, NodeCapabilities, NodeState, PointerEvent, PointerEventKind, PointerId,
11    PointerInputNode, PointerSource,
12};
13use cranpose_ui_graphics::Color;
14use smallvec::SmallVec;
15
16use crate::{Indication, IndicationState, modifier::Point};
17
18/// Where a clickable's press stands.
19#[derive(Clone, Copy, Debug)]
20enum ClickPress {
21    Idle,
22    /// A pointer went down here, and the id of that pointer.
23    Pressed(Point, PointerId),
24    /// The press was cancelled, by a long press that took it among others:
25    /// its release does not click.
26    Cancelled,
27}
28
29// What a clickable shares between its pointer handler and the draw of its
30// indication.
31#[derive(Debug)]
32pub(crate) struct ClickLook {
33    press: Cell<ClickPress>,
34    // The pointers that rest over the control. Two hands of a headset can
35    // rest on one control.
36    hovers: RefCell<SmallVec<[PointerId; 2]>>,
37    indication: Cell<Indication>,
38    // The layout node whose draw shows the indication, once the node is attached
39    node: Cell<Option<NodeId>>,
40}
41
42impl ClickLook {
43    fn new(indication: Indication) -> Self {
44        Self {
45            press: Cell::new(ClickPress::Idle),
46            hovers: RefCell::new(SmallVec::new()),
47            indication: Cell::new(indication),
48            node: Cell::new(None),
49        }
50    }
51
52    fn state(&self) -> IndicationState {
53        if matches!(self.press.get(), ClickPress::Pressed(..)) {
54            IndicationState::Pressed
55        } else if self.hovers.borrow().is_empty() {
56            IndicationState::Idle
57        } else {
58            IndicationState::Hovered
59        }
60    }
61
62    // The color that the indication lays over the control now, or `None`
63    // while it shows nothing.
64    pub(crate) fn color(&self) -> Option<Color> {
65        self.indication.get().color(self.state())
66    }
67
68    // A finger rests on nothing: a touch's enter comes with its press and no
69    // exit follows its lift.
70    fn hover(&self, event: &PointerEvent) {
71        match event.kind {
72            PointerEventKind::Enter if event.source != PointerSource::Touch => {
73                let mut hovers = self.hovers.borrow_mut();
74                if !hovers.contains(&event.id) {
75                    hovers.push(event.id);
76                }
77            }
78            PointerEventKind::Exit => self.hovers.borrow_mut().retain(|id| *id != event.id),
79            _ => {}
80        }
81    }
82
83    // Draws the control again when its indication changed and shows something.
84    fn redraw_after(&self, before: IndicationState) {
85        if self.state() == before || self.indication.get() == Indication::NONE {
86            return;
87        }
88        redraw(self.node.get());
89    }
90
91    // The node leaves: nothing of its interaction stays for a later attach.
92    fn end(&self) {
93        self.press.set(ClickPress::Idle);
94        self.hovers.borrow_mut().clear();
95    }
96}
97
98// Draws `node` again, in the app context that is active: outside one no frame draws.
99fn redraw(node: Option<NodeId>) {
100    if let Some(node) = node
101        && crate::render_state::current_app_context().is_some()
102    {
103        crate::render_state::schedule_draw_repass(node);
104    }
105}
106
107/// Node that reports a click when a pointer goes down and up without moving farther than the drag
108/// threshold: the first pointer that goes down holds the press, and the others pass by until it
109/// lifts, so a second finger does not click, and each controller of a headset clicks with its own.
110/// A press that travels past the threshold ends at once: the control stops showing it pressed, and
111/// its release does not click. Callbacks get positions in the node's local coordinates, in logical
112/// pixels.
113///
114/// The node draws its [`Indication`] over the control while a pointer rests on it or presses it.
115pub struct ClickableNode {
116    on_press: Option<Rc<dyn Fn(Point)>>,
117    on_click: Rc<dyn Fn(Point)>,
118    state: NodeState,
119    look: Rc<ClickLook>,
120    cached_handler: Rc<dyn Fn(PointerEvent)>,
121}
122
123impl std::fmt::Debug for ClickableNode {
124    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
125        f.debug_struct("ClickableNode").finish()
126    }
127}
128
129impl ClickableNode {
130    /// Creates a node that calls `on_click` with the position of the click.
131    pub fn new(on_click: impl Fn(Point) + 'static) -> Self {
132        Self::with_handler(Rc::new(on_click))
133    }
134
135    /// Creates a node that calls the shared callback `on_click` with the position of the click.
136    pub fn with_handler(on_click: Rc<dyn Fn(Point)>) -> Self {
137        Self::with_handlers(None, on_click)
138    }
139
140    /// Creates a node that calls `on_press`, when given, as the pointer goes down, and `on_click`
141    /// on a click. Both get the pointer position.
142    pub fn with_handlers(on_press: Option<Rc<dyn Fn(Point)>>, on_click: Rc<dyn Fn(Point)>) -> Self {
143        Self::with_indication(on_press, on_click, Indication::default())
144    }
145
146    fn with_indication(
147        on_press: Option<Rc<dyn Fn(Point)>>,
148        on_click: Rc<dyn Fn(Point)>,
149        indication: Indication,
150    ) -> Self {
151        let look = Rc::new(ClickLook::new(indication));
152        let cached_handler =
153            Self::create_handler(on_press.clone(), Rc::clone(&on_click), Rc::clone(&look));
154        Self {
155            on_press,
156            on_click,
157            state: NodeState::new(),
158            look,
159            cached_handler,
160        }
161    }
162
163    fn create_handler(
164        on_press: Option<Rc<dyn Fn(Point)>>,
165        on_click: Rc<dyn Fn(Point)>,
166        look: Rc<ClickLook>,
167    ) -> Rc<dyn Fn(PointerEvent)> {
168        Rc::new(move |event: PointerEvent| {
169            let before = look.state();
170            look.hover(&event);
171            handle_press(&look.press, on_press.as_deref(), &*on_click, &event);
172            look.redraw_after(before);
173        })
174    }
175
176    /// Returns the click callback.
177    pub fn handler(&self) -> Rc<dyn Fn(Point)> {
178        Rc::clone(&self.on_click)
179    }
180
181    /// The state that the node's indication shows.
182    pub fn indication_state(&self) -> IndicationState {
183        self.look.state()
184    }
185
186    pub(crate) fn look(&self) -> Rc<ClickLook> {
187        Rc::clone(&self.look)
188    }
189}
190
191fn handle_press(
192    press: &Cell<ClickPress>,
193    on_press: Option<&dyn Fn(Point)>,
194    on_click: &dyn Fn(Point),
195    event: &PointerEvent,
196) {
197    if matches!(press.get(), ClickPress::Pressed(_, holder) if holder != event.id) {
198        return;
199    }
200
201    if event.is_consumed() {
202        press.set(ClickPress::Idle);
203        return;
204    }
205
206    match event.kind {
207        PointerEventKind::Down => {
208            press.set(ClickPress::Pressed(event.travelled_to(), event.id));
209            if let Some(on_press) = on_press {
210                on_press(event.position);
211            }
212        }
213        PointerEventKind::Move => {
214            if let ClickPress::Pressed(origin, _) = press.get()
215                && (event.travelled_to() - origin).distance() > DRAG_THRESHOLD
216            {
217                press.set(ClickPress::Cancelled);
218            }
219        }
220        PointerEventKind::Up => {
221            let should_click = match press.replace(ClickPress::Idle) {
222                ClickPress::Pressed(origin, _) => {
223                    (event.travelled_to() - origin).distance() <= DRAG_THRESHOLD
224                }
225                // A release with no press before it clicks for the primary pointer only: another
226                // finger's release after the first one clicked is not a click of its own.
227                ClickPress::Idle => event.id.is_primary(),
228                ClickPress::Cancelled => false,
229            };
230
231            if should_click {
232                on_click(Point {
233                    x: event.position.x,
234                    y: event.position.y,
235                });
236                event.consume();
237            }
238        }
239        PointerEventKind::Cancel => {
240            press.set(ClickPress::Cancelled);
241        }
242        _ => {}
243    }
244}
245
246impl DelegatableNode for ClickableNode {
247    fn node_state(&self) -> &NodeState {
248        &self.state
249    }
250}
251
252impl ModifierNode for ClickableNode {
253    fn on_attach(&mut self, context: &mut dyn ModifierNodeContext) {
254        self.look.node.set(context.node_id());
255        context.invalidate(InvalidationKind::PointerInput);
256    }
257
258    fn on_detach(&mut self) {
259        self.look.end();
260        self.look.node.set(None);
261    }
262
263    fn as_pointer_input_node(&self) -> Option<&dyn PointerInputNode> {
264        Some(self)
265    }
266
267    fn as_pointer_input_node_mut(&mut self) -> Option<&mut dyn PointerInputNode> {
268        Some(self)
269    }
270}
271
272impl PointerInputNode for ClickableNode {
273    fn on_pointer_event(
274        &mut self,
275        _context: &mut dyn ModifierNodeContext,
276        event: &PointerEvent,
277    ) -> bool {
278        (self.cached_handler)(event.clone());
279        event.is_consumed()
280    }
281
282    fn hit_test(&self, _x: f32, _y: f32) -> bool {
283        true
284    }
285
286    fn pointer_input_handler(&self) -> Option<Rc<dyn Fn(PointerEvent)>> {
287        Some(Rc::clone(&self.cached_handler))
288    }
289}
290
291/// Element that creates and updates clickable nodes.
292#[derive(Clone)]
293pub struct ClickableElement {
294    on_press: Option<Rc<dyn Fn(Point)>>,
295    on_click: Rc<dyn Fn(Point)>,
296    indication: Indication,
297}
298
299impl ClickableElement {
300    /// Creates an element that calls `on_click` with the position of the click.
301    pub fn new(on_click: impl Fn(Point) + 'static) -> Self {
302        Self::with_handler(Rc::new(on_click))
303    }
304
305    /// Creates an element that calls the shared callback `on_click` with the position of the click.
306    pub fn with_handler(on_click: Rc<dyn Fn(Point)>) -> Self {
307        Self {
308            on_press: None,
309            on_click,
310            indication: Indication::default(),
311        }
312    }
313
314    /// Creates an element that calls `on_press` as the pointer goes down and `on_click` on a click.
315    /// Both get the pointer position.
316    pub fn with_handlers(on_press: Rc<dyn Fn(Point)>, on_click: Rc<dyn Fn(Point)>) -> Self {
317        Self {
318            on_press: Some(on_press),
319            ..Self::with_handler(on_click)
320        }
321    }
322
323    /// The element with `indication` in place of the default one.
324    #[must_use]
325    pub fn indication(self, indication: Indication) -> Self {
326        Self { indication, ..self }
327    }
328}
329
330impl std::fmt::Debug for ClickableElement {
331    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
332        f.debug_struct("ClickableElement").finish()
333    }
334}
335
336impl PartialEq for ClickableElement {
337    fn eq(&self, _other: &Self) -> bool {
338        true
339    }
340}
341
342impl Eq for ClickableElement {}
343
344impl Hash for ClickableElement {
345    fn hash<H: Hasher>(&self, state: &mut H) {
346        "clickable".hash(state);
347    }
348}
349
350impl ModifierNodeElement for ClickableElement {
351    type Node = ClickableNode;
352
353    fn create(&self) -> Self::Node {
354        ClickableNode::with_indication(
355            self.on_press.clone(),
356            Rc::clone(&self.on_click),
357            self.indication,
358        )
359    }
360
361    fn update(&self, node: &mut Self::Node) {
362        node.on_press.clone_from(&self.on_press);
363        node.on_click.clone_from(&self.on_click);
364        if node.look.indication.replace(self.indication) != self.indication {
365            redraw(node.look.node.get());
366        }
367        node.cached_handler = ClickableNode::create_handler(
368            node.on_press.clone(),
369            Rc::clone(&node.on_click),
370            Rc::clone(&node.look),
371        );
372    }
373
374    // A clickable that shows no indication draws nothing, so its chain keeps
375    // the draws it had without one.
376    fn capabilities(&self) -> NodeCapabilities {
377        if self.indication == Indication::NONE {
378            NodeCapabilities::POINTER_INPUT
379        } else {
380            NodeCapabilities::POINTER_INPUT | NodeCapabilities::DRAW
381        }
382    }
383
384    fn always_update(&self) -> bool {
385        true
386    }
387}