aetna-core 0.3.3

Aetna — backend-agnostic UI library core
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
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
//! Pointer hit-testing and scroll routing on a laid-out tree.
//!
//! All entry points walk children in reverse paint order (top-most
//! visual first), respecting the inherited clip stack so a button outside
//! its scroll viewport can't be clicked. Only nodes with `key.is_some()`
//! are hit-test targets — author intent is "I tagged it with a key, it's
//! interactive."
//!
//! This keyed-only rule is also what gates
//! [`crate::tree::El::tooltip`]: an unkeyed leaf with `.tooltip()` is
//! silently dead because hover never lands on it. The bundle lint
//! flags this case as
//! [`crate::bundle::lint::FindingKind::DeadTooltip`].
//!
//! Reads computed rects from `UiState`'s layout side map (populated by
//! the layout pass) — the tree carries identity (`computed_id`) but not
//! geometry. Paint-time transforms (`translate`, `scale`) are then
//! applied in the same way `draw_ops::push_node` applies them, so
//! hit-testing matches what the user sees. Parent rects are *not*
//! barriers: a child can paint outside its parent (a swatch lifting on
//! `.scale(1.15)`) and still be hittable. Only `clip()` (an explicit
//! author-declared boundary) gates descent into descendants.

use std::ops::Range;

use crate::event::UiTarget;
use crate::selection::SelectionPoint;
use crate::state::UiState;
use crate::text::metrics;
use crate::tree::{El, FontWeight, Kind, Rect, TextWrap};

/// Find the topmost keyed node whose effective hit rect contains
/// `point` (logical pixels). Returns `None` if the point hits no keyed
/// node. By default the effective hit rect is the transformed laid-out
/// rect; nodes can opt into extra input area with `.hit_overflow(...)`.
pub fn hit_test(root: &El, ui_state: &UiState, point: (f32, f32)) -> Option<String> {
    hit_test_target(root, ui_state, point).map(|target| target.key)
}

/// Find the topmost keyed node and return full target metadata.
pub fn hit_test_target(root: &El, ui_state: &UiState, point: (f32, f32)) -> Option<UiTarget> {
    match hit_test_rec(root, ui_state, point, None, (0.0, 0.0)) {
        Hit::Target(target) => Some(target),
        Hit::Blocked | Hit::Miss => None,
    }
}

enum Hit {
    Target(UiTarget),
    Blocked,
    Miss,
}

fn hit_test_rec(
    node: &El,
    ui_state: &UiState,
    point: (f32, f32),
    inherited_clip: Option<Rect>,
    inherited_translate: (f32, f32),
) -> Hit {
    if let Some(clip) = inherited_clip
        && !clip.contains(point.0, point.1)
    {
        return Hit::Miss;
    }
    // Mirror `draw_ops::push_node`: translate accumulates through the
    // subtree; scale applies to this node only and doesn't propagate.
    // Hit-testing must use the same painted rect that the user sees, or
    // clicks on a translated card land on whatever sibling occupies the
    // un-translated layout slot.
    let total_translate = (
        inherited_translate.0 + node.translate.0,
        inherited_translate.1 + node.translate.1,
    );
    let computed = ui_state.rect(&node.computed_id);
    let translated_rect = translated(computed, total_translate);
    let painted_rect = scaled_around_center(translated_rect, node.scale);
    // We do NOT early-return on `!painted_rect.contains(point)`.
    // A child can paint outside its parent's rect (the palette
    // swatches `.scale(1.15).translate(0, -8)` lift over the row's
    // computed bounds) and the only hard boundary is `inherited_clip`.
    // The painted-rect containment is checked below for self-as-target.
    let child_clip = if node.clip {
        match inherited_clip {
            Some(clip) => Some(
                clip.intersect(painted_rect)
                    .unwrap_or(Rect::new(0.0, 0.0, 0.0, 0.0)),
            ),
            None => Some(painted_rect),
        }
    } else {
        inherited_clip
    };
    // Children paint last → are on top → check first.
    for child in node.children.iter().rev() {
        match hit_test_rec(child, ui_state, point, child_clip, total_translate) {
            Hit::Target(target) => return Hit::Target(target),
            Hit::Blocked => return Hit::Blocked,
            Hit::Miss => {}
        }
    }
    // No child hit. Self counts only if its effective hit rect contains
    // the point AND it's keyed (author tagged it interactive). The
    // returned target rect remains the transformed visual/layout rect:
    // hit overflow is an input affordance, not geometry apps should
    // use for pointer-to-value math.
    let hit_rect = painted_rect.outset(node.hit_overflow);
    if !hit_rect.contains(point.0, point.1) {
        return Hit::Miss;
    }
    if let Some(key) = &node.key {
        return Hit::Target(UiTarget {
            key: key.clone(),
            node_id: node.computed_id.clone(),
            rect: painted_rect,
            tooltip: node.tooltip.clone(),
            scroll_offset_y: nearest_descendant_scroll_offset_y(node, ui_state),
        });
    }
    if node.block_pointer {
        return Hit::Blocked;
    }
    Hit::Miss
}

