cranpose-ui 0.1.118

UI primitives for Cranpose
Documentation
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
//! Native-grade text selection primitives for `BasicTextField`.
//!
//! This module holds the pure, unit-tested building blocks the text field uses
//! to offer Android/iOS-style selection: tap-count classification, word and
//! line/paragraph boundary detection, and the geometry of the draggable
//! teardrop selection handles (their shapes, their hit regions, and the
//! selection math that a handle drag produces).
//!
//! Keeping these as free functions makes the touch behavior testable without a
//! renderer and keeps `TextFieldModifierNode` focused on wiring.

/// Maximum time between taps that still counts as a multi-tap, in milliseconds.
pub const MULTI_TAP_TIMEOUT_MS: u128 = 500;

/// Maximum distance (px) between consecutive taps that still counts as a
/// multi-tap. A tap that lands far from the previous one starts a fresh
/// single tap even if it arrives quickly, matching Android's `ViewConfiguration`
/// double-tap slop behavior.
pub const MULTI_TAP_SLOP_PX: f32 = 24.0;

/// The unit of text a tap gesture selects, growing with the tap count the way
/// mature text editors do (Android `TextView`, iOS `UITextView`, VS Code):
///
/// * 1 tap → [`Caret`](SelectionGranularity::Caret) (place the cursor);
/// * 2 taps → [`Word`](SelectionGranularity::Word);
/// * 3 taps → [`Line`](SelectionGranularity::Line);
/// * 4 taps → [`Paragraph`](SelectionGranularity::Paragraph);
/// * 5+ taps → cycle back through word → line → paragraph.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SelectionGranularity {
    /// Collapsed caret (a single tap places the cursor).
    Caret,
    /// The word under the tap.
    Word,
    /// The line under the tap (delimited by `\n`).
    Line,
    /// The paragraph under the tap (delimited by blank lines).
    Paragraph,
}

/// Classifies a press into a 1-based tap count from the previous tap's count,
/// the time since it, and the distance from it.
///
/// `previous` is the last tap's `(count, x, y)` or `None` for the first tap. A
/// tap increments the count only when it lands within both the timeout and the
/// slop radius; otherwise it restarts at `1`. The count is **not** wrapped here
/// — the granularity mapping ([`tap_selection_granularity`]) cycles instead, so
/// the field can keep escalating (word → line → paragraph → word …) as long as
/// the finger keeps tapping in place.
pub fn classify_tap_count(
    previous: Option<(u8, f32, f32)>,
    elapsed_ms: u128,
    x: f32,
    y: f32,
    timeout_ms: u128,
    slop_px: f32,
) -> u8 {
    let Some((prev_count, prev_x, prev_y)) = previous else {
        return 1;
    };
    let within_time = elapsed_ms <= timeout_ms;
    let dx = x - prev_x;
    let dy = y - prev_y;
    let within_slop = dx * dx + dy * dy <= slop_px * slop_px;
    if !within_time || !within_slop {
        return 1;
    }
    prev_count.saturating_add(1)
}

/// Resolves the effective tap count for a press, folding in the "tap inside an
/// existing selection" gesture so it drives the same word → line → paragraph
/// granularity ladder ([`tap_selection_granularity`]) as a rapid multi-tap.
///
/// Inputs:
/// * `raw_tap_count` — the time-and-slop-gated multi-tap count from
///   [`classify_tap_count`] (2+ means a genuine rapid multi-tap in progress);
/// * `previous_count` — the effective count the *previous* press resolved to
///   (the field remembers it as its click count);
/// * `tap_in_selection` — the press landed inside the current, non-collapsed
///   selection;
/// * `repeat_in_place` — the press landed within the multi-tap slop of the
///   previous press, **independent of timing** (the same spot, tapped again).
///
/// Behavior:
/// * a rapid multi-tap (`raw_tap_count >= 2`) uses its own running count, so
///   double→word, triple→line, … keep working exactly as before;
/// * a lone tap inside a selection selects the word under the finger, and each
///   further tap at the *same spot* climbs the ladder (word → line → paragraph →
///   word …) even when it arrives slowly (the multi-tap timeout has lapsed) —
///   users tap-then-look-then-tap, so the growth is keyed on location, not time;
/// * a lone tap at a *new* spot inside the selection re-grabs that word (resets
///   to word); and
/// * a lone tap outside any selection is left as-is (a single tap → caret).
pub fn resolve_selection_tap_count(
    raw_tap_count: u8,
    previous_count: u8,
    tap_in_selection: bool,
    repeat_in_place: bool,
) -> u8 {
    if raw_tap_count >= 2 {
        raw_tap_count
    } else if tap_in_selection {
        if repeat_in_place {
            previous_count.max(1).saturating_add(1)
        } else {
            2
        }
    } else {
        raw_tap_count
    }
}

