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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
use std::collections::VecDeque;
use std::time::Instant;

use dioxus::prelude::*;
use freya_elements::elements as dioxus_elements;
use freya_elements::events::{touch::TouchPhase, TouchEvent};

/// Distance between the first tap and the second tap in `DoubleTap` gesture.
const DOUBLE_TAP_DISTANCE: f64 = 100.0;

/// Maximum time between the start of the first tap and the start of the second tap in a `DoubleTap` gesture.
const DOUBLE_TAP_TIMEOUT: u128 = 300; // 300ms

/// Minimum time between the end of the first time to the start of the second tap in a `DoubleTap` gesture.
const DOUBLE_TAP_MIN: u128 = 40; // 40ms

/// In-memory events queue maximum size.
const MAX_EVENTS_QUEUE: usize = 20;

/// Gesture emitted by the `GestureArea` component.
#[derive(Debug, PartialEq, Eq)]
pub enum Gesture {
    TapUp,
    TapDown,
    DoubleTap,
}

/// [`GestureArea`] component properties.
#[derive(Props)]
pub struct GestureAreaProps<'a> {
    /// Inner children for the GestureArea.
    pub children: Element<'a>,
    /// Handler for the `ongesture` event.
    pub ongesture: EventHandler<'a, Gesture>,
}

type EventsQueue = VecDeque<(Instant, TouchEvent)>;

/// `GestureArea` component.
///
/// # Props
/// See [`GestureAreaProps`].
///
/// # Example
///
/// ```rust
/// # use freya::prelude::*;
/// fn app(cx: Scope) -> Element {
///    let gesture = use_state(cx, || "Tap here".to_string());
///    render!(
///        GestureArea {
///            ongesture: move |g| gesture.set(format!("{g:?}")),
///            label {
///                "{gesture}"
///            }
///        }
///    )
/// }
/// ```
///
#[allow(non_snake_case)]
pub fn GestureArea<'a>(cx: Scope<'a, GestureAreaProps<'a>>) -> Element {
    let touch_events = use_ref::<EventsQueue>(cx, VecDeque::new);

    use_effect(cx, touch_events, move |_| {
        // Keep the touch events queue under a certain size
        if touch_events.read().len() > MAX_EVENTS_QUEUE {
            touch_events.write_silent().pop_front();
        }

        // Find the first event with the `target_phase` that happened before the `start_time`
        let find_previous_event = |start_time: &Instant,
                                   events: &EventsQueue,
                                   target_phase: TouchPhase|
         -> Option<(Instant, TouchEvent)> {
            let mut start = false;
            for (time, event) in events.iter().rev() {
                if time == start_time {
                    start = true;
                    continue;
                }
                if event.phase == target_phase && start {
                    return Some((*time, event.clone()));
                }
            }
            None
        };

        let touch_events = touch_events.read();

        // Process the most recent event
        let event = touch_events.iter().last();

        if let Some((time, event)) = event {
            let phase = event.get_touch_phase();

            match phase {
                TouchPhase::Started => {
                    // TapDown
                    cx.props.ongesture.call(Gesture::TapDown);

                    let last_ended_event =
                        find_previous_event(time, &touch_events, TouchPhase::Ended);
                    let last_started_event =
                        find_previous_event(time, &touch_events, TouchPhase::Started);

                    // DoubleTap
                    if let Some(((ended_time, ended_event), (started_time, _))) =
                        last_ended_event.zip(last_started_event)
                    {
                        // Has the latest `touchend` event went too far?
                        let is_ended_close = event
                            .get_screen_coordinates()
                            .distance_to(ended_event.get_screen_coordinates())
                            < DOUBLE_TAP_DISTANCE;
                        // Is the latest `touchend` mature enough?
                        let is_ended_mature = ended_time.elapsed().as_millis() >= DOUBLE_TAP_MIN;

                        // Hast the latest `touchstart` event expired?
                        let is_started_recent =
                            started_time.elapsed().as_millis() <= DOUBLE_TAP_TIMEOUT;

                        if is_ended_close && is_ended_mature && is_started_recent {
                            cx.props.ongesture.call(Gesture::DoubleTap);
                        }
                    }
                }
                TouchPhase::Ended => {
                    // TapUp
                    cx.props.ongesture.call(Gesture::TapUp);
                }
                _ => {}
            }
        }

        async move {}
    });

    let ontouchcancel = |e: TouchEvent| {
        touch_events.write().push_back((Instant::now(), e));
    };

    let ontouchend = |e: TouchEvent| {
        touch_events.write().push_back((Instant::now(), e));
    };

    let ontouchmove = |e: TouchEvent| {
        touch_events.write().push_back((Instant::now(), e));
    };

    let ontouchstart = |e: TouchEvent| {
        touch_events.write().push_back((Instant::now(), e));
    };

    render!(
        rect {
            ontouchcancel: ontouchcancel,
            ontouchend: ontouchend,
            ontouchmove: ontouchmove,
            ontouchstart: ontouchstart,
            &cx.props.children
        }
    )
}