/// Find the topmost selectable + keyed text leaf containing `point`
/// and return a [`SelectionPoint`] resolved against the leaf's text
/// content (one byte offset per Unicode scalar boundary).
///
/// Returns `None` when the point misses every selectable leaf, or
/// when the hit leaf has no text. Walks the same tree the focus
/// hit-test walks, with the same clip / translate rules — so a
/// selectable paragraph that's been scrolled out of view is correctly
/// excluded.
pub fn selection_point_at(
    root: &El,
    ui_state: &UiState,
    point: (f32, f32),
) -> Option<SelectionPoint> {
    let mut hit: Option<SelectableHit<'_>> = None;
    selectable_rec(root, ui_state, point, None, (0.0, 0.0), &mut hit);
    let SelectableHit { node, painted } = hit?;
    let key = node.key.clone()?;
    let value = node
        .selection_source
        .as_ref()
        .map(|source| source.visible.as_str())
        .or(node.text.as_deref())?;
    if matches!(node.kind, Kind::Inlines)
        && node.children.iter().any(|c| matches!(c.kind, Kind::Math))
        && let Some(byte) = mixed_inline_hit_byte(node, painted, point)
    {
        return Some(SelectionPoint { key, byte });
    }
    let local_x = (point.0 - painted.x).max(0.0);
    let local_y = (point.1 - painted.y).clamp(0.0, painted.h.max(1.0) - 1.0);
    let geometry = metrics::TextGeometry::new_with_family(
        value,
        node.font_size,
        effective_text_family(node),
        node.font_weight,
        node.font_mono,
        node.text_wrap,
        Some(painted.w),
    );
    let byte = match geometry.hit_byte(local_x, local_y) {
        Some(byte) => byte.min(value.len()),
        None => {
            if local_x <= 0.0 {
                0
            } else {
                value.len()
            }
        }
    };
    Some(SelectionPoint { key, byte })
}

fn mixed_inline_hit_byte(node: &El, painted_rect: Rect, point: (f32, f32)) -> Option<usize> {
    let glyph_rect = painted_rect.inset(node.padding);
    let items = mixed_inline_hit_items(node, glyph_rect);
    if items.is_empty() {
        return Some(0);
    }
    let line = mixed_hit_line(&items, point.1);
    let line_items: Vec<&MixedHitItem> = items.iter().filter(|item| item.line == line).collect();
    let first = line_items.first()?;
    let last = line_items.last()?;
    if point.0 <= first.rect.x {
        return Some(first.visible.start);
    }
    for item in &line_items {
        if point.0 <= item.rect.right() {
            return Some(match &item.kind {
                MixedHitKind::Text {
                    text,
                    font_size,
                    font_family,
                    font_weight,
                    font_mono,
                } => {
                    let geometry = metrics::TextGeometry::new_with_family(
                        text,
                        *font_size,
                        *font_family,
                        *font_weight,
                        *font_mono,
                        TextWrap::NoWrap,
                        None,
                    );
                    let local_x = (point.0 - item.rect.x).max(0.0);
                    let local_y = (point.1 - item.rect.y).clamp(0.0, item.rect.h.max(1.0) - 1.0);
                    let byte = geometry
                        .hit_byte(local_x, local_y)
                        .unwrap_or(if local_x <= 0.0 { 0 } else { text.len() });
                    item.visible.start + byte.min(text.len())
                }
                MixedHitKind::Atomic => {
                    if point.0 < item.rect.center_x() {
                        item.visible.start
                    } else {
                        item.visible.end
                    }
                }
            });
        }
    }
    Some(last.visible.end)
}

#[derive(Clone)]
struct PendingMixedHitItem {
    kind: PendingMixedHitKind,
    x: f32,
    visible: Range<usize>,
}

#[derive(Clone)]
enum PendingMixedHitKind {
    Text { child: Box<El>, text: String },
    Math { layout: crate::math::MathLayout },
}

struct MixedHitItem {
    rect: Rect,
    line_top: f32,
    line_bottom: f32,
    line: usize,
    visible: Range<usize>,
    kind: MixedHitKind,
}

enum MixedHitKind {
    Text {
        text: String,
        font_size: f32,
        font_family: crate::tree::FontFamily,
        font_weight: FontWeight,
        font_mono: bool,
    },
    Atomic,
}