/// Maps a 1-based tap count to the granularity it selects.
///
/// A single tap places the caret; two taps select the word, three the line,
/// four the paragraph, and every further tap cycles back through
/// word → line → paragraph so a resting finger keeps toggling between the three
/// range granularities (matching desktop editors and iOS).
pub fn tap_selection_granularity(tap_count: u8) -> SelectionGranularity {
    match tap_count {
        0 | 1 => SelectionGranularity::Caret,
        n => match (n - 2) % 3 {
            0 => SelectionGranularity::Word,
            1 => SelectionGranularity::Line,
            _ => SelectionGranularity::Paragraph,
        },
    }
}

/// Returns the byte range `[start, end)` of the line containing `pos`, delimited
/// by `\n` (the newline itself is excluded from the range).
///
/// Used for triple-tap line selection. Byte offsets always land on `char`
/// boundaries because `\n` is a single-byte ASCII character.
pub fn find_line_boundaries(text: &str, pos: usize) -> (usize, usize) {
    let pos = pos.min(text.len());
    let start = text[..pos].rfind('\n').map(|i| i + 1).unwrap_or(0);
    let end = text[pos..]
        .find('\n')
        .map(|i| pos + i)
        .unwrap_or(text.len());
    (start, end)
}

/// Returns the byte range `[start, end)` of the paragraph containing `pos`.
///
/// Paragraphs are delimited by blank lines — a run of two or more consecutive
/// `\n` — so a fourth tap grows the selection from one line to the whole block
/// of text around it. Text with no blank line is a single paragraph (the whole
/// string). Byte offsets land on `char` boundaries because `\n` is single-byte
/// ASCII. Unicode-aware: multi-byte characters inside the paragraph are spanned
/// whole.
pub fn find_paragraph_boundaries(text: &str, pos: usize) -> (usize, usize) {
    let pos = pos.min(text.len());
    let start = text[..pos]
        .rfind("\n\n")
        .map(|i| {
            let mut s = i + 1;
            while text[s..].starts_with('\n') {
                s += 1;
            }
            s
        })
        .unwrap_or(0);
    let end = text[pos..]
        .find("\n\n")
        .map(|i| pos + i)
        .unwrap_or(text.len());
    (start.min(end), end)
}

/// Which visual line a caret/handle at a soft-wrap boundary belongs to. At a
/// shared boundary byte (the end of one wrapped visual line IS the start of
/// the next — mid-word wraps produce these) the offset alone is ambiguous:
///
/// * [`LineAffinity::Upstream`] anchors to the END of the upper line — the
///   glyph a dragging finger means. Selection END and cursor handles, the
///   drawn caret, and the loupe use this; without it a drag along a wrapped
///   line's right edge snaps the handle one line DOWN and to the left edge.
/// * [`LineAffinity::Downstream`] anchors to the START of the lower line —
///   where the first selected glyph actually renders. Selection START handles
///   and highlight geometry use this.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LineAffinity {
    Upstream,
    Downstream,
}

/// Given the source byte ranges of the **visual** (wrapped) lines and a caret
/// byte `offset`, returns the `(visual_line_index, line_start_byte)` the caret
/// sits on.
///
/// The caret belongs to the last visual line whose start is at or before
/// `offset`, except at a shared soft-wrap boundary where `affinity` decides
/// (see [`LineAffinity`]):
/// * a caret in the middle of a visual line resolves to that line;
/// * a caret at the very end of the text sits on the last visual line.
///
/// This is the wrap-aware replacement for counting logical `\n` lines: without
/// it, a caret on a wrapped line's second visual line is drawn on the first (and
/// its x runs off the right edge), even though typing and the magnifier place it
/// correctly. Returns `(0, 0)` when there are no ranges.
pub fn caret_visual_line(
    ranges: &[std::ops::Range<usize>],
    offset: usize,
    affinity: LineAffinity,
) -> (usize, usize) {
    let mut result = (0usize, 0usize);
    for (index, range) in ranges.iter().enumerate() {
        if range.start <= offset {
            if affinity == LineAffinity::Upstream
                && index > 0
                && range.start == offset
                && ranges[index - 1].end == offset
                && ranges[index - 1].start < offset
            {
                break;
            }
            result = (index, range.start);
        } else {
            break;
        }
    }
    result
}

