fenestra-core 0.4.0

Element IR, theme tokens, style resolution, layout, text, and scene building for the fenestra GUI framework
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
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
//! The frame pipeline: element tree -> ids -> style resolution -> taffy
//! layout (with parley-backed text measurement) -> a [`Frame`] of resolved
//! absolute rects -> vello scene. Pure given `(tree, theme, size, scale)`
//! plus the retained [`FrameState`].

use kurbo::{Point, Rect};
use serde::Serialize;
use taffy::prelude::{AvailableSpace, NodeId, Size, TaffyTree};
use vello::Scene;

use crate::element::{Element, Kind, Overlay, OverlayMode, OverlayPlacement, PathData, Semantics};
use crate::frame_state::FrameState;
use crate::id::WidgetId;
use crate::input::{EditorState, InputPaint};
use crate::layout;
use crate::painter;
use crate::style::{AlignItems, Direction, Display, Overflow, Paint, Position, Style};
use crate::text::{Fonts, ResolvedText, resolve_text};
use crate::theme::Theme;
use crate::tokens::{FOCUS_RING, R_FULL};

/// Scrollbar thumb width and edge inset, logical px.
const SCROLLBAR_WIDTH: f64 = 6.0;
const SCROLLBAR_INSET: f64 = 2.0;
/// Wheel scrolling needs at least this much overflow to engage.
const MIN_SCROLL_RANGE: f32 = 0.5;

/// Taffy node context for measured leaves.
enum MeasureCtx {
    Text {
        text: String,
        style: ResolvedText,
    },
    Input {
        /// Current value, measured for multiline height.
        text: String,
        style: ResolvedText,
        multiline: bool,
    },
}

/// Content height of an input leaf: one line for single-line inputs, the
/// wrapped text height (plus the caret line after a trailing newline) for
/// multiline ones.
fn measure_input_height(
    fonts: &mut Fonts,
    text: &str,
    style: &ResolvedText,
    multiline: bool,
    wrap: Option<f32>,
) -> f32 {
    let line = (style.px * style.line_height).ceil();
    if !multiline || text.is_empty() {
        return line;
    }
    // The editor shows a caret line after a trailing newline; measure one.
    let measured: std::borrow::Cow<'_, str> = if text.ends_with('\n') {
        std::borrow::Cow::Owned(format!("{text} "))
    } else {
        std::borrow::Cow::Borrowed(text)
    };
    let (_, h) = fonts.measure(&measured, style, wrap);
    h.max(line)
}

/// Intrinsic width of an unconstrained input, logical px.
const INPUT_DEFAULT_WIDTH: f32 = 220.0;

enum PaintKind {
    Box,
    Text { text: String, style: ResolvedText },
    Path(PathData),
    Input(InputPaint),
    Image(crate::element::ImageData),
}

/// Interactivity facts the frame needs for hit/focus queries.
#[derive(Debug, Clone, Copy, Default)]
struct NodeMeta {
    /// Focusable and enabled.
    focusable: bool,
    focus_ring: bool,
}

/// Scroll geometry of one scrollable container, resolved for this frame.
struct ScrollInfo {
    offset: f32,
    thumb: Option<Rect>,
    alpha: f32,
    /// Content actually overflows; wheel routing skips containers that fit.
    can_scroll: bool,
}

/// One node with its final absolute logical rect.
struct FrameNode {
    id: WidgetId,
    kind: PaintKind,
    style: Style,
    rect: Rect,
    /// Effective clip rect inherited from ancestors (None = unclipped).
    visible: Option<Rect>,
    scroll: Option<ScrollInfo>,
    meta: NodeMeta,
    /// Continuous rotation period (ms) for spinner paths.
    spin: Option<f32>,
    /// Accessibility projection: role/state, name, and value.
    access: (Option<Semantics>, Option<String>, Option<String>),
    children: Vec<FrameNode>,
}

/// One node of a frame's accessibility projection (see
/// [`Frame::access_tree`]): plain data, usable headlessly in tests and
/// mapped to AccessKit by the windowed shell.
#[derive(Debug, Clone)]
pub struct AccessNode {
    /// Stable widget identity (also the platform node id).
    pub id: WidgetId,
    /// Role and state, when the element exposes one.
    pub semantics: Option<Semantics>,
    /// Accessible name.
    pub label: Option<String>,
    /// Current value (text inputs).
    pub value: Option<String>,
    /// Layout rect in logical px.
    pub rect: Rect,
    /// Keyboard focusable (and enabled).
    pub focusable: bool,
    /// Children in paint order.
    pub children: Vec<AccessNode>,
}

/// One realized overlay, painted above the root in stack order.
struct OverlayFrame {
    id: WidgetId,
    mode: OverlayMode,
    node: FrameNode,
    /// Enter progress 0..=1 (drives backdrop fade and slide-up).
    progress: f32,
    backdrop: bool,
    trap_focus: bool,
    hittable: bool,
}

/// A laid-out frame: resolved styles and absolute rects for every element.
/// Paint, input routing, and debug dumps all read from this one structure.
pub struct Frame {
    root: FrameNode,
    overlays: Vec<OverlayFrame>,
    /// Anchor id -> (overlay id, mode) for every overlay child present in
    /// the tree (open or not); dispatch uses it for toggling.
    overlay_anchors: std::collections::HashMap<WidgetId, (WidgetId, OverlayMode)>,
    canvas: Rect,
    scale: f64,
    thumb_color: crate::Color,
    ring_color: crate::Color,
    /// `true` while any scrollbar fade, style transition, caret blink, or
    /// overlay animation is running; the runner keeps scheduling frames.
    pub animating: bool,
}

// ---------------------------------------------------------------- building