fn mixed_inline_hit_items(node: &El, rect: Rect) -> Vec<MixedHitItem> {
    let mut breaker = crate::inline_mixed::MixedInlineBreaker::new(
        node.text_wrap,
        Some(rect.w),
        node.font_size * 0.82,
        node.font_size * 0.22,
        node.line_height,
    );
    let mut pending = Vec::new();
    let mut out = Vec::new();
    let mut visible_cursor = 0usize;
    let mut line_index = 0usize;

    for child in &node.children {
        match child.kind {
            Kind::HardBreak => {
                flush_mixed_hit_line(node, rect, &mut breaker, &mut pending, &mut out, line_index);
                line_index += 1;
                visible_cursor += "\n".len();
            }
            Kind::Text => {
                if let Some(text) = &child.text {
                    for chunk in inline_text_chunks(text) {
                        let visible = visible_cursor..(visible_cursor + chunk.len());
                        visible_cursor += chunk.len();
                        let is_space = chunk.chars().all(char::is_whitespace);
                        if breaker.skips_leading_space(is_space) {
                            continue;
                        }
                        let (w, ascent, descent) = inline_text_chunk_metrics(child, chunk);
                        if breaker.wraps_before(is_space, w) {
                            flush_mixed_hit_line(
                                node,
                                rect,
                                &mut breaker,
                                &mut pending,
                                &mut out,
                                line_index,
                            );
                            line_index += 1;
                        }
                        if breaker.skips_overflowing_space(is_space, w) {
                            continue;
                        }
                        if is_space
                            && !matches!(
                                pending.last(),
                                Some(PendingMixedHitItem {
                                    kind: PendingMixedHitKind::Text { .. },
                                    ..
                                })
                            )
                        {
                            breaker.push(w, ascent, descent);
                            continue;
                        }
                        pending.push(PendingMixedHitItem {
                            kind: PendingMixedHitKind::Text {
                                child: Box::new(child.clone()),
                                text: chunk.to_string(),
                            },
                            x: breaker.x(),
                            visible,
                        });
                        breaker.push(w, ascent, descent);
                    }
                }
            }
            Kind::Math => {
                if let Some(expr) = &child.math {
                    let layout =
                        crate::math::layout_math(expr, child.font_size, child.math_display);
                    if breaker.wraps_before(false, layout.width) {
                        flush_mixed_hit_line(
                            node,
                            rect,
                            &mut breaker,
                            &mut pending,
                            &mut out,
                            line_index,
                        );
                        line_index += 1;
                    }
                    let visible_len = "\u{fffc}".len();
                    let visible = visible_cursor..(visible_cursor + visible_len);
                    visible_cursor += visible_len;
                    let width = layout.width;
                    let ascent = layout.ascent;
                    let descent = layout.descent;
                    pending.push(PendingMixedHitItem {
                        kind: PendingMixedHitKind::Math { layout },
                        x: breaker.x(),
                        visible,
                    });
                    breaker.push(width, ascent, descent);
                }
            }
            _ => {}
        }
    }
    flush_mixed_hit_line(node, rect, &mut breaker, &mut pending, &mut out, line_index);
    out
}

fn flush_mixed_hit_line(
    parent: &El,
    rect: Rect,
    breaker: &mut crate::inline_mixed::MixedInlineBreaker,
    pending: &mut Vec<PendingMixedHitItem>,
    out: &mut Vec<MixedHitItem>,
    line_index: usize,
) {
    let line = breaker.finish_line();
    let line_top = rect.y + line.top;
    let line_bottom = line_top + (line.ascent + line.descent).max(parent.line_height);
    let baseline_y = rect.y + line.top + line.ascent;
    for item in pending.drain(..) {
        match item.kind {
            PendingMixedHitKind::Text { child, text } => {
                let size = child.font_size * parent.scale;
                let glyph_layout = metrics::layout_text_with_line_height_and_family(
                    &text,
                    size,
                    child.line_height * parent.scale,
                    child.font_family,
                    child.font_weight,
                    child.font_mono,
                    TextWrap::NoWrap,
                    None,
                );
                let glyph_baseline = glyph_layout
                    .lines
                    .first()
                    .map(|line| line.baseline)
                    .unwrap_or_else(|| metrics::line_height(size) * 0.75);
                out.push(MixedHitItem {
                    rect: Rect::new(
                        rect.x + item.x,
                        baseline_y - glyph_baseline,
                        glyph_layout.width,
                        glyph_layout.height,
                    ),
                    line_top,
                    line_bottom,
                    line: line_index,
                    visible: item.visible,
                    kind: MixedHitKind::Text {
                        text,
                        font_size: size,
                        font_family: child.font_family,
                        font_weight: child.font_weight,
                        font_mono: child.font_mono,
                    },
                });
            }
            PendingMixedHitKind::Math { layout } => {
                out.push(MixedHitItem {
                    rect: Rect::new(
                        rect.x + item.x,
                        baseline_y - layout.ascent,
                        layout.width,
                        layout.height(),
                    ),
                    line_top,
                    line_bottom,
                    line: line_index,
                    visible: item.visible,
                    kind: MixedHitKind::Atomic,
                });
            }
        }
    }
}

fn mixed_hit_line(items: &[MixedHitItem], y: f32) -> usize {
    for item in items {
        if y >= item.line_top && y <= item.line_bottom {
            return item.line;
        }
    }
    items
        .iter()
        .min_by(|a, b| {
            let ac = (a.line_top + a.line_bottom) * 0.5;
            let bc = (b.line_top + b.line_bottom) * 0.5;
            (y - ac).abs().total_cmp(&(y - bc).abs())
        })
        .map(|item| item.line)
        .unwrap_or(0)
}

