Skip to main content

cranpose_ui/
text_selection.rs

1//! Native-grade text selection primitives for `BasicTextField`.
2//!
3//! This module holds the pure, unit-tested building blocks the text field uses
4//! to offer Android/iOS-style selection: tap-count classification, word and
5//! line/paragraph boundary detection, and the geometry of the draggable
6//! teardrop selection handles (their shapes, their hit regions, and the
7//! selection math that a handle drag produces).
8//!
9//! Keeping these as free functions makes the touch behavior testable without a
10//! renderer and keeps `TextFieldModifierNode` focused on wiring.
11
12use cranpose_ui_graphics::Rect;
13
14/// How many consecutive taps a press represents, mirroring the platform text
15/// selection gestures: one tap places the cursor, two select the word, three
16/// select the line/paragraph.
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18pub enum TapCount {
19    Single,
20    Double,
21    Triple,
22}
23
24impl TapCount {
25    /// The 1-based tap number, capped at three.
26    pub fn as_u8(self) -> u8 {
27        match self {
28            TapCount::Single => 1,
29            TapCount::Double => 2,
30            TapCount::Triple => 3,
31        }
32    }
33}
34
35impl TryFrom<u8> for TapCount {
36    type Error = ();
37
38    fn try_from(value: u8) -> Result<Self, Self::Error> {
39        match value {
40            1 => Ok(TapCount::Single),
41            2 => Ok(TapCount::Double),
42            3 => Ok(TapCount::Triple),
43            _ => Err(()),
44        }
45    }
46}
47
48/// Maximum time between taps that still counts as a multi-tap, in milliseconds.
49pub const MULTI_TAP_TIMEOUT_MS: u128 = 500;
50
51/// Maximum distance (px) between consecutive taps that still counts as a
52/// multi-tap. A tap that lands far from the previous one starts a fresh
53/// single tap even if it arrives quickly, matching Android's `ViewConfiguration`
54/// double-tap slop behavior.
55pub const MULTI_TAP_SLOP_PX: f32 = 24.0;
56
57/// Classifies a press into a tap count from the previous tap's count, the time
58/// since it, and the distance from it.
59///
60/// `previous` is the last tap's `(count, x, y)` or `None` for the first tap.
61/// A tap escalates the count (single -> double -> triple, then wraps back to
62/// single) only when it lands within both the timeout and the slop radius;
63/// otherwise it restarts at a single tap.
64pub fn classify_tap(
65    previous: Option<(TapCount, f32, f32)>,
66    elapsed_ms: u128,
67    x: f32,
68    y: f32,
69    timeout_ms: u128,
70    slop_px: f32,
71) -> TapCount {
72    let Some((prev_count, prev_x, prev_y)) = previous else {
73        return TapCount::Single;
74    };
75    let within_time = elapsed_ms <= timeout_ms;
76    let dx = x - prev_x;
77    let dy = y - prev_y;
78    let within_slop = dx * dx + dy * dy <= slop_px * slop_px;
79    if !within_time || !within_slop {
80        return TapCount::Single;
81    }
82    match prev_count {
83        TapCount::Single => TapCount::Double,
84        TapCount::Double => TapCount::Triple,
85        // A fourth tap cycles back to a single cursor placement.
86        TapCount::Triple => TapCount::Single,
87    }
88}
89
90/// Returns the byte range `[start, end)` of the line/paragraph containing
91/// `pos`, delimited by `\n` (the newline itself is excluded from the range).
92///
93/// Used for triple-tap line/paragraph selection. Byte offsets always land on
94/// `char` boundaries because `\n` is a single-byte ASCII character.
95pub fn find_line_boundaries(text: &str, pos: usize) -> (usize, usize) {
96    let pos = pos.min(text.len());
97    let start = text[..pos].rfind('\n').map(|i| i + 1).unwrap_or(0);
98    let end = text[pos..]
99        .find('\n')
100        .map(|i| pos + i)
101        .unwrap_or(text.len());
102    (start, end)
103}
104
105/// Which selection handle a teardrop represents.
106#[derive(Clone, Copy, Debug, PartialEq, Eq)]
107pub enum HandleKind {
108    /// The blinking-cursor handle shown for a collapsed selection: a teardrop
109    /// whose tip points up at the cursor, centered under it.
110    Cursor,
111    /// The start (leftmost) selection handle: tip at the top-right, bulb below-left.
112    SelectionStart,
113    /// The end (rightmost) selection handle: tip at the top-left, bulb below-right.
114    SelectionEnd,
115}
116
117/// Radius of a selection/cursor handle bulb in px (Android uses ~11dp).
118pub const HANDLE_RADIUS: f32 = 8.0;
119
120/// Extra hit-test slop (px) around a handle so it is easy to grab with a finger.
121pub const HANDLE_TOUCH_SLOP: f32 = 12.0;
122
123/// SVG path data for a handle teardrop whose tip sits at `(tip_x, tip_y)`.
124///
125/// The tip is anchored at the text edge (the cursor position or a selection
126/// endpoint at the line's bottom) and the rounded bulb hangs below it, so the
127/// caller positions the handle by passing the on-screen anchor point.
128pub fn handle_path_data(kind: HandleKind, tip_x: f32, tip_y: f32, radius: f32) -> String {
129    let r = radius.max(0.0);
130    let cy = tip_y + r; // bulb center y
131    match kind {
132        HandleKind::Cursor => {
133            // Symmetric teardrop: tip up, full circular bulb below.
134            format!(
135                "M {tip_x} {tip_y} L {left} {cy} A {r} {r} 0 1 0 {right} {cy} Z",
136                left = tip_x - r,
137                right = tip_x + r,
138            )
139        }
140        HandleKind::SelectionStart => {
141            // Tip at the endpoint, bulb hanging down and to the LEFT.
142            format!(
143                "M {tip_x} {tip_y} L {tip_x} {cy} A {r} {r} 0 1 0 {left} {tip_y} Z",
144                left = tip_x - r,
145            )
146        }
147        HandleKind::SelectionEnd => {
148            // Tip at the endpoint, bulb hanging down and to the RIGHT.
149            format!(
150                "M {tip_x} {tip_y} L {right} {tip_y} A {r} {r} 0 1 0 {tip_x} {cy} Z",
151                right = tip_x + r,
152            )
153        }
154    }
155}
156
157/// The axis-aligned hit region for a handle, expanded by touch slop, used to
158/// decide whether a pointer-down grabbed a handle.
159pub fn handle_hit_rect(kind: HandleKind, tip_x: f32, tip_y: f32, radius: f32, slop: f32) -> Rect {
160    let r = radius.max(0.0);
161    let slop = slop.max(0.0);
162    // Horizontal span of the bulb relative to the tip depends on the handle side.
163    let (left, right) = match kind {
164        HandleKind::Cursor => (tip_x - r, tip_x + r),
165        HandleKind::SelectionStart => (tip_x - 2.0 * r, tip_x + r),
166        HandleKind::SelectionEnd => (tip_x - r, tip_x + 2.0 * r),
167    };
168    Rect {
169        x: left - slop,
170        y: tip_y - slop,
171        width: (right - left) + 2.0 * slop,
172        height: 2.0 * r + 2.0 * slop,
173    }
174}
175
176/// Returns the handle nearest to `(x, y)` whose slop-expanded hit region
177/// contains the point, or `None` when the point misses every handle.
178///
179/// `handles` lists the currently drawn handles as `(kind, tip_x, tip_y)`.
180pub fn hit_test_handles(
181    handles: &[(HandleKind, f32, f32)],
182    x: f32,
183    y: f32,
184    radius: f32,
185    slop: f32,
186) -> Option<HandleKind> {
187    let mut best: Option<(HandleKind, f32)> = None;
188    for &(kind, tip_x, tip_y) in handles {
189        let rect = handle_hit_rect(kind, tip_x, tip_y, radius, slop);
190        let inside =
191            x >= rect.x && x <= rect.x + rect.width && y >= rect.y && y <= rect.y + rect.height;
192        if !inside {
193            continue;
194        }
195        let cx = tip_x;
196        let cy = tip_y + radius;
197        let dist_sq = (x - cx) * (x - cx) + (y - cy) * (y - cy);
198        if best
199            .map(|(_, best_dist)| dist_sq < best_dist)
200            .unwrap_or(true)
201        {
202            best = Some((kind, dist_sq));
203        }
204    }
205    best.map(|(kind, _)| kind)
206}
207
208/// Computes the selection `(min, max)` that results from dragging one handle to
209/// a new text `offset`, keeping the opposite (fixed) edge anchored.
210///
211/// Dragging never lets the two edges cross: a dragged start clamps to just
212/// before the fixed end, and a dragged end clamps to just after the fixed
213/// start, so the selection keeps at least one selected unit.
214pub fn selection_after_handle_drag(
215    dragged: HandleKind,
216    fixed_edge: usize,
217    dragged_offset: usize,
218    text_len: usize,
219) -> (usize, usize) {
220    let fixed = fixed_edge.min(text_len);
221    let dragged_offset = dragged_offset.min(text_len);
222    match dragged {
223        HandleKind::SelectionStart => {
224            let start = dragged_offset.min(fixed.saturating_sub(1));
225            (start, fixed)
226        }
227        HandleKind::SelectionEnd => {
228            let end = dragged_offset.max(fixed + 1).min(text_len);
229            (fixed, end)
230        }
231        // The cursor handle just moves the collapsed caret.
232        HandleKind::Cursor => (dragged_offset, dragged_offset),
233    }
234}
235
236#[cfg(test)]
237mod tests {
238    use super::*;
239
240    #[test]
241    fn tap_classification_escalates_within_time_and_slop() {
242        assert_eq!(
243            classify_tap(None, 0, 10.0, 10.0, 500, 24.0),
244            TapCount::Single
245        );
246        assert_eq!(
247            classify_tap(
248                Some((TapCount::Single, 10.0, 10.0)),
249                100,
250                11.0,
251                12.0,
252                500,
253                24.0
254            ),
255            TapCount::Double
256        );
257        assert_eq!(
258            classify_tap(
259                Some((TapCount::Double, 10.0, 10.0)),
260                100,
261                11.0,
262                12.0,
263                500,
264                24.0
265            ),
266            TapCount::Triple
267        );
268        // A fourth quick tap wraps back to a single cursor placement.
269        assert_eq!(
270            classify_tap(
271                Some((TapCount::Triple, 10.0, 10.0)),
272                100,
273                11.0,
274                12.0,
275                500,
276                24.0
277            ),
278            TapCount::Single
279        );
280    }
281
282    #[test]
283    fn tap_classification_resets_past_timeout_or_slop() {
284        // Too slow: restarts.
285        assert_eq!(
286            classify_tap(
287                Some((TapCount::Single, 10.0, 10.0)),
288                600,
289                10.0,
290                10.0,
291                500,
292                24.0
293            ),
294            TapCount::Single
295        );
296        // Too far: restarts even though it is quick.
297        assert_eq!(
298            classify_tap(
299                Some((TapCount::Single, 10.0, 10.0)),
300                50,
301                100.0,
302                10.0,
303                500,
304                24.0
305            ),
306            TapCount::Single
307        );
308    }
309
310    #[test]
311    fn line_boundaries_span_between_newlines() {
312        let text = "first line\nsecond line\nthird";
313        // Inside the second line.
314        assert_eq!(find_line_boundaries(text, 15), (11, 22));
315        // Start of the first line.
316        assert_eq!(find_line_boundaries(text, 0), (0, 10));
317        // Inside the last (newline-terminated-absent) line.
318        assert_eq!(find_line_boundaries(text, 25), (23, text.len()));
319    }
320
321    #[test]
322    fn line_boundaries_handle_unicode_and_empty_lines() {
323        let text = "\u{00e9}\u{00e8}\n\n\u{4e2d}\u{6587}";
324        // Empty middle line: start == end at the byte after the first newline.
325        let (start, end) = find_line_boundaries(text, "\u{00e9}\u{00e8}\n".len());
326        assert_eq!(start, end);
327        // Last line spans the two CJK characters.
328        let last = find_line_boundaries(text, text.len());
329        assert_eq!(&text[last.0..last.1], "\u{4e2d}\u{6587}");
330    }
331
332    #[test]
333    fn handle_path_is_non_empty_and_contains_the_tip() {
334        for kind in [
335            HandleKind::Cursor,
336            HandleKind::SelectionStart,
337            HandleKind::SelectionEnd,
338        ] {
339            let data = handle_path_data(kind, 40.0, 20.0, HANDLE_RADIUS);
340            let path = cranpose_ui_graphics::VectorPath::parse(&data)
341                .expect("handle path must be valid SVG");
342            assert!(!path.is_empty(), "{kind:?} handle must have geometry");
343            let bounds = path.bounds();
344            // The tip (40, 20) must lie within the shape's bounds.
345            assert!(bounds.x <= 40.0 + 0.5 && bounds.x + bounds.width >= 40.0 - 0.5);
346            assert!(bounds.y <= 20.0 + 0.5);
347            // The bulb hangs below the tip.
348            assert!(bounds.y + bounds.height >= 20.0 + HANDLE_RADIUS);
349        }
350    }
351
352    #[test]
353    fn handle_hit_rect_covers_tip_and_bulb_with_slop() {
354        let rect = handle_hit_rect(
355            HandleKind::Cursor,
356            40.0,
357            20.0,
358            HANDLE_RADIUS,
359            HANDLE_TOUCH_SLOP,
360        );
361        // Tip and bulb center are inside.
362        assert!(rect.x <= 40.0 && 40.0 <= rect.x + rect.width);
363        assert!(rect.y <= 20.0 && 20.0 + HANDLE_RADIUS <= rect.y + rect.height);
364        // Slop widens the region beyond the bulb radius.
365        assert!(rect.width >= 2.0 * HANDLE_RADIUS + 2.0 * HANDLE_TOUCH_SLOP - 0.01);
366    }
367
368    #[test]
369    fn hit_test_prefers_the_nearest_handle() {
370        let handles = [
371            (HandleKind::SelectionStart, 20.0, 20.0),
372            (HandleKind::SelectionEnd, 120.0, 20.0),
373        ];
374        // Near the start handle bulb.
375        assert_eq!(
376            hit_test_handles(&handles, 20.0, 28.0, HANDLE_RADIUS, HANDLE_TOUCH_SLOP),
377            Some(HandleKind::SelectionStart)
378        );
379        // Near the end handle bulb.
380        assert_eq!(
381            hit_test_handles(&handles, 120.0, 28.0, HANDLE_RADIUS, HANDLE_TOUCH_SLOP),
382            Some(HandleKind::SelectionEnd)
383        );
384        // Far from both.
385        assert_eq!(
386            hit_test_handles(&handles, 300.0, 300.0, HANDLE_RADIUS, HANDLE_TOUCH_SLOP),
387            None
388        );
389    }
390
391    #[test]
392    fn handle_drag_keeps_edges_from_crossing() {
393        // Dragging the end handle left past the start clamps to start+1.
394        assert_eq!(
395            selection_after_handle_drag(HandleKind::SelectionEnd, 5, 2, 20),
396            (5, 6)
397        );
398        // Dragging the end handle right extends normally.
399        assert_eq!(
400            selection_after_handle_drag(HandleKind::SelectionEnd, 5, 12, 20),
401            (5, 12)
402        );
403        // Dragging the start handle right past the end clamps to end-1.
404        assert_eq!(
405            selection_after_handle_drag(HandleKind::SelectionStart, 8, 10, 20),
406            (7, 8)
407        );
408        // Dragging the start handle left extends normally.
409        assert_eq!(
410            selection_after_handle_drag(HandleKind::SelectionStart, 8, 3, 20),
411            (3, 8)
412        );
413        // The cursor handle moves a collapsed caret.
414        assert_eq!(
415            selection_after_handle_drag(HandleKind::Cursor, 4, 9, 20),
416            (9, 9)
417        );
418    }
419}