struct BuiltNode {
    taffy: NodeId,
    id: WidgetId,
    kind: PaintKind,
    style: Style,
    focusable: bool,
    disabled: bool,
    spin: Option<f32>,
    /// Scroll containers: pin to the bottom while content grows.
    stick_bottom: bool,
    /// Accessibility projection: role/state, name, and value.
    access: (Option<Semantics>, Option<String>, Option<String>),
    children: Vec<BuiltNode>,
}

/// Resolves an element's style against the theme: applies the deferred
/// `themed` styling, overlays interaction variants from state, expands
/// shadow tokens, fills role-based defaults, and advances any transition.
/// Returns the style to paint and whether a transition is still running.
fn resolve<Msg>(
    el: &Element<Msg>,
    theme: &Theme,
    state: &mut FrameState,
    id: WidgetId,
) -> (Style, bool) {
    let mut style = el.style.clone();
    if let Some(f) = &el.themed {
        style = f(theme, style);
    }
    if !el.disabled {
        if state.is_hovered(id)
            && let Some(f) = &el.hover_style
        {
            style = f(theme, style);
        }
        if state.is_active(id)
            && let Some(f) = &el.active_style
        {
            style = f(theme, style);
        }
        if state.focused() == Some(id)
            && let Some(f) = &el.focus_style
        {
            style = f(theme, style);
        }
    }
    if let Some(token) = style.shadow_token {
        let mut layers = theme.shadow(token);
        layers.append(&mut style.shadows);
        style.shadows = layers;
    }
    if matches!(el.kind, Kind::Divider) && style.fill.is_none() {
        style.fill = Some(Paint::Solid(theme.border_subtle));
    }
    if style.text.color.is_none() {
        style.text.color = Some(theme.text);
    }

    let mut animating = false;
    if let Some(transition) = el.transition
        && !state.reduced_motion
    {
        let now = state.now();
        let seen = state.frame_no;
        let anim = state
            .anims
            .entry(id)
            .or_insert_with(|| crate::anim::Anim::new(style.clone(), now, seen));
        let (animated, running) = anim.advance(&style, transition, now, seen);
        style = animated;
        animating = running;
    }
    if let Some(kf) = &el.keyframes {
        style = crate::anim::sample_keyframes(kf, theme, &style, state.now(), state.reduced_motion);
        // Looping timelines repaint for as long as they are mounted.
        animating |= !state.reduced_motion && !kf.stops.is_empty();
    }
    (style, animating)
}

/// An overlay child discovered during the main build pass: the path
/// navigates from the root element to the overlay element.
struct PendingOverlay {
    anchor: WidgetId,
    id: WidgetId,
    def: Overlay,
    path: Vec<usize>,
}

#[expect(
    clippy::too_many_arguments,
    reason = "internal recursion carries build context"
)]
fn build<Msg>(
    el: &Element<Msg>,
    theme: &Theme,
    tree: &mut TaffyTree<MeasureCtx>,
    state: &mut FrameState,
    animating: &mut bool,
    id: WidgetId,
    in_stack: bool,
    path: &mut Vec<usize>,
    pending: &mut Vec<PendingOverlay>,
    // Canvas height: the materialization viewport for virtual lists.
    viewport: f32,
) -> BuiltNode {
    if el.autofocus && !el.disabled {
        // Focus when newly appearing (absent last frame or a different
        // element), without a keyboard focus ring.
        let newly = match state.autofocus_last {
            Some((prev, seen)) => prev != id || seen + 1 < state.frame_no,
            None => true,
        };
        state.autofocus_last = Some((id, state.frame_no));
        if newly {
            state.focus = Some(id);
            state.focus_visible = false;
        }
    }
    let (style, anim) = resolve(el, theme, state, id);
    *animating |= anim;
    // Virtual containers swap their declared children for the materialized
    // window. Overlays inside virtual rows are unsupported (the overlay
    // path machinery indexes the declared tree).
    let generated: Vec<Element<Msg>>;
    let child_slice: &[Element<Msg>] = match &el.virtual_rows {
        Some(v) => {
            generated = expand_virtual(v, state.scroll_offset(id), viewport);
            &generated
        }
        None => &el.children,
    };
    let children: Vec<BuiltNode> = child_slice
        .iter()
        .enumerate()
        .filter_map(|(i, c)| {
            let child_id = id.child(i, c.key.as_deref());
            if let Some(def) = c.overlay {
                // Overlay children leave normal flow entirely; they are
                // built separately once openness is known.
                let mut overlay_path = path.clone();
                overlay_path.push(i);
                pending.push(PendingOverlay {
                    anchor: id,
                    id: child_id,
                    def,
                    path: overlay_path,
                });
                return None;
            }
            path.push(i);
            let node = build(
                c, theme, tree, state, animating, child_id, el.stack, path, pending, viewport,
            );
            path.pop();
            Some(node)
        })
        .collect();
    let taffy_style = layout::to_taffy(&style, in_stack);
    let (taffy, kind) = match &el.kind {
        Kind::Text(content) => {
            let resolved = resolve_text(&style.text, theme);
            let ctx = MeasureCtx::Text {
                text: content.clone(),
                style: resolved,
            };
            (
                tree.new_leaf_with_context(taffy_style, ctx)
                    .expect("taffy new_leaf_with_context"),
                PaintKind::Text {
                    text: content.clone(),
                    style: resolved,
                },
            )
        }
        Kind::Input(data) => {
            let resolved = resolve_text(&style.text, theme);
            // Sync the retained editor with the app-provided value.
            let now = state.now();
            let frame_no = state.frame_no;
            let editor = state
                .editors
                .entry(id)
                .or_insert_with(|| EditorState::new(&resolved, now, data.multiline));
            editor.sync(&data.value, &resolved);
            editor.multiline = data.multiline;
            editor.seen = frame_no;
            let focused = state.focused() == Some(id);
            if focused && !state.reduced_motion {
                // Caret blink needs repaints while focused.
                *animating = true;
            }
            (
                tree.new_leaf_with_context(
                    taffy_style,
                    MeasureCtx::Input {
                        text: data.value.clone(),
                        style: resolved,
                        multiline: data.multiline,
                    },
                )
                .expect("taffy new_leaf_with_context"),
                PaintKind::Input(InputPaint {
                    placeholder: data.placeholder.clone(),
                    style: resolved,
                    placeholder_color: theme.text_subtle,
                    caret_color: theme.accent,
                    selection_color: theme.accent.with_alpha(0.25),
                    focused,
                    pad_x: f64::from(style.padding.left),
                    pad_y: f64::from(style.padding.top),
                    multiline: data.multiline,
                }),
            )
        }
        Kind::Path(data) => (
            tree.new_leaf(taffy_style).expect("taffy new_leaf"),
            PaintKind::Path(data.clone()),
        ),
        Kind::Image(data) => (
            tree.new_leaf(taffy_style).expect("taffy new_leaf"),
            PaintKind::Image(data.clone()),
        ),
        Kind::Box | Kind::Divider => {
            let node = if children.is_empty() {
                tree.new_leaf(taffy_style).expect("taffy new_leaf")
            } else {
                let ids: Vec<NodeId> = children.iter().map(|c| c.taffy).collect();
                tree.new_with_children(taffy_style, &ids)
                    .expect("taffy new_with_children")
            };
            (node, PaintKind::Box)
        }
    };
    if el.spin.is_some() && !state.reduced_motion {
        // Spinners rotate continuously.
        *animating = true;
    }
    // Accessibility projection: explicit semantics win; text, image, and
    // input leaves project automatically.
    let semantics = el.semantics.or(match &el.kind {
        Kind::Text(_) => Some(Semantics::Label),
        Kind::Image(_) => Some(Semantics::Image),
        Kind::Input(data) => Some(Semantics::TextInput {
            multiline: data.multiline,
        }),
        Kind::Box | Kind::Divider | Kind::Path(_) => None,
    });
    let label = el.label.clone().or(match &el.kind {
        Kind::Text(content) => Some(content.clone()),
        _ => None,
    });
    let value = match &el.kind {
        Kind::Input(data) => Some(data.value.clone()),
        _ => None,
    };

    BuiltNode {
        taffy,
        id,
        kind,
        style,
        focusable: el.focusable,
        disabled: el.disabled,
        spin: el.spin,
        stick_bottom: el.stick_bottom,
        access: (semantics, label, value),
        children,
    }
}