fn inline_text_chunks(text: &str) -> Vec<&str> {
    let mut chunks = Vec::new();
    let mut start = 0;
    let mut last_space = None;
    for (i, ch) in text.char_indices() {
        let is_space = ch.is_whitespace();
        match last_space {
            None => last_space = Some(is_space),
            Some(prev) if prev != is_space => {
                chunks.push(&text[start..i]);
                start = i;
                last_space = Some(is_space);
            }
            _ => {}
        }
    }
    if start < text.len() {
        chunks.push(&text[start..]);
    }
    chunks
}

fn inline_text_chunk_metrics(child: &El, text: &str) -> (f32, f32, f32) {
    let layout = metrics::layout_text_with_line_height_and_family(
        text,
        child.font_size,
        child.line_height,
        child.font_family,
        child.font_weight,
        child.font_mono,
        TextWrap::NoWrap,
        None,
    );
    (layout.width, child.font_size * 0.82, child.font_size * 0.22)
}

/// Find the link URL of the topmost text-link run containing `point`.
///
/// Walks the tree for `Kind::Inlines` paragraphs whose painted rect
/// contains the pointer, re-runs the same shaping pipeline the paint
/// pass uses to find the byte under the pointer, then walks the
/// paragraph's child runs to identify which one owns that byte.
/// Returns the run's [`crate::tree::El::text_link`] URL, or `None`
/// when the click missed every link run.
///
/// This is the read side of the link-click contract: the runtime calls
/// it from `pointer_down` / `pointer_up` and the app sees the result as
/// a [`crate::event::UiEventKind::LinkActivated`] event with the URL in
/// [`crate::event::UiEvent::key`]. Aetna does not act on the URL — see
/// [`crate::event::App::drain_link_opens`] for the app-decided handoff
/// to a host opener.
pub fn link_at(root: &El, ui_state: &UiState, point: (f32, f32)) -> Option<String> {
    link_at_rec(root, ui_state, point, None, (0.0, 0.0))
}

fn link_at_rec(
    node: &El,
    ui_state: &UiState,
    point: (f32, f32),
    inherited_clip: Option<Rect>,
    inherited_translate: (f32, f32),
) -> Option<String> {
    if let Some(clip) = inherited_clip
        && !clip.contains(point.0, point.1)
    {
        return None;
    }
    let total_translate = (
        inherited_translate.0 + node.translate.0,
        inherited_translate.1 + node.translate.1,
    );
    let computed = ui_state.rect(&node.computed_id);
    let translated_rect = translated(computed, total_translate);
    let painted_rect = scaled_around_center(translated_rect, node.scale);
    let child_clip = if node.clip {
        match inherited_clip {
            Some(clip) => Some(
                clip.intersect(painted_rect)
                    .unwrap_or(Rect::new(0.0, 0.0, 0.0, 0.0)),
            ),
            None => Some(painted_rect),
        }
    } else {
        inherited_clip
    };
    // Children paint last → are on top → check first. A link nested
    // inside an overlay should win over a link in the page beneath.
    for child in node.children.iter().rev() {
        if let Some(url) = link_at_rec(child, ui_state, point, child_clip, total_translate) {
            return Some(url);
        }
    }
    if !matches!(node.kind, Kind::Inlines) {
        return None;
    }
    if !painted_rect.contains(point.0, point.1) {
        return None;
    }
    link_in_inlines_at(node, painted_rect, point)
}

fn link_in_inlines_at(node: &El, painted_rect: Rect, point: (f32, f32)) -> Option<String> {
    // Mirror `draw_ops`'s inline paragraph: glyphs paint inside the
    // node's padding rect, with the same per-paragraph font size /
    // line height aggregated from the child Text runs.
    let glyph_rect = painted_rect.inset(node.padding);
    if !glyph_rect.contains(point.0, point.1) {
        return None;
    }
    let runs = collect_link_runs(node);
    if runs.iter().all(|(_, link)| link.is_none()) {
        return None;
    }
    let concat: String = runs.iter().map(|(t, _)| t.as_str()).collect();
    if concat.is_empty() {
        return None;
    }
    let inline_size = inline_paragraph_font_size(node) * node.scale;
    let geometry = metrics::TextGeometry::new_with_family(
        &concat,
        inline_size,
        node.font_family,
        FontWeight::Regular,
        false,
        node.text_wrap,
        match node.text_wrap {
            TextWrap::NoWrap => None,
            TextWrap::Wrap => Some(glyph_rect.w),
        },
    );
    let local_x = (point.0 - glyph_rect.x).max(0.0);
    let local_y = (point.1 - glyph_rect.y).max(0.0);
    let byte = geometry.hit_byte(local_x, local_y)?;
    // Map the global byte offset back to the run that owns it. A byte
    // past the last grapheme means the click landed beyond the rendered
    // text (paragraphs hugged narrower than their layout slot leave
    // empty space at the end of each line) — treat as no link rather
    // than guessing the nearest run.
    let mut offset = 0usize;
    for (text, link) in &runs {
        let len = text.len();
        if byte < offset + len {
            return link.clone();
        }
        offset += len;
    }
    None
}