/// Downward travel that follows with the original finger-to-handle offset
/// before the visibility drift starts.
pub const GRAB_DIRECT_FOLLOW_DISTANCE: f32 = 8.0;
/// Additional downward travel over which the handle moves into full view.
pub const GRAB_VISIBILITY_DRIFT_DISTANCE: f32 = 48.0;
/// Extra clearance (dp) below the handle dot once fully visible above the
/// finger.
pub const GRAB_BIAS_VIEW_CLEARANCE: f32 = 4.0;

/// The drift target: bias placing the finger just below the handle dot
/// (tip + dot + clearance), so the whole lollipop stays visible above it.
pub fn grab_bias_full_view() -> f32 {
    -(2.0 * HANDLE_RADIUS + GRAB_BIAS_VIEW_CLEARANCE)
}

/// Finger-to-handle relationship for one drag. The first phase preserves the
/// captured offset exactly, the second shifts the handle above the finger,
/// and the third preserves that final offset exactly. Progress is based on
/// the furthest displacement from the grab, so event cadence and small
/// reversals cannot change the result.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct HandleGrabOffset {
    initial_bias: f32,
    bias: f32,
    start_y: f32,
    furthest_y: f32,
    drift_progress: f32,
    drifts: bool,
}

impl HandleGrabOffset {
    pub fn begin(handle_tip_y: f32, finger_y: f32) -> Self {
        Self::begin_for(handle_tip_y, finger_y, true)
    }

    pub fn begin_for(handle_tip_y: f32, finger_y: f32, drifts: bool) -> Self {
        let initial_bias = handle_tip_y - finger_y;
        Self {
            initial_bias,
            bias: initial_bias,
            start_y: finger_y,
            furthest_y: finger_y,
            drift_progress: 0.0,
            drifts,
        }
    }

    pub fn track(&mut self, finger_y: f32) -> f32 {
        if !self.drifts {
            self.bias = self.initial_bias;
            return self.bias;
        }
        self.furthest_y = self.furthest_y.max(finger_y);
        let travel = (self.furthest_y - self.start_y - GRAB_DIRECT_FOLLOW_DISTANCE).max(0.0);
        let t = (travel / GRAB_VISIBILITY_DRIFT_DISTANCE).clamp(0.0, 1.0);
        self.drift_progress = t * t * (3.0 - 2.0 * t);
        let full_view = self.initial_bias.min(grab_bias_full_view());
        self.bias = self.initial_bias + (full_view - self.initial_bias) * self.drift_progress;
        self.bias
    }

    pub fn bias(&self) -> f32 {
        self.bias
    }

    pub fn drift_progress(&self) -> f32 {
        self.drift_progress
    }
}

/// Which selection handle a lollipop represents.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum HandleKind {
    /// The cursor handle shown for a collapsed selection: the caret stem with a
    /// round grab dot hanging below the line (like the end handle).
    Cursor,
    /// The start (leftmost) selection handle: dot ON TOP of the line, stem
    /// spanning the line box below it.
    SelectionStart,
    /// The end (rightmost) selection handle: stem spanning the line box, dot
    /// hanging BELOW it.
    SelectionEnd,
}

/// Radius of a selection/cursor handle dot in dp (the reference dot is
/// 16.2 physical px at 3x ≈ a 16 dp circle).
pub const HANDLE_RADIUS: f32 = 8.0;

/// Width of the handle stem in dp (measured 6 px at 3x = 2 dp — the same
/// weight as the caret).
pub const HANDLE_STEM_WIDTH: f32 = 2.0;