/// The materialized index window for a virtual list: the rows overlapping
/// `offset..offset+viewport`, padded by a fixed overscan. Shared by the
/// frame build and event dispatch so ids always agree.
pub(crate) fn virtual_window(
    count: usize,
    row_height: f32,
    offset: f32,
    viewport: f32,
) -> std::ops::Range<usize> {
    const OVERSCAN: usize = 8;
    if count == 0 || row_height <= 0.0 || row_height.is_nan() || !viewport.is_finite() {
        return 0..0;
    }
    let offset = offset.max(0.0);
    #[expect(clippy::cast_possible_truncation, reason = "row indices fit in usize")]
    #[expect(clippy::cast_sign_loss, reason = "clamped non-negative above")]
    let first = (offset / row_height).floor() as usize;
    #[expect(clippy::cast_possible_truncation, reason = "row indices fit in usize")]
    #[expect(clippy::cast_sign_loss, reason = "clamped non-negative above")]
    let last = ((offset + viewport.max(0.0)) / row_height).ceil() as usize;
    first.saturating_sub(OVERSCAN).min(count)..last.saturating_add(OVERSCAN).min(count)
}

/// Builds one virtual row with the shared invariants applied: keyed by
/// index (so identity is stable as the window slides) and forced to the
/// declared row height.
pub(crate) fn materialize_virtual_row<Msg>(
    v: &crate::element::VirtualData<Msg>,
    i: usize,
) -> Element<Msg> {
    let mut row = (v.builder)(i);
    if row.key.is_none() {
        row = row.id(&format!("v{i}"));
    }
    row.h(v.row_height).shrink0()
}

/// Expands a virtual container into spacer + visible rows + spacer.
fn expand_virtual<Msg>(
    v: &crate::element::VirtualData<Msg>,
    offset: f32,
    viewport: f32,
) -> Vec<Element<Msg>> {
    let window = virtual_window(v.count, v.row_height, offset, viewport);
    let mut out = Vec::with_capacity(window.len() + 2);
    #[expect(clippy::cast_precision_loss, reason = "row counts fit in f32")]
    let top = window.start as f32 * v.row_height;
    #[expect(clippy::cast_precision_loss, reason = "row counts fit in f32")]
    let bottom = (v.count - window.end) as f32 * v.row_height;
    out.push(crate::element::div().h(top).w_full().shrink0());
    for i in window {
        out.push(materialize_virtual_row(v, i));
    }
    out.push(crate::element::div().h(bottom).w_full().shrink0());
    out
}

/// Wrap width for a text leaf given taffy's measure inputs.
fn wrap_width(known: Option<f32>, available: AvailableSpace) -> Option<f32> {
    known.or(match available {
        AvailableSpace::Definite(w) => Some(w),
        AvailableSpace::MaxContent => None,
        AvailableSpace::MinContent => Some(0.0),
    })
}

/// The baseline of a child for `items_baseline` rows: true first-line
/// baseline for text, bottom edge for boxes (CSS synthesized baseline).
fn child_baseline(fonts: &mut Fonts, tree: &TaffyTree<MeasureCtx>, node: &BuiltNode) -> f64 {
    let l = tree.layout(node.taffy).expect("taffy layout");
    match &node.kind {
        PaintKind::Text { text, style } => {
            f64::from(fonts.first_baseline(text, style, Some(l.size.width)))
        }
        PaintKind::Box | PaintKind::Path(_) | PaintKind::Input(_) | PaintKind::Image(_) => {
            f64::from(l.size.height)
        }
    }
}