/// Mirror `draw_ops::collect_inline_runs` but keep just the run text
/// and link URL — that's all the link hit-test needs. Hard breaks
/// inject a `\n` so byte offsets line up with the shaped string.
fn collect_link_runs(node: &El) -> Vec<(String, Option<String>)> {
    let mut runs = Vec::new();
    for c in &node.children {
        match c.kind {
            Kind::Text => {
                if let Some(text) = &c.text {
                    runs.push((text.clone(), c.text_link.clone()));
                }
            }
            Kind::HardBreak => runs.push(("\n".to_string(), None)),
            _ => {}
        }
    }
    runs
}

/// Mirror `draw_ops::inline_paragraph_font_size` so the shaping
/// here matches the paint pass exactly.
fn inline_paragraph_font_size(node: &El) -> f32 {
    let mut size: f32 = node.font_size;
    for c in &node.children {
        if matches!(c.kind, Kind::Text) {
            size = size.max(c.font_size);
        }
    }
    size
}

/// Inner state carried while walking for a selectable target. We
/// keep a borrow of the El so the caller can read `text` / font
/// params after the walk completes — saving a second tree walk.
struct SelectableHit<'a> {
    node: &'a El,
    painted: Rect,
}

fn effective_text_family(node: &El) -> crate::tree::FontFamily {
    if node.font_mono {
        node.mono_font_family
    } else {
        node.font_family
    }
}

fn selectable_rec<'a>(
    node: &'a El,
    ui_state: &UiState,
    point: (f32, f32),
    inherited_clip: Option<Rect>,
    inherited_translate: (f32, f32),
    out: &mut Option<SelectableHit<'a>>,
) {
    if let Some(clip) = inherited_clip
        && !clip.contains(point.0, point.1)
    {
        return;
    }
    let total_translate = (
        inherited_translate.0 + node.translate.0,
        inherited_translate.1 + node.translate.1,
    );
    let computed = ui_state.rect(&node.computed_id);
    let translated_rect = translated(computed, total_translate);
    let painted_rect = scaled_around_center(translated_rect, node.scale);
    let child_clip = if node.clip {
        match inherited_clip {
            Some(clip) => Some(
                clip.intersect(painted_rect)
                    .unwrap_or(Rect::new(0.0, 0.0, 0.0, 0.0)),
            ),
            None => Some(painted_rect),
        }
    } else {
        inherited_clip
    };
    // Children paint on top → check first.
    for child in node.children.iter().rev() {
        selectable_rec(child, ui_state, point, child_clip, total_translate, out);
        if out.is_some() {
            return;
        }
    }
    // Self counts only if it's a selectable + keyed text-bearing leaf and the
    // point lands inside its painted rect.
    if node.selectable
        && node.key.is_some()
        && (matches!(node.kind, Kind::Text | Kind::Heading) || node.selection_source.is_some())
        && painted_rect.contains(point.0, point.1)
    {
        *out = Some(SelectableHit {
            node,
            painted: painted_rect,
        });
    }
}

/// Return the `computed_id` of the deepest scrollable container whose
/// laid-out rect contains `point`, respecting clipping ancestors.
/// Used to route wheel events.
pub(crate) fn scroll_target_at(root: &El, ui_state: &UiState, point: (f32, f32)) -> Option<String> {
    let mut hit = None;
    scroll_target_rec(root, ui_state, point, None, (0.0, 0.0), &mut hit);
    hit
}

fn scroll_target_rec(
    node: &El,
    ui_state: &UiState,
    point: (f32, f32),
    inherited_clip: Option<Rect>,
    inherited_translate: (f32, f32),
    out: &mut Option<String>,
) {
    if let Some(clip) = inherited_clip
        && !clip.contains(point.0, point.1)
    {
        return;
    }
    let total_translate = (
        inherited_translate.0 + node.translate.0,
        inherited_translate.1 + node.translate.1,
    );
    let computed = ui_state.rect(&node.computed_id);
    let translated_rect = translated(computed, total_translate);
    let painted_rect = scaled_around_center(translated_rect, node.scale);
    // Self counts as a scroll target only if its painted rect contains
    // the point — but we still recurse into children regardless, since
    // a child can paint outside its parent (translate/scale).
    if node.scrollable && painted_rect.contains(point.0, point.1) {
        *out = Some(node.computed_id.clone());
    }
    let child_clip = if node.clip {
        match inherited_clip {
            Some(clip) => Some(
                clip.intersect(painted_rect)
                    .unwrap_or(Rect::new(0.0, 0.0, 0.0, 0.0)),
            ),
            None => Some(painted_rect),
        }
    } else {
        inherited_clip
    };
    for c in &node.children {
        scroll_target_rec(c, ui_state, point, child_clip, total_translate, out);
    }
}

