blit_widget/interact/
focus.rs1use blit::{ContactSource, Context, InteractCx, Phase, input::MouseButton};
2
3#[derive(Clone, Copy, Debug)]
5pub struct Interact;
6
7impl<C: Context> blit::Interact<C> for Interact {
8 type State = ();
9 type Response = bool;
10
11 fn update(&self, _: &mut (), cx: &mut InteractCx<'_, C::Scalar>) -> bool {
12 if cx.contacts().any(|contact| {
13 contact.free
14 && match contact.source {
15 ContactSource::Mouse(MouseButton::Primary) => contact.phase == Phase::Started,
16 ContactSource::Touch(_) => contact.phase == Phase::Ended,
17 ContactSource::Mouse(_) => false,
18 }
19 }) {
20 cx.focus();
21 }
22 cx.focused()
23 }
24}
25
26#[cfg(test)]
27mod tests {
28 use std::cell::Cell;
29
30 use blit::{
31 Rect, Scope, Tree, Ui,
32 input::{
33 Input,
34 TouchPhase::{Down, Move, Up},
35 },
36 };
37
38 use crate::{
39 interact,
40 layout::rect,
41 test::{TestContext, pointer, step},
42 };
43
44 #[test]
45 fn focus_follows_presses_and_taps() {
46 let left = 1000;
47 let right = 1001;
48 let mut tree = Tree::<TestContext>::default();
49 let change_focus = Cell::new(false);
50 let clear_focus = Cell::new(false);
51 let build = |mut ui: Ui<'_, TestContext>| {
52 if clear_focus.replace(false) {
53 ui.clear_focus();
54 }
55 let mut ui = ui.layout(rect::new());
56 let mut left = ui.child_in(Scope::ROOT, left).item(Rect::new(0.0, 0.0, 100.0, 200.0));
57 let left_focused = left.interact(interact::focus());
58 if change_focus.replace(false) {
59 let target = left.resolve(Scope::ROOT, right);
60 left.node(target).focus();
61 }
62 drop(left);
63 let mut right = ui
64 .child_in(Scope::ROOT, right)
65 .item(Rect::new(100.0, 0.0, 100.0, 200.0));
66 (left_focused, right.interact(interact::focus()))
67 };
68 let mut next = |input| step(&mut tree, input, build);
69 next(Input::None);
70 assert_eq!(next(pointer(None, Down, 10.0, 10.0)), (true, false));
71 next(pointer(None, Up, 10.0, 10.0));
72 change_focus.set(true);
74 assert_eq!(next(Input::None), (true, false));
75 assert_eq!(next(Input::None), (false, true));
76 clear_focus.set(true);
78 next(pointer(Some(1), Down, 10.0, 10.0));
79 next(pointer(Some(1), Move, 30.0, 10.0));
80 assert_eq!(next(pointer(Some(1), Up, 30.0, 10.0)), (true, false));
81 next(pointer(Some(1), Down, 110.0, 10.0));
82 assert_eq!(next(pointer(Some(1), Up, 110.0, 10.0)), (false, true));
83 }
84}