struct Realize<'a> {
    tree: &'a TaffyTree<MeasureCtx>,
    fonts: &'a mut Fonts,
    state: &'a mut FrameState,
    animating: bool,
}

impl Realize<'_> {
    /// Converts a built node into a frame node with absolute rects, applying
    /// baseline shifts, scroll offsets, and clip propagation.
    fn realize(&mut self, node: BuiltNode, origin: Point, visible: Option<Rect>) -> FrameNode {
        let l = self.tree.layout(node.taffy).expect("taffy layout");
        let x = origin.x + f64::from(l.location.x);
        let y = origin.y + f64::from(l.location.y);
        let rect = Rect::new(
            x,
            y,
            x + f64::from(l.size.width),
            y + f64::from(l.size.height),
        );

        // Scroll resolution: clamp the persisted offset to the content range.
        let scroll = (node.style.overflow_y == Overflow::Scroll).then(|| {
            let max = (l.content_size.height - l.size.height).max(0.0);
            let offset = if max >= MIN_SCROLL_RANGE {
                self.state.clamp_scroll(node.id, max, node.stick_bottom)
            } else {
                self.state.clamp_scroll(node.id, 0.0, node.stick_bottom)
            };
            let alpha = if max >= MIN_SCROLL_RANGE {
                self.state.scrollbar_alpha(node.id)
            } else {
                0.0
            };
            self.animating |= self.state.scrollbar_animating(node.id);
            let thumb = (alpha > 0.0 && max >= MIN_SCROLL_RANGE).then(|| {
                let track_h = rect.height() - 2.0 * SCROLLBAR_INSET;
                let content_h = f64::from(l.content_size.height);
                let thumb_h = (track_h * rect.height() / content_h).max(24.0).min(track_h);
                let denom = f64::from(max);
                let t = if denom > 0.0 {
                    f64::from(offset) / denom
                } else {
                    0.0
                };
                let thumb_y = rect.y0 + SCROLLBAR_INSET + t * (track_h - thumb_h);
                Rect::new(
                    rect.x1 - SCROLLBAR_INSET - SCROLLBAR_WIDTH,
                    thumb_y,
                    rect.x1 - SCROLLBAR_INSET,
                    thumb_y + thumb_h,
                )
            });
            ScrollInfo {
                offset,
                thumb,
                alpha,
                can_scroll: max >= MIN_SCROLL_RANGE,
            }
        });

        // Children visibility: intersect with this node's bounds when clipping.
        let child_visible = if node.style.clip {
            Some(visible.map_or(rect, |v| v.intersect(rect)))
        } else {
            visible
        };
        let scroll_dy = scroll.as_ref().map_or(0.0, |s| f64::from(s.offset));
        let child_origin = Point::new(x, y - scroll_dy);

        // Baseline rows: shift in-flow children so first baselines align.
        let baseline_offsets: Option<Vec<f64>> = (node.style.display == Display::Flex
            && node.style.direction == Direction::Row
            && node.style.align_items == AlignItems::Baseline)
            .then(|| {
                let baselines: Vec<f64> = node
                    .children
                    .iter()
                    .map(|c| {
                        if c.style.position == Position::Absolute {
                            0.0
                        } else {
                            child_baseline(self.fonts, self.tree, c)
                        }
                    })
                    .collect();
                let target = baselines.iter().copied().fold(0.0, f64::max);
                baselines
                    .iter()
                    .zip(&node.children)
                    .map(|(b, c)| {
                        if c.style.position == Position::Absolute {
                            0.0
                        } else {
                            target - b
                        }
                    })
                    .collect()
            });

        let children = node
            .children
            .into_iter()
            .enumerate()
            .map(|(i, child)| {
                let dy = baseline_offsets.as_ref().map_or(0.0, |o| o[i]);
                self.realize(
                    child,
                    Point::new(child_origin.x, child_origin.y + dy),
                    child_visible,
                )
            })
            .collect();

        let meta = NodeMeta {
            focusable: node.focusable && !node.disabled,
            focus_ring: node.focusable
                && !node.disabled
                && self.state.focused() == Some(node.id)
                && self.state.focus_visible,
        };
        FrameNode {
            id: node.id,
            kind: node.kind,
            style: node.style,
            rect,
            visible,
            scroll,
            meta,
            spin: node.spin,
            access: node.access,
            children,
        }
    }
}