#[cfg(test)]
mod test {
    use std::time::Duration;

    use freya::prelude::*;
    use freya_elements::events::touch::TouchPhase;
    use freya_testing::{launch_test, FreyaEvent};
    use tokio::time::sleep;

    use crate::gesture_area::DOUBLE_TAP_MIN;

    /// This test simulates a `DoubleTap` gesture in this order:
    /// 1. Touch start
    /// 2. Touch end
    /// 3. Wait 40ms
    /// 4. Touch start
    #[tokio::test]
    pub async fn double_tap() {
        fn dobule_tap_app(cx: Scope) -> Element {
            let value = use_state(cx, || "EMPTY".to_string());

            let ongesture = |e: Gesture| {
                value.set(format!("{e:?}"));
            };

            render!(
                GestureArea {
                    ongesture: ongesture,
                    "{value}"
                }
            )
        }

        let mut utils = launch_test(dobule_tap_app);

        // Initial state
        utils.wait_for_update().await;

        assert_eq!(utils.root().get(0).get(0).text(), Some("EMPTY"));

        utils.push_event(FreyaEvent::Touch {
            name: "touchstart".to_string(),
            location: (1.0, 1.0).into(),
            phase: TouchPhase::Started,
            finger_id: 0,
            force: None,
        });

        utils.push_event(FreyaEvent::Touch {
            name: "touchend".to_string(),
            location: (1.0, 1.0).into(),
            phase: TouchPhase::Ended,
            finger_id: 0,
            force: None,
        });

        utils.wait_for_update().await;
        utils.wait_for_update().await;

        sleep(Duration::from_millis(DOUBLE_TAP_MIN as u64)).await;

        utils.push_event(FreyaEvent::Touch {
            name: "touchstart".to_string(),
            location: (1.0, 1.0).into(),
            phase: TouchPhase::Started,
            finger_id: 0,
            force: None,
        });

        utils.wait_for_update().await;
        utils.wait_for_update().await;

        assert_eq!(utils.root().get(0).get(0).text(), Some("DoubleTap"));
    }

    /// Simulates `TapUp` and `TapDown` gestures.
    #[tokio::test]
    pub async fn tap_up_down() {
        fn tap_up_down_app(cx: Scope) -> Element {
            let value = use_state(cx, || "EMPTY".to_string());

            let ongesture = |e: Gesture| {
                value.set(format!("{e:?}"));
            };

            render!(
                GestureArea {
                    ongesture: ongesture,
                    "{value}"
                }
            )
        }

        let mut utils = launch_test(tap_up_down_app);

        // Initial state
        utils.wait_for_update().await;

        assert_eq!(utils.root().get(0).get(0).text(), Some("EMPTY"));

        utils.push_event(FreyaEvent::Touch {
            name: "touchstart".to_string(),
            location: (1.0, 1.0).into(),
            phase: TouchPhase::Started,
            finger_id: 0,
            force: None,
        });

        utils.wait_for_update().await;
        utils.wait_for_update().await;

        assert_eq!(utils.root().get(0).get(0).text(), Some("TapDown"));

        utils.push_event(FreyaEvent::Touch {
            name: "touchend".to_string(),
            location: (1.0, 1.0).into(),
            phase: TouchPhase::Ended,
            finger_id: 0,
            force: None,
        });

        utils.wait_for_update().await;
        utils.wait_for_update().await;

        assert_eq!(utils.root().get(0).get(0).text(), Some("TapUp"));
    }
}