/// Find the nearest `Kind::Scroll` descendant of `node` (or `node`
/// itself) and return its stored scroll offset y. Returns `0.0` when
/// no scroll lives in this subtree.
///
/// Walks pre-order, first-match-wins — widgets that compose a single
/// inner scroll (e.g. `text_area`) get the right offset in O(depth).
/// Widgets that nest multiple scrolls would need a different
/// convention; none exist today.
fn nearest_descendant_scroll_offset_y(node: &El, ui_state: &UiState) -> f32 {
    if matches!(node.kind, Kind::Scroll) {
        return ui_state
            .scroll
            .offsets
            .get(&node.computed_id)
            .copied()
            .unwrap_or(0.0);
    }
    for c in &node.children {
        if let Some(off) = find_scroll_offset_y(c, ui_state) {
            return off;
        }
    }
    0.0
}

fn find_scroll_offset_y(node: &El, ui_state: &UiState) -> Option<f32> {
    if matches!(node.kind, Kind::Scroll) {
        return Some(
            ui_state
                .scroll
                .offsets
                .get(&node.computed_id)
                .copied()
                .unwrap_or(0.0),
        );
    }
    node.children
        .iter()
        .find_map(|c| find_scroll_offset_y(c, ui_state))
}

fn translated(r: Rect, offset: (f32, f32)) -> Rect {
    if offset.0 == 0.0 && offset.1 == 0.0 {
        return r;
    }
    Rect::new(r.x + offset.0, r.y + offset.1, r.w, r.h)
}