/// How far the dot dips INTO the line box (dp): the reference start dot's
/// bottom sits ~5 px (1.7 dp) below the line-box top, the end dot's top ~6 px
/// above the line-box bottom, so dot and stem read as one continuous shape.
pub const HANDLE_DOT_LINE_OVERLAP: f32 = 2.0;

/// SVG path data for a handle lollipop at a text edge.
///
/// `anchor_x` is the text edge (caret / selection endpoint) x; the line box
/// spans `line_top .. line_bottom`. The stem (width
/// [`HANDLE_STEM_WIDTH`]) always spans the line box, centered on `anchor_x`;
/// the dot (radius `radius`) sits tangent just outside the line box — above it
/// for [`SelectionStart`](HandleKind::SelectionStart), below it for
/// [`SelectionEnd`](HandleKind::SelectionEnd) and
/// [`Cursor`](HandleKind::Cursor) — overlapping the box edge by
/// [`HANDLE_DOT_LINE_OVERLAP`] so the two read as one shape.
pub fn handle_path_data(
    kind: HandleKind,
    anchor_x: f32,
    line_top: f32,
    line_bottom: f32,
    radius: f32,
) -> String {
    let r = radius.max(0.0);
    let half_stem = HANDLE_STEM_WIDTH * 0.5;
    let (left, right) = (anchor_x - half_stem, anchor_x + half_stem);
    let stem = |top: f32, bottom: f32| {
        format!("M {left} {top} L {right} {top} L {right} {bottom} L {left} {bottom} Z")
    };
    let dot = |cy: f32| {
        format!(
            "M {x0} {cy} A {r} {r} 0 1 1 {x1} {cy} A {r} {r} 0 1 1 {x0} {cy} Z",
            x0 = anchor_x - r,
            x1 = anchor_x + r,
        )
    };
    match kind {
        HandleKind::SelectionStart => {
            let cy = line_top - r + HANDLE_DOT_LINE_OVERLAP;
            format!("{} {}", stem(line_top, line_bottom), dot(cy))
        }
        HandleKind::SelectionEnd | HandleKind::Cursor => {
            let cy = line_bottom + r - HANDLE_DOT_LINE_OVERLAP;
            format!("{} {}", stem(line_top, line_bottom), dot(cy))
        }
    }
}

/// Finger-sized grab slop (px) added around a handle's drawn teardrop to enlarge
/// its touch target, matching Android's generous handle hit area. A bare
/// teardrop (~2·[`HANDLE_RADIUS`] across) is far smaller than a fingertip, so a
/// touch-DOWN aimed at a handle routinely lands a few px off it; without this
/// slop the press falls through to the field below and places a caret, which
/// collapses the selection. The slop is applied to the sides and BELOW the tip
/// (where the bulb and the grabbing finger sit) but never ABOVE the tip — see
/// [`crate::widgets::selection_handle`], which keeps the box off the glyph line
/// so a double-tap still reaches the field to escalate into a word selection.
pub const HANDLE_GRAB_SLOP: f32 = 24.0;