/// Lays out an element tree into a [`Frame`] at the given logical size and
/// DPI scale. A root with `Auto` width/height is stretched to the canvas.
pub fn build_frame<Msg>(
    root: &Element<Msg>,
    theme: &Theme,
    fonts: &mut Fonts,
    state: &mut FrameState,
    size: (f32, f32),
    scale: f64,
) -> Frame {
    let mut tree: TaffyTree<MeasureCtx> = TaffyTree::new();
    state.frame_no += 1;
    let mut transitions_running = false;
    let mut path = Vec::new();
    let mut pending = Vec::new();
    let mut node = build(
        root,
        theme,
        &mut tree,
        state,
        &mut transitions_running,
        WidgetId::ROOT,
        false,
        &mut path,
        &mut pending,
        size.1,
    );
    if root.style.width == crate::style::Length::Auto {
        node.style.width = crate::style::Length::Px(size.0);
    }
    if root.style.height == crate::style::Length::Auto {
        node.style.height = crate::style::Length::Px(size.1);
    }
    tree.set_style(node.taffy, layout::to_taffy(&node.style, false))
        .expect("taffy set_style");
    tree.compute_layout_with_measure(
        node.taffy,
        Size {
            width: AvailableSpace::Definite(size.0),
            height: AvailableSpace::Definite(size.1),
        },
        |known, available, _id, ctx, _style| match ctx {
            Some(MeasureCtx::Text { text, style }) => {
                let (w, h) = fonts.measure(text, style, wrap_width(known.width, available.width));
                Size {
                    width: known.width.unwrap_or(w),
                    height: known.height.unwrap_or(h),
                }
            }
            Some(MeasureCtx::Input {
                text,
                style,
                multiline,
            }) => Size {
                width: known.width.unwrap_or(INPUT_DEFAULT_WIDTH),
                height: known.height.unwrap_or_else(|| {
                    measure_input_height(
                        fonts,
                        text,
                        style,
                        *multiline,
                        wrap_width(known.width, available.width),
                    )
                }),
            },
            None => Size::ZERO,
        },
    )
    .expect("taffy compute_layout");

    let mut realize = Realize {
        tree: &tree,
        fonts,
        state,
        animating: false,
    };
    let root_node = realize.realize(node, Point::ORIGIN, None);
    let mut animating = realize.animating || transitions_running;
    let canvas = Rect::new(0.0, 0.0, f64::from(size.0), f64::from(size.1));

    // ---- overlay passes: openness, layout against the canvas, placement.
    let mut overlay_anchors = std::collections::HashMap::new();
    let mut overlays: Vec<OverlayFrame> = Vec::new();
    let mut queue = pending;
    let mut present: Vec<WidgetId> = Vec::new();
    while !queue.is_empty() {
        let batch = std::mem::take(&mut queue);
        for p in batch {
            present.push(p.id);
            overlay_anchors.insert(p.anchor, (p.id, p.def.mode));
            let open = match p.def.mode {
                OverlayMode::Open => {
                    state.open_overlay(p.id);
                    true
                }
                OverlayMode::Toggle => state.overlay_open(p.id),
                OverlayMode::Hover { delay_ms } => {
                    match state.hovered_for(p.anchor) {
                        Some(t) if t >= f64::from(delay_ms) / 1000.0 => true,
                        Some(_) => {
                            // Waiting out the delay: keep frames coming.
                            animating = true;
                            false
                        }
                        None => false,
                    }
                }
            };
            if !open {
                continue;
            }
            let Some(el) = element_at(root, &p.path) else {
                continue;
            };
            // Anchor rect from the realized main tree or earlier overlays.
            let anchor_rect = rect_in(&root_node, p.anchor)
                .or_else(|| overlays.iter().find_map(|o| rect_in(&o.node, p.anchor)))
                .unwrap_or(canvas);

            let mut opath = Vec::new();
            let mut nested = Vec::new();
            let built = build(
                el,
                theme,
                &mut tree,
                state,
                &mut animating,
                p.id,
                false,
                &mut opath,
                &mut nested,
                size.1,
            );
            // Nested overlay paths are relative to `el`; rebase onto root.
            for mut q in nested {
                let mut full = p.path.clone();
                full.extend(q.path.iter());
                q.path = full;
                queue.push(q);
            }
            tree.compute_layout_with_measure(
                built.taffy,
                Size {
                    width: AvailableSpace::Definite(size.0),
                    height: AvailableSpace::Definite(size.1),
                },
                |known, available, _id, ctx, _style| match ctx {
                    Some(MeasureCtx::Text { text, style }) => {
                        let (w, h) =
                            fonts.measure(text, style, wrap_width(known.width, available.width));
                        Size {
                            width: known.width.unwrap_or(w),
                            height: known.height.unwrap_or(h),
                        }
                    }
                    Some(MeasureCtx::Input {
                        text,
                        style,
                        multiline,
                    }) => Size {
                        width: known.width.unwrap_or(INPUT_DEFAULT_WIDTH),
                        height: known.height.unwrap_or_else(|| {
                            measure_input_height(
                                fonts,
                                text,
                                style,
                                *multiline,
                                wrap_width(known.width, available.width),
                            )
                        }),
                    },
                    None => Size::ZERO,
                },
            )
            .expect("taffy compute_layout (overlay)");
            let measured = tree.layout(built.taffy).expect("overlay layout").size;
            let (w, h) = (f64::from(measured.width), f64::from(measured.height));

            // Enter animation progress.
            let progress = if state.reduced_motion {
                1.0
            } else {
                let opened = state.overlay_opened.get(&p.id).copied().unwrap_or(0.0);
                let t = ((state.now() - opened) / 0.2).clamp(0.0, 1.0);
                #[expect(clippy::cast_possible_truncation, reason = "progress is 0..=1")]
                {
                    crate::tokens::EASE_STANDARD.eval(t as f32)
                }
            };
            if progress < 1.0 {
                animating = true;
            }

            let state_pointer = state.pointer;
            let origin = match p.def.placement {
                OverlayPlacement::Below { gap } => {
                    let gap = f64::from(gap);
                    let y = if anchor_rect.y1 + gap + h <= canvas.y1
                        || anchor_rect.y0 - gap - h < canvas.y0
                    {
                        anchor_rect.y1 + gap
                    } else {
                        anchor_rect.y0 - gap - h
                    };
                    Point::new(anchor_rect.x0.clamp(canvas.x0, (canvas.x1 - w).max(0.0)), y)
                }
                OverlayPlacement::BelowCenter { gap } => {
                    let gap = f64::from(gap);
                    let x = anchor_rect.x0 + (anchor_rect.width() - w) * 0.5;
                    Point::new(
                        x.clamp(canvas.x0, (canvas.x1 - w).max(0.0)),
                        anchor_rect.y1 + gap,
                    )
                }
                OverlayPlacement::TopRight { margin } => {
                    let m = f64::from(margin);
                    Point::new((canvas.x1 - w - m).max(canvas.x0), canvas.y0 + m)
                }
                OverlayPlacement::Pointer { gap } => {
                    // Pin where the pointer was when the overlay opened.
                    let fallback = (
                        #[expect(clippy::cast_possible_truncation, reason = "logical px")]
                        {
                            anchor_rect.x0 as f32
                        },
                        #[expect(clippy::cast_possible_truncation, reason = "logical px")]
                        {
                            anchor_rect.y1 as f32
                        },
                    );
                    let (px, py) = *state
                        .pointer_pins
                        .entry(p.id)
                        .or_insert_with(|| state_pointer.unwrap_or(fallback));
                    let g = f64::from(gap);
                    Point::new(
                        (f64::from(px) + g).clamp(canvas.x0, (canvas.x1 - w).max(canvas.x0)),
                        (f64::from(py) + g).clamp(canvas.y0, (canvas.y1 - h).max(canvas.y0)),
                    )
                }
                OverlayPlacement::Center => {
                    // Slide up 8px as the modal enters.
                    let dy = 8.0 * (1.0 - f64::from(progress));
                    Point::new(
                        canvas.x0 + (canvas.width() - w) * 0.5,
                        canvas.y0 + (canvas.height() - h) * 0.5 + dy,
                    )
                }
            };

            let mut orealize = Realize {
                tree: &tree,
                fonts,
                state,
                animating: false,
            };
            let onode = orealize.realize(built, origin, None);
            animating |= orealize.animating;

            overlays.push(OverlayFrame {
                id: p.id,
                mode: p.def.mode,
                node: onode,
                progress,
                backdrop: p.def.backdrop,
                trap_focus: p.def.trap_focus,
                hittable: !matches!(p.def.mode, OverlayMode::Hover { .. }),
            });
        }
    }
    // Drop stale stack entries for overlays no longer in the tree.
    let stale: Vec<WidgetId> = state
        .overlays
        .iter()
        .copied()
        .filter(|id| !present.contains(id))
        .collect();
    for id in stale {
        state.close_overlay(id);
    }
    // Stack order: state.overlays is bottom-to-top; sort realized overlays.
    overlays.sort_by_key(|o| {
        state
            .overlays
            .iter()
            .position(|id| *id == o.id)
            .unwrap_or(usize::MAX)
    });

    let frame_no = state.frame_no;
    state.anims.retain(|_, a| a.seen == frame_no);
    state.editors.retain(|_, e| e.seen == frame_no);
    state.gc_scroll(frame_no);

    Frame {
        root: root_node,
        overlays,
        overlay_anchors,
        canvas,
        scale,
        thumb_color: theme.text_subtle,
        ring_color: theme.accent.with_alpha(FOCUS_RING.alpha),
        animating,
    }
}

