cranpose_ui/modifier_nodes/
clickable.rs1use 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#[derive(Clone, Copy, Debug)]
20enum ClickPress {
21 Idle,
22 Pressed(Point, PointerId),
24 Cancelled,
27}
28
29#[derive(Debug)]
32pub(crate) struct ClickLook {
33 press: Cell<ClickPress>,
34 hovers: RefCell<SmallVec<[PointerId; 2]>>,
37 indication: Cell<Indication>,
38 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 pub(crate) fn color(&self) -> Option<Color> {
65 self.indication.get().color(self.state())
66 }
67
68 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 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 fn end(&self) {
93 self.press.set(ClickPress::Idle);
94 self.hovers.borrow_mut().clear();
95 }
96}
97
98fn 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
107pub 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 pub fn new(on_click: impl Fn(Point) + 'static) -> Self {
132 Self::with_handler(Rc::new(on_click))
133 }
134
135 pub fn with_handler(on_click: Rc<dyn Fn(Point)>) -> Self {
137 Self::with_handlers(None, on_click)
138 }
139
140 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 pub fn handler(&self) -> Rc<dyn Fn(Point)> {
178 Rc::clone(&self.on_click)
179 }
180
181 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 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#[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 pub fn new(on_click: impl Fn(Point) + 'static) -> Self {
302 Self::with_handler(Rc::new(on_click))
303 }
304
305 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 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 #[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 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}