/// Computes the selection `(min, max)` that results from dragging one handle to
/// a new text `offset`, keeping the opposite (fixed) edge anchored.
///
/// Dragging never lets the two edges cross: a dragged start clamps to just
/// before the fixed end, and a dragged end clamps to just after the fixed
/// start, so the selection keeps at least one selected unit.
pub fn selection_after_handle_drag(
    dragged: HandleKind,
    fixed_edge: usize,
    dragged_offset: usize,
    text_len: usize,
) -> (usize, usize) {
    let fixed = fixed_edge.min(text_len);
    let dragged_offset = dragged_offset.min(text_len);
    match dragged {
        HandleKind::SelectionStart => {
            let start = dragged_offset.min(fixed.saturating_sub(1));
            (start, fixed)
        }
        HandleKind::SelectionEnd => {
            let end = dragged_offset.max(fixed + 1).min(text_len);
            (fixed, end)
        }
        HandleKind::Cursor => (dragged_offset, dragged_offset),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn tap_classification_escalates_within_time_and_slop() {
        assert_eq!(classify_tap_count(None, 0, 10.0, 10.0, 500, 24.0), 1);
        assert_eq!(
            classify_tap_count(Some((1, 10.0, 10.0)), 100, 11.0, 12.0, 500, 24.0),
            2
        );
        assert_eq!(
            classify_tap_count(Some((2, 10.0, 10.0)), 100, 11.0, 12.0, 500, 24.0),
            3
        );
        assert_eq!(
            classify_tap_count(Some((3, 10.0, 10.0)), 100, 11.0, 12.0, 500, 24.0),
            4
        );
        assert_eq!(
            classify_tap_count(Some((4, 10.0, 10.0)), 100, 11.0, 12.0, 500, 24.0),
            5
        );
    }

    #[test]
    fn tap_classification_resets_past_timeout_or_slop() {
        assert_eq!(
            classify_tap_count(Some((1, 10.0, 10.0)), 600, 10.0, 10.0, 500, 24.0),
            1
        );
        assert_eq!(
            classify_tap_count(Some((1, 10.0, 10.0)), 50, 100.0, 10.0, 500, 24.0),
            1
        );
        assert_eq!(
            classify_tap_count(Some((3, 10.0, 10.0)), 600, 10.0, 10.0, 500, 24.0),
            1
        );
    }

    #[test]
    fn tap_inside_selection_cycles_word_line_paragraph_by_location() {
        use SelectionGranularity::*;

        let mut count = resolve_selection_tap_count(1, 0, true, false);
        assert_eq!(count, 2);
        assert_eq!(tap_selection_granularity(count), Word);

        count = resolve_selection_tap_count(1, count, true, true);
        assert_eq!(count, 3);
        assert_eq!(tap_selection_granularity(count), Line);

        count = resolve_selection_tap_count(1, count, true, true);
        assert_eq!(count, 4);
        assert_eq!(tap_selection_granularity(count), Paragraph);

        count = resolve_selection_tap_count(1, count, true, true);
        assert_eq!(count, 5);
        assert_eq!(tap_selection_granularity(count), Word);

        let reset = resolve_selection_tap_count(1, count, true, false);
        assert_eq!(reset, 2);
        assert_eq!(tap_selection_granularity(reset), Word);
    }

    #[test]
    fn resolve_tap_count_preserves_rapid_multitap_and_caret() {
        assert_eq!(resolve_selection_tap_count(2, 1, false, false), 2);
        assert_eq!(resolve_selection_tap_count(3, 2, true, true), 3);
        assert_eq!(resolve_selection_tap_count(1, 4, false, true), 1);
    }

    #[test]
    fn tap_granularity_grows_then_cycles() {
        use SelectionGranularity::*;
        assert_eq!(tap_selection_granularity(0), Caret);
        assert_eq!(tap_selection_granularity(1), Caret);
        assert_eq!(tap_selection_granularity(2), Word);
        assert_eq!(tap_selection_granularity(3), Line);
        assert_eq!(tap_selection_granularity(4), Paragraph);
        assert_eq!(tap_selection_granularity(5), Word);
        assert_eq!(tap_selection_granularity(6), Line);
        assert_eq!(tap_selection_granularity(7), Paragraph);
        assert_eq!(tap_selection_granularity(8), Word);
    }

    #[test]
    fn paragraph_boundaries_span_blank_line_delimited_blocks() {
        let text = "line one\nline two\n\nsecond para\nstill second\n\n\nthird";
        let (s, e) = find_paragraph_boundaries(text, 3);
        assert_eq!(&text[s..e], "line one\nline two");
        let (s, e) = find_paragraph_boundaries(text, 20);
        assert_eq!(&text[s..e], "second para\nstill second");
        let (s, e) = find_paragraph_boundaries(text, text.len());
        assert_eq!(&text[s..e], "third");
    }

    #[test]
    fn paragraph_boundaries_no_blank_line_is_whole_text() {
        let text = "just\none\nblock";
        assert_eq!(find_paragraph_boundaries(text, 5), (0, text.len()));
    }

    #[test]
    fn paragraph_boundaries_are_unicode_aware() {
        let text = "\u{4e2d}\u{6587}\u{6bb5}\u{843d}\n\n\u{6b21}";
        let first = "\u{4e2d}\u{6587}\u{6bb5}\u{843d}";
        let (s, e) = find_paragraph_boundaries(text, 3);
        assert_eq!(&text[s..e], first);
        assert!(text.is_char_boundary(s) && text.is_char_boundary(e));
    }

    #[test]
    fn line_boundaries_span_between_newlines() {
        let text = "first line\nsecond line\nthird";
        assert_eq!(find_line_boundaries(text, 15), (11, 22));
        assert_eq!(find_line_boundaries(text, 0), (0, 10));
        assert_eq!(find_line_boundaries(text, 25), (23, text.len()));
    }

    #[test]
    fn line_boundaries_handle_unicode_and_empty_lines() {
        let text = "\u{00e9}\u{00e8}\n\n\u{4e2d}\u{6587}";
        let (start, end) = find_line_boundaries(text, "\u{00e9}\u{00e8}\n".len());
        assert_eq!(start, end);
        let last = find_line_boundaries(text, text.len());
        assert_eq!(&text[last.0..last.1], "\u{4e2d}\u{6587}");
    }

    #[test]
    fn handle_path_is_valid_and_spans_the_line_box() {
        let (x, top, bottom) = (40.0_f32, 20.0_f32, 40.0_f32);
        for kind in [
            HandleKind::Cursor,
            HandleKind::SelectionStart,
            HandleKind::SelectionEnd,
        ] {
            let data = handle_path_data(kind, x, top, bottom, HANDLE_RADIUS);
            let path = cranpose_ui_graphics::VectorPath::parse(&data)
                .expect("handle path must be valid SVG");
            assert!(!path.is_empty(), "{kind:?} handle must have geometry");
            let bounds = path.bounds();
            assert!(bounds.y <= top + 0.5, "{kind:?} must reach the line top");
            assert!(
                bounds.y + bounds.height >= bottom - 0.5,
                "{kind:?} must reach the line bottom"
            );
            assert!((bounds.x - (x - HANDLE_RADIUS)).abs() <= 0.5);
            assert!((bounds.x + bounds.width - (x + HANDLE_RADIUS)).abs() <= 0.5);
        }
    }

    #[test]
    fn selection_handle_dots_sit_on_the_correct_side_of_the_line() {
        let (x, top, bottom, r) = (40.0_f32, 20.0_f32, 40.0_f32, HANDLE_RADIUS);
        let eps = 0.5_f32;

        let bounds = |kind: HandleKind| {
            let data = handle_path_data(kind, x, top, bottom, r);
            cranpose_ui_graphics::VectorPath::parse(&data)
                .expect("valid handle path")
                .bounds()
        };

        let start = bounds(HandleKind::SelectionStart);
        assert!(
            (start.y - (top - 2.0 * r + HANDLE_DOT_LINE_OVERLAP)).abs() <= eps,
            "start dot must ride on top of the line (top at {}, expected {})",
            start.y,
            top - 2.0 * r + HANDLE_DOT_LINE_OVERLAP
        );
        assert!(
            start.y + start.height <= bottom + eps,
            "start handle must not extend below the line box"
        );

        for kind in [HandleKind::SelectionEnd, HandleKind::Cursor] {
            let b = bounds(kind);
            assert!(
                (b.y + b.height - (bottom + 2.0 * r - HANDLE_DOT_LINE_OVERLAP)).abs() <= eps,
                "{kind:?} dot must hang below the line (bottom at {}, expected {})",
                b.y + b.height,
                bottom + 2.0 * r - HANDLE_DOT_LINE_OVERLAP
            );
            assert!(
                b.y >= top - eps,
                "{kind:?} handle must not extend above the line box"
            );
        }
    }

    #[test]
    fn caret_visual_line_resolves_wrapped_visual_lines() {
        let ranges = vec![0..5usize, 5..9, 10..12];

        assert_eq!(
            caret_visual_line(&ranges, 0, LineAffinity::Downstream),
            (0, 0)
        );
        assert_eq!(
            caret_visual_line(&ranges, 3, LineAffinity::Downstream),
            (0, 0)
        );
        assert_eq!(
            caret_visual_line(&ranges, 5, LineAffinity::Downstream),
            (1, 5)
        );
        assert_eq!(
            caret_visual_line(&ranges, 7, LineAffinity::Downstream),
            (1, 5)
        );
        assert_eq!(
            caret_visual_line(&ranges, 9, LineAffinity::Downstream),
            (1, 5)
        );
        assert_eq!(
            caret_visual_line(&ranges, 11, LineAffinity::Downstream),
            (2, 10)
        );
        assert_eq!(
            caret_visual_line(&ranges, 12, LineAffinity::Downstream),
            (2, 10)
        );
    }

    #[test]
    fn start_handle_grab_never_drifts() {
        let mut grab = HandleGrabOffset::begin_for(108.0, 100.0, false);
        assert_eq!(grab.track(108.0), 8.0);
        assert_eq!(grab.track(160.0), 8.0, "no drift on long downward travel");
        assert_eq!(grab.drift_progress(), 0.0);
    }

    #[test]
    fn grab_offset_has_follow_drift_and_strict_phases() {
        let mut grab = HandleGrabOffset::begin(108.0, 100.0);
        assert_eq!(grab.bias(), 8.0);

        let direct_bias = grab.track(108.0);
        assert_eq!(direct_bias, 8.0, "initial travel follows exactly");
        assert_eq!(108.0 + direct_bias, 116.0);

        let drifting_bias = grab.track(132.0);
        assert!(drifting_bias < 8.0 && drifting_bias > grab_bias_full_view());
        assert!((0.0..1.0).contains(&grab.drift_progress()));

        assert_eq!(grab.track(156.0), grab_bias_full_view());
        assert_eq!(grab.drift_progress(), 1.0);
        assert_eq!(grab.track(220.0), grab_bias_full_view());
    }

    #[test]
    fn grab_offset_is_cadence_independent_and_never_unwinds() {
        let mut single = HandleGrabOffset::begin(108.0, 100.0);
        single.track(140.0);

        let mut sampled = HandleGrabOffset::begin(108.0, 100.0);
        for y in [104.0, 109.0, 116.0, 130.0, 140.0] {
            sampled.track(y);
        }
        assert_eq!(sampled.bias(), single.bias());
        assert_eq!(sampled.drift_progress(), single.drift_progress());

        let migrated = sampled.bias();
        sampled.track(90.0);
        assert_eq!(
            sampled.bias(),
            migrated,
            "upward travel cannot unwind drift"
        );

        let deep = grab_bias_full_view() - 10.0;
        let mut already_visible = HandleGrabOffset::begin(deep, 0.0);
        already_visible.track(100.0);
        assert_eq!(already_visible.bias(), deep);
    }

    #[test]
    fn caret_visual_line_handles_empty_ranges() {
        assert_eq!(caret_visual_line(&[], 5, LineAffinity::Upstream), (0, 0));
        assert_eq!(caret_visual_line(&[], 5, LineAffinity::Downstream), (0, 0));
    }

    #[test]
    fn caret_visual_line_upstream_anchors_shared_wrap_boundary_to_upper_line() {
        let ranges = vec![0..5usize, 5..9, 10..12];

        assert_eq!(
            caret_visual_line(&ranges, 5, LineAffinity::Upstream),
            (0, 0)
        );
        assert_eq!(
            caret_visual_line(&ranges, 5, LineAffinity::Downstream),
            (1, 5)
        );

        assert_eq!(
            caret_visual_line(&ranges, 3, LineAffinity::Upstream),
            (0, 0)
        );
        assert_eq!(
            caret_visual_line(&ranges, 7, LineAffinity::Upstream),
            (1, 5)
        );

        assert_eq!(
            caret_visual_line(&ranges, 10, LineAffinity::Upstream),
            (2, 10)
        );

        assert_eq!(
            caret_visual_line(&ranges, 12, LineAffinity::Upstream),
            (2, 10)
        );
    }

    #[test]
    fn handle_drag_keeps_edges_from_crossing() {
        assert_eq!(
            selection_after_handle_drag(HandleKind::SelectionEnd, 5, 2, 20),
            (5, 6)
        );
        assert_eq!(
            selection_after_handle_drag(HandleKind::SelectionEnd, 5, 12, 20),
            (5, 12)
        );
        assert_eq!(
            selection_after_handle_drag(HandleKind::SelectionStart, 8, 10, 20),
            (7, 8)
        );
        assert_eq!(
            selection_after_handle_drag(HandleKind::SelectionStart, 8, 3, 20),
            (3, 8)
        );
        assert_eq!(
            selection_after_handle_drag(HandleKind::Cursor, 4, 9, 20),
            (9, 9)
        );
    }
}