/// Navigates the element tree by child indices.
fn element_at<'a, Msg>(root: &'a Element<Msg>, path: &[usize]) -> Option<&'a Element<Msg>> {
    let mut el = root;
    for &i in path {
        el = el.children.get(i)?;
    }
    Some(el)
}

/// Finds a node's rect within a realized subtree.
fn rect_in(node: &FrameNode, id: WidgetId) -> Option<Rect> {
    if node.id == id {
        return Some(node.rect);
    }
    node.children.iter().find_map(|c| rect_in(c, id))
}

/// Convenience: lays out and paints in one call with throwaway state.
pub fn build_scene<Msg>(
    root: &Element<Msg>,
    theme: &Theme,
    fonts: &mut Fonts,
    size: (f32, f32),
) -> Scene {
    let mut state = FrameState::new();
    state.reduced_motion = true;
    let frame = build_frame(root, theme, fonts, &mut state, size, 1.0);
    frame.paint(fonts, &mut state)
}

// ---------------------------------------------------------------- painting

impl Frame {
    /// Paints the frame into a fresh scene (logical coordinates). Needs the
    /// retained state for editor layouts and caret blink phase.
    pub fn paint(&self, fonts: &mut Fonts, state: &mut FrameState) -> Scene {
        // Recomputed below when a focused editor paints its caret.
        state.ime_caret = None;
        let mut scene = Scene::new();
        self.paint_node(&mut scene, fonts, state, &self.root);
        for overlay in &self.overlays {
            if overlay.backdrop {
                let alpha = 0.4 * overlay.progress;
                scene.fill(
                    peniko::Fill::NonZero,
                    kurbo::Affine::IDENTITY,
                    crate::Color::new([0.0, 0.0, 0.0, alpha]),
                    None,
                    &self.canvas,
                );
            }
            let faded = overlay.progress < 1.0;
            if faded {
                scene.push_layer(
                    peniko::Fill::NonZero,
                    peniko::Mix::Normal,
                    overlay.progress,
                    kurbo::Affine::IDENTITY,
                    &self.canvas,
                );
            }
            self.paint_node(&mut scene, fonts, state, &overlay.node);
            if faded {
                scene.pop_layer();
            }
        }
        scene
    }