fn scaled_around_center(r: Rect, s: f32) -> Rect {
    if (s - 1.0).abs() < f32::EPSILON {
        return r;
    }
    let cx = r.center_x();
    let cy = r.center_y();
    let w = r.w * s;
    let h = r.h * s;
    Rect::new(cx - w * 0.5, cy - h * 0.5, w, h)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::layout::layout;
    use crate::state::UiState;
    use crate::tree::*;
    use crate::{button, column, row};

    fn lay_out_counter() -> (El, UiState) {
        let mut tree = column([
            crate::text("0"),
            row([button("-").key("dec"), button("+").key("inc")]),
        ])
        .padding(20.0);
        let mut state = UiState::new();
        layout(&mut tree, &mut state, Rect::new(0.0, 0.0, 400.0, 200.0));
        (tree, state)
    }

    fn find_rect(node: &El, state: &UiState, key: &str) -> Option<Rect> {
        if node.key.as_deref() == Some(key) {
            return Some(state.rect(&node.computed_id));
        }
        node.children.iter().find_map(|c| find_rect(c, state, key))
    }

    fn find_text_rect(node: &El, state: &UiState) -> Option<Rect> {
        if matches!(node.kind, Kind::Text) {
            return Some(state.rect(&node.computed_id));
        }
        node.children.iter().find_map(|c| find_text_rect(c, state))
    }

    /// Find the rect of the topmost `Kind::Inlines` paragraph. Inline
    /// children (Text leaves) have zero-size rects in layout so callers
    /// that want the painted box reach for the parent's instead.
    fn find_inlines_rect(node: &El, state: &UiState) -> Option<Rect> {
        if matches!(node.kind, Kind::Inlines) {
            return Some(state.rect(&node.computed_id));
        }
        node.children
            .iter()
            .find_map(|c| find_inlines_rect(c, state))
    }

    #[test]
    fn link_at_resolves_per_run_inside_inline_paragraph() {
        // Layout a paragraph that mixes plain text and a single linked
        // run. Clicks on the plain prefix should miss the link; clicks
        // on the linked run should resolve to its URL. This locks the
        // per-run hit test against regressing back to whole-paragraph
        // detection.
        const PREFIX: &str = "Visit ";
        const LINKED: &str = "github.com/computer-whisperer/aetna";
        const URL: &str = "https://github.com/computer-whisperer/aetna";
        let mut tree = column([crate::text_runs([
            crate::text(PREFIX),
            crate::text(LINKED).link(URL),
            crate::text("."),
        ])])
        .padding(20.0);
        let mut state = UiState::new();
        layout(&mut tree, &mut state, Rect::new(0.0, 0.0, 600.0, 200.0));
        let para = find_inlines_rect(&tree, &state).expect("inlines rect");
        // Sanity: the layout fits on one line, so vertical center is
        // safe everywhere.
        let cy = para.y + para.h * 0.5;
        // Click 1px in from the left edge of the paragraph — squarely
        // inside the "Visit " prefix (no link).
        let prefix_x = para.x + 1.0;
        assert_eq!(
            link_at(&tree, &state, (prefix_x, cy)),
            None,
            "clicking the unlinked prefix should not surface the link URL",
        );
        // Click well past the prefix — the linked run is much wider
        // than "Visit " and its trailing ".", so a probe halfway across
        // the paragraph is inside the linked region for any plausible
        // proportional font.
        let linked_x = para.x + para.w * 0.5;
        assert_eq!(
            link_at(&tree, &state, (linked_x, cy)).as_deref(),
            Some(URL),
            "clicking inside the linked run should surface its URL",
        );
    }

    #[test]
    fn selection_point_for_mixed_inline_respects_math_widths() {
        use crate::selection::SelectionSource;

        const TEXT_A: &str = "alpha ";
        const TEXT_B: &str = " middle ";
        let object = "\u{fffc}";
        let visible = format!("{TEXT_A}{object}{TEXT_B}{object}");
        let expr_a = crate::math::parse_tex(r"\frac{a+b}{c+d}").expect("fixture TeX parses");
        let expr_b = crate::math::parse_tex(r"\sqrt{x_1+x_2}").expect("fixture TeX parses");
        let mut tree = column([crate::text_runs([
            crate::text(TEXT_A),
            crate::math_inline(expr_a.clone()),
            crate::text(TEXT_B),
            crate::math_inline(expr_b.clone()),
        ])
        .key("mixed")
        .selectable()
        .selection_source(SelectionSource::identity(visible))])
        .padding(20.0);
        let mut state = UiState::new();
        layout(&mut tree, &mut state, Rect::new(0.0, 0.0, 700.0, 200.0));
        let para = find_inlines_rect(&tree, &state).expect("inlines rect");

        let text_a_w = metrics::line_width_with_family(
            TEXT_A,
            16.0,
            FontFamily::default(),
            FontWeight::Regular,
            false,
        );
        let math_a_w =
            crate::math::layout_math(&expr_a, 16.0, crate::math::MathDisplay::Inline).width;
        let text_b_w = metrics::line_width_with_family(
            TEXT_B,
            16.0,
            FontFamily::default(),
            FontWeight::Regular,
            false,
        );
        let probe_x = para.x + text_a_w + math_a_w + text_b_w * 0.5;
        let probe_y = para.center_y();
        let point = selection_point_at(&tree, &state, (probe_x, probe_y)).expect("selection point");

        let text_b_start = TEXT_A.len() + object.len();
        let math_b_start = text_b_start + TEXT_B.len();
        assert_eq!(point.key, "mixed");
        assert!(
            point.byte >= text_b_start && point.byte < math_b_start,
            "probe inside second text run must not jump to second math atom; got byte {}, expected {}..{}",
            point.byte,
            text_b_start,
            math_b_start,
        );
    }

    #[test]
    fn hit_test_finds_keyed_button() {
        let (tree, state) = lay_out_counter();
        for key in &["dec", "inc"] {
            let r = find_rect(&tree, &state, key).expect("button rect");
            let center = (r.x + r.w * 0.5, r.y + r.h * 0.5);
            let hit = hit_test(&tree, &state, center);
            assert_eq!(hit.as_deref(), Some(*key));
        }
    }

    #[test]
    fn hit_overflow_expands_pointer_target_but_not_target_rect() {
        let mut tree = column([button("x")
            .key("x")
            .hit_overflow(Sides::all(8.0))
            .width(Size::Fixed(40.0))
            .height(Size::Fixed(24.0))])
        .padding(20.0);
        let mut state = UiState::new();
        layout(&mut tree, &mut state, Rect::new(0.0, 0.0, 200.0, 100.0));

        let rect = find_rect(&tree, &state, "x").expect("button rect");
        let target = hit_test_target(&tree, &state, (rect.x - 4.0, rect.center_y()))
            .expect("left hit overflow should route to the button");
        assert_eq!(target.key, "x");
        assert_eq!(
            target.rect, rect,
            "hit overflow should not change UiTarget::rect used by widgets for pointer math"
        );
    }

    #[test]
    fn paint_overflow_does_not_expand_pointer_target() {
        let mut tree = column([button("x")
            .key("x")
            .paint_overflow(Sides::all(8.0))
            .width(Size::Fixed(40.0))
            .height(Size::Fixed(24.0))])
        .padding(20.0);
        let mut state = UiState::new();
        layout(&mut tree, &mut state, Rect::new(0.0, 0.0, 200.0, 100.0));

        let rect = find_rect(&tree, &state, "x").expect("button rect");
        assert_eq!(
            hit_test(&tree, &state, (rect.x - 4.0, rect.center_y())),
            None,
            "paint overflow is visual only; hit-test requires explicit hit_overflow"
        );
    }

    #[test]
    fn hit_overflow_respects_clipping_ancestor() {
        let mut tree = column([button("x")
            .key("x")
            .hit_overflow(Sides::left(16.0))
            .width(Size::Fixed(40.0))
            .height(Size::Fixed(24.0))])
        .clip()
        .padding(20.0);
        let mut state = UiState::new();
        layout(&mut tree, &mut state, Rect::new(20.0, 0.0, 120.0, 80.0));

        let rect = find_rect(&tree, &state, "x").expect("button rect");
        assert_eq!(
            hit_test(&tree, &state, (rect.x - 8.0, rect.center_y())).as_deref(),
            Some("x"),
            "overflow inside the ancestor clip should remain hittable"
        );
        assert_eq!(
            hit_test(&tree, &state, (19.0, rect.center_y())),
            None,
            "ancestor clip should bound hit overflow"
        );
    }

    #[test]
    fn hit_test_misses_unkeyed_text() {
        let (tree, state) = lay_out_counter();
        let r = find_text_rect(&tree, &state).expect("text rect");
        let center = (r.x + r.w * 0.5, r.y + r.h * 0.5);
        assert!(hit_test(&tree, &state, center).is_none());
    }

    #[test]
    fn hit_test_outside_returns_none() {
        let (tree, state) = lay_out_counter();
        assert!(hit_test(&tree, &state, (-10.0, -10.0)).is_none());
        assert!(hit_test(&tree, &state, (9999.0, 9999.0)).is_none());
    }

    #[test]
    fn hit_test_respects_clipping_ancestor() {
        let mut tree = column([row([
            button("-").key("visible"),
            button("+").key("clipped").width(Size::Fixed(240.0)),
        ])
        .clip()
        .width(Size::Fixed(80.0))]);
        let mut state = UiState::new();
        layout(&mut tree, &mut state, Rect::new(0.0, 0.0, 400.0, 100.0));

        let clipped = find_rect(&tree, &state, "clipped").expect("clipped button rect");
        assert!(hit_test(&tree, &state, (clipped.center_x(), clipped.center_y())).is_none());
    }

    #[test]
    fn hit_test_follows_ancestor_translate() {
        // A keyed button inside a column that is translated horizontally
        // by 120 px must be hit-testable at its translated location, and
        // the un-translated layout slot should miss. This guards against
        // a regression where `.translate()` (paint-time) shifts visuals
        // but hit-testing still uses layout rects, causing clicks on the
        // visually-shifted widget to land on whatever sibling occupies
        // the original layout slot.
        let mut tree = row([
            column([button("A").key("a")]).translate(120.0, 0.0),
            button("B").key("b"),
        ]);
        let mut state = UiState::new();
        layout(&mut tree, &mut state, Rect::new(0.0, 0.0, 400.0, 100.0));

        let untranslated = find_rect(&tree, &state, "a").expect("a layout rect");
        let translated_center = (untranslated.center_x() + 120.0, untranslated.center_y());
        let untranslated_center = (untranslated.center_x(), untranslated.center_y());

        assert_eq!(
            hit_test(&tree, &state, translated_center).as_deref(),
            Some("a"),
            "click at translated location should hit the translated button"
        );
        // The original layout slot may still belong to an ancestor row,
        // but it must not return "a" — that would be the bug.
        assert_ne!(
            hit_test(&tree, &state, untranslated_center).as_deref(),
            Some("a"),
            "click at the un-translated layout slot must not hit the translated button"
        );
    }

    #[test]
    fn hit_test_child_lifted_above_parent_still_hits() {
        // Reproduces the palette swatch bug: a child uses
        // `.scale(1.15).translate(0, -8)` so its painted rect lifts
        // above the parent row's layout rect. A click on the lifted
        // top edge must still find the child — the parent row's bounds
        // should not be a hit-test boundary, since only `clip()` is.
        let mut tree = row([crate::titled_card("c", [crate::text("body")])
            .key("swatch")
            .width(Size::Fixed(120.0))
            .height(Size::Fixed(120.0))
            .scale(1.15)
            .translate(0.0, -20.0)]);
        let mut state = UiState::new();
        layout(&mut tree, &mut state, Rect::new(0.0, 0.0, 400.0, 200.0));

        let layout_rect = find_rect(&tree, &state, "swatch").expect("swatch rect");
        // Painted top is roughly: layout.y - 20 (translate) - layout.h * 0.075 (scale lift).
        let painted_top_y = layout_rect.y - 20.0 - layout_rect.h * 0.075 + 1.0;
        let painted_top_x = layout_rect.center_x();
        assert_eq!(
            hit_test(&tree, &state, (painted_top_x, painted_top_y)).as_deref(),
            Some("swatch"),
            "click on lifted top of scaled+translated child should hit"
        );
    }

    #[test]
    fn hit_test_translate_inherits_to_descendants() {
        // Ancestor translate should propagate through a chain of children.
        let mut tree = column([row([button("X").key("x")]).translate(0.0, 50.0)]);
        let mut state = UiState::new();
        layout(&mut tree, &mut state, Rect::new(0.0, 0.0, 400.0, 200.0));

        let pre = find_rect(&tree, &state, "x").expect("x layout rect");
        let translated = (pre.center_x(), pre.center_y() + 50.0);
        assert_eq!(
            hit_test(&tree, &state, translated).as_deref(),
            Some("x"),
            "ancestor translate must accumulate to descendants"
        );
    }

    #[test]
    fn unkeyed_blocking_node_stops_fallthrough() {
        use crate::tree::stack;
        let mut tree = stack([
            El::new(Kind::Scrim)
                .key("dismiss")
                .fill(crate::tokens::OVERLAY_SCRIM)
                .fill_size(),
            El::new(Kind::Modal)
                .block_pointer()
                .width(Size::Fixed(100.0))
                .height(Size::Fixed(100.0)),
        ])
        .align(Align::Center)
        .justify(Justify::Center)
        .fill_size();
        let mut state = UiState::new();
        layout(&mut tree, &mut state, Rect::new(0.0, 0.0, 300.0, 300.0));

        assert!(hit_test(&tree, &state, (150.0, 150.0)).is_none());
        assert_eq!(
            hit_test(&tree, &state, (10.0, 10.0)).as_deref(),
            Some("dismiss")
        );
    }
}