    fn paint_node(
        &self,
        scene: &mut Scene,
        fonts: &mut Fonts,
        state: &mut FrameState,
        node: &FrameNode,
    ) {
        if node.style.display == Display::None {
            return;
        }
        let layers = painter::push_box(scene, &node.style, node.rect, self.canvas, self.scale);
        if node.meta.focus_ring {
            painter::focus_ring(scene, node.rect, node.style.corner_radius, self.ring_color);
        }
        match &node.kind {
            PaintKind::Text { text, style } => fonts.paint(scene, text, style, node.rect),
            PaintKind::Path(data) => {
                let color = node.style.text.color.unwrap_or(self.thumb_color);
                let rotation = node
                    .spin
                    .filter(|_| !state.reduced_motion)
                    .map_or(0.0, |p| {
                        let period = f64::from(p.max(1.0)) / 1000.0;
                        (state.now() % period) / period * std::f64::consts::TAU
                    });
                painter::draw_path_rotated(
                    scene,
                    data,
                    node.style.path_trim,
                    color,
                    node.rect,
                    rotation,
                );
            }
            PaintKind::Input(data) => {
                let now = state.now();
                let reduced = state.reduced_motion;
                if let Some(editor) = state.editors.get_mut(&node.id) {
                    let caret =
                        crate::input::paint(scene, fonts, editor, data, node.rect, now, reduced);
                    if caret.is_some() {
                        state.ime_caret = caret;
                    }
                }
            }
            PaintKind::Image(data) => {
                painter::draw_image(scene, &data.image, node.rect, node.style.corner_radius);
            }
            PaintKind::Box => {}
        }
        for child in &node.children {
            self.paint_node(scene, fonts, state, child);
        }
        if let Some(scroll) = &node.scroll
            && let Some(thumb) = scroll.thumb
        {
            let color = self.thumb_color.multiply_alpha(scroll.alpha * 0.6);
            painter::fill_rounded(scene, thumb, R_FULL, color);
        }
        painter::pop_box(scene, layers);
    }

    // ------------------------------------------------------------- queries

    /// Canvas height in logical px: the virtual-list materialization
    /// viewport used by event dispatch.
    pub(crate) fn canvas_height(&self) -> f32 {
        #[expect(clippy::cast_possible_truncation, reason = "canvas sizes fit in f32")]
        {
            self.canvas.height() as f32
        }
    }

    /// The accessibility projection of this frame: roles, names, values,
    /// logical rects, and focusability, with open overlays appended after
    /// the root content in paint order. Headless and dependency-free; the
    /// windowed shell maps it to the platform tree via AccessKit.
    pub fn access_tree(&self) -> AccessNode {
        fn project(node: &FrameNode) -> AccessNode {
            let (semantics, label, value) = node.access.clone();
            AccessNode {
                id: node.id,
                semantics,
                label,
                value,
                rect: node.rect,
                focusable: node.meta.focusable,
                children: node.children.iter().map(project).collect(),
            }
        }
        let mut root = project(&self.root);
        for overlay in &self.overlays {
            root.children.push(project(&overlay.node));
        }
        root
    }

    /// The scrollable that keyboard paging should drive: the nearest
    /// scrollable ancestor of `focus` (itself included), else the first
    /// overflowing scrollable in paint order. Returns its rect too (the
    /// paging viewport).
    pub(crate) fn scroll_target_for(&self, focus: Option<WidgetId>) -> Option<(WidgetId, Rect)> {
        fn path_scrollables(
            node: &FrameNode,
            id: WidgetId,
            out: &mut Vec<(WidgetId, Rect)>,
        ) -> bool {
            let here = node
                .scroll
                .as_ref()
                .is_some_and(|s| s.can_scroll)
                .then_some((node.id, node.rect));
            if let Some(h) = here {
                out.push(h);
            }
            if node.id == id {
                return true;
            }
            for child in &node.children {
                if path_scrollables(child, id, out) {
                    return true;
                }
            }
            if here.is_some() {
                out.pop();
            }
            false
        }
        fn first_scrollable(node: &FrameNode) -> Option<(WidgetId, Rect)> {
            if node.scroll.as_ref().is_some_and(|s| s.can_scroll) {
                return Some((node.id, node.rect));
            }
            node.children.iter().find_map(first_scrollable)
        }
        if let Some(focus) = focus {
            let mut path = Vec::new();
            let found = path_scrollables(&self.root, focus, &mut path)
                || self.overlays.iter().any(|o| {
                    path.clear();
                    path_scrollables(&o.node, focus, &mut path)
                });
            if found && let Some(last) = path.last() {
                return Some(*last);
            }
        }
        first_scrollable(&self.root)
            .or_else(|| self.overlays.iter().find_map(|o| first_scrollable(&o.node)))
    }

    /// The deepest scrollable container whose visible area contains `point`
    /// and which actually has overflowing content.
    pub fn scrollable_at(&self, point: Point) -> Option<WidgetId> {
        fn walk(node: &FrameNode, point: Point) -> Option<WidgetId> {
            if node.style.display == Display::None {
                return None;
            }
            if let Some(v) = node.visible
                && !v.contains(point)
            {
                return None;
            }
            if !node.rect.contains(point) && node.style.clip {
                return None;
            }
            // Children win over the container (deepest scrollable first);
            // later children paint on top, so walk them in reverse.
            for child in node.children.iter().rev() {
                if let Some(id) = walk(child, point) {
                    return Some(id);
                }
            }
            (node.scroll.as_ref().is_some_and(|s| s.can_scroll) && node.rect.contains(point))
                .then_some(node.id)
        }
        walk(&self.root, point)
    }

    /// All elements containing `point` along the topmost branch (later
    /// siblings paint on top and win), ordered root to deepest. Clip-aware:
    /// content scrolled out of a clipped container does not hit.
    pub fn hit_chain(&self, point: Point) -> Vec<WidgetId> {
        // Overlays hit-test first, topmost first; a modal backdrop swallows
        // everything beneath it.
        for overlay in self.overlays.iter().rev() {
            if !overlay.hittable {
                continue;
            }
            let mut chain = Vec::new();
            if Self::walk_hit(&overlay.node, point, &mut chain) {
                return chain;
            }
            if overlay.backdrop {
                return Vec::new();
            }
        }
        let mut chain = Vec::new();
        Self::walk_hit(&self.root, point, &mut chain);
        chain
    }

    fn walk_hit(node: &FrameNode, point: Point, out: &mut Vec<WidgetId>) -> bool {
        if node.style.display == Display::None {
            return false;
        }
        if let Some(v) = node.visible
            && !v.contains(point)
        {
            return false;
        }
        let inside = node.rect.contains(point);
        if node.style.clip && !inside {
            return false;
        }
        let mark = out.len();
        if inside {
            out.push(node.id);
        }
        for child in node.children.iter().rev() {
            if Self::walk_hit(child, point, out) {
                return true;
            }
        }
        if inside {
            true
        } else {
            out.truncate(mark);
            false
        }
    }

    /// The absolute rect of the element with the given id.
    pub fn rect_of(&self, id: WidgetId) -> Option<Rect> {
        rect_in(&self.root, id).or_else(|| self.overlays.iter().find_map(|o| rect_in(&o.node, id)))
    }

    /// The toggle overlay anchored at `anchor`, if any.
    pub fn toggle_overlay_of(&self, anchor: WidgetId) -> Option<WidgetId> {
        match self.overlay_anchors.get(&anchor) {
            Some((id, OverlayMode::Toggle)) => Some(*id),
            _ => None,
        }
    }

    /// The open overlay whose subtree contains `id`.
    pub fn overlay_containing(&self, id: WidgetId) -> Option<WidgetId> {
        fn contains(node: &FrameNode, id: WidgetId) -> bool {
            node.id == id || node.children.iter().any(|c| contains(c, id))
        }
        self.overlays
            .iter()
            .find(|o| contains(&o.node, id))
            .map(|o| o.id)
    }

    /// Open overlays from top of the stack down: `(id, mode)`.
    pub fn open_overlays_top_down(&self) -> Vec<(WidgetId, OverlayMode)> {
        self.overlays.iter().rev().map(|o| (o.id, o.mode)).collect()
    }

    /// Whether the topmost open overlay paints a backdrop (modal).
    pub fn top_overlay_is_modal(&self) -> Option<WidgetId> {
        self.overlays
            .iter()
            .next_back()
            .filter(|o| o.backdrop)
            .map(|o| o.id)
    }

    /// The pointer position as fractions (0..=1) of the id's rect.
    pub fn fraction_in(&self, id: WidgetId, point: Point) -> Option<(f32, f32)> {
        let rect = self.rect_of(id)?;
        if rect.width() <= 0.0 || rect.height() <= 0.0 {
            return None;
        }
        #[expect(clippy::cast_possible_truncation, reason = "fractions are 0..=1")]
        Some((
            (((point.x - rect.x0) / rect.width()).clamp(0.0, 1.0)) as f32,
            (((point.y - rect.y0) / rect.height()).clamp(0.0, 1.0)) as f32,
        ))
    }

    /// Focusable element ids in tree order (disabled elements excluded).
    /// While a focus-trapping overlay (modal) is open, only its subtree
    /// participates.
    pub fn focusables(&self) -> Vec<WidgetId> {
        fn walk(node: &FrameNode, out: &mut Vec<WidgetId>) {
            if node.style.display == Display::None {
                return;
            }
            if node.meta.focusable {
                out.push(node.id);
            }
            for child in &node.children {
                walk(child, out);
            }
        }
        let mut out = Vec::new();
        if let Some(trap) = self.overlays.iter().rev().find(|o| o.trap_focus) {
            walk(&trap.node, &mut out);
            return out;
        }
        walk(&self.root, &mut out);
        for overlay in &self.overlays {
            if overlay.hittable {
                walk(&overlay.node, &mut out);
            }
        }
        out
    }

    /// `true` if the id resolves to a scrollable with room to scroll.
    pub fn is_scrollable(&self, id: WidgetId) -> bool {
        fn walk(node: &FrameNode, id: WidgetId) -> bool {
            (node.id == id && node.scroll.as_ref().is_some_and(|s| s.can_scroll))
                || node.children.iter().any(|c| walk(c, id))
        }
        walk(&self.root, id)
    }

    // ---------------------------------------------------------------- dump

    /// A serde debug dump of the resolved layout tree: ids, rects, and key
    /// style properties. Locked with insta snapshots in tests.
    pub fn dump(&self) -> String {
        let dump = NodeDump::from_node(&self.root);
        serde_json::to_string_pretty(&dump).expect("layout dump serializes")
    }
}

#[derive(Serialize)]
struct NodeDump {
    id: u64,
    kind: &'static str,
    /// `[x, y, w, h]` in logical px.
    rect: [f32; 4],
    #[serde(skip_serializing_if = "Option::is_none")]
    text: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    fill: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    scroll_offset: Option<f32>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    children: Vec<NodeDump>,
}

impl NodeDump {
    fn from_node(node: &FrameNode) -> Self {
        #[expect(clippy::cast_possible_truncation, reason = "logical px fit in f32")]
        let rect = [
            node.rect.x0 as f32,
            node.rect.y0 as f32,
            node.rect.width() as f32,
            node.rect.height() as f32,
        ];
        Self {
            id: node.id.0,
            kind: match &node.kind {
                PaintKind::Box => "box",
                PaintKind::Text { .. } => "text",
                PaintKind::Path(_) => "path",
                PaintKind::Input(_) => "input",
                PaintKind::Image(_) => "image",
            },
            rect,
            text: match &node.kind {
                PaintKind::Text { text, .. } => Some(text.clone()),
                PaintKind::Box | PaintKind::Path(_) | PaintKind::Input(_) | PaintKind::Image(_) => {
                    None
                }
            },
            fill: node.style.fill.as_ref().map(|f| match f {
                Paint::Solid(c) => {
                    let c = c.to_rgba8();
                    format!("#{:02x}{:02x}{:02x}", c.r, c.g, c.b)
                }
                Paint::LinearGradient { .. } => "linear-gradient".to_owned(),
                Paint::RadialGradient { .. } => "radial-gradient".to_owned(),
            }),
            scroll_offset: node.scroll.as_ref().map(|s| s.offset),
            children: node.children.iter().map(Self::from_node).collect(),
        }
    }
}