uzor-framework 1.5.30

uzor app engine: one kernel of single-writer engines driven by a typed input bus
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
//! Kit pieces driven by a hand-built [`VisualView`] over several frames.

use uzor::app_context::StateRegistry;
use uzor::input::{InputCoordinator, LayerId};
use uzor::layout::docking::{DockPanel, LeafId};
use uzor::testing::NullRenderContext;
use uzor::tokens::{BuiltinSet, Tokens};
use uzor::{Rect, WidgetId};

use super::*;
use crate::handle::{FrameTime, HookOps, PanelCx, VisualView, Widgets};
use crate::types::ids::WindowId;
use crate::types::spec::{PanelHome, Spec};

#[derive(Clone, Debug)]
struct P;
impl DockPanel for P {
    fn title(&self) -> &str {
        "kit"
    }
    fn type_id(&self) -> &'static str {
        "kit"
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
enum Never {}

struct K;
impl Spec for K {
    type Panel = P;
    type Overlay = Never;
    type Action = Never;
    fn decode_panel(_home: PanelHome, _type_id: &str) -> Option<P> {
        Some(P)
    }
}

/// Widget state that outlives a frame, as the kernel keeps it.
#[derive(Default)]
struct Harness {
    states: StateRegistry,
    coord: InputCoordinator,
    /// Keep the coordinator (and its text store) across frames, as the kernel does.
    keep_coord: bool,
    /// Paint into this recorder instead of a null context.
    record: Option<uzor::testing::RecordingRenderContext>,
}

impl Harness {
    fn frame<R>(&mut self, visual: &VisualView<K>, body: impl FnOnce(&mut PanelCx<'_, K>) -> R) -> R {
        let tokens = Tokens::builtin(BuiltinSet::Dark);
        if self.keep_coord {
            self.coord.begin_frame_widgets_only();
        } else {
            self.coord = InputCoordinator::new();
        }
        let mut null = NullRenderContext::default();
        let render: &mut dyn uzor::render::RenderContext = match self.record.as_mut() {
            Some(r) => r,
            None => &mut null,
        };
        let mut hooks = HookOps::<K>::default();
        let mut cx = PanelCx {
            window: WindowId(1),
            leaf: LeafId(0),
            panel: &P,
            index: 0,
            rect: Rect::new(0.0, 0.0, 800.0, 600.0),
            dpr: 1.0,
            tokens: tokens.as_ref(),
            render,
            widgets: Widgets {
                coord: &mut self.coord,
                states: &mut self.states,
                selectables: &mut Default::default(),
                layer: LayerId::main(),
            },
            view: visual,
            time: FrameTime::default(),
            out: &mut hooks,
        };
        body(&mut cx)
    }
}

fn click(id: &str) -> VisualView<K> {
    let mut v = VisualView::<K>::default();
    v.clicked = vec![(WidgetId::from(id), 1)];
    v
}

fn idle() -> VisualView<K> {
    VisualView::<K>::default()
}

#[test]
fn tabs_lay_out_parts_and_bind_a_click() {
    let mut h = Harness::default();
    let mut tab = 0usize;
    let r = h.frame(&click("t:tab:2"), |cx| {
        tabs("t", Rect::new(0.0, 0.0, 300.0, 30.0), &["A", "B", "C"]).bind(&mut tab).build(cx)
    });
    assert_eq!((r.index, r.changed, tab), (Some(2), true, 2));
    assert_eq!(h.coord.widget_rect(&WidgetId::from("t:tab:1")), Some(Rect::new(100.0, 0.0, 100.0, 30.0)));
    let tabbable = h.coord.focusable_ids(None);
    assert!(["t:tab:0", "t:tab:1", "t:tab:2"].iter().all(|t| tabbable.contains(&WidgetId::from(*t))));
    let r = h.frame(&click("t:tab:2"), |cx| tabs("t", Rect::new(0.0, 0.0, 300.0, 30.0), &["A", "B", "C"]).bind(&mut tab).build(cx));
    assert!(!r.changed, "clicking the active tab is not a change");
}

#[test]
fn list_hits_only_visible_rows() {
    let mut h = Harness::default();
    let mut sel = None;
    let rows = ["a", "b", "c", "d", "e"];
    let r = h.frame(&click("l:row:3"), |cx| {
        list("l", Rect::new(0.0, 0.0, 200.0, 60.0), &rows).row_height(20.0).scroll(40.0).bind(&mut sel).build(cx)
    });
    assert_eq!((r.index, sel), (Some(3), Some(3)));
    assert!(h.coord.widget_rect(&WidgetId::from("l:row:1")).is_none(), "scrolled out");
    assert_eq!(h.coord.widget_rect(&WidgetId::from("l:row:2")), Some(Rect::new(0.0, 0.0, 200.0, 20.0)));
    assert!(h.coord.widget_rect(&WidgetId::from("l:row:4")).is_some());
}

#[test]
fn select_opens_picks_and_closes() {
    let mut h = Harness::default();
    let mut choice = 0usize;
    let opts = ["Low", "Mid", "High"];
    let rect = Rect::new(10.0, 10.0, 120.0, 28.0);
    h.frame(&click("s"), |cx| select("s", rect, &opts).bind(&mut choice).build(cx));
    h.frame(&idle(), |cx| select("s", rect, &opts).bind(&mut choice).build(cx));
    assert!(h.coord.widget_rect(&WidgetId::from("s:list:item:2")).is_some(), "open list registers its options");
    let r = h.frame(&click("s:list:item:2"), |cx| select("s", rect, &opts).bind(&mut choice).build(cx));
    assert_eq!((r.index, r.changed, choice), (Some(2), true, 2));
    h.frame(&idle(), |cx| select("s", rect, &opts).bind(&mut choice).build(cx));
    assert!(h.coord.widget_rect(&WidgetId::from("s:list:item:2")).is_none(), "closed after the pick");
    // A click elsewhere closes it too.
    h.frame(&click("s"), |cx| select("s", rect, &opts).build(cx));
    h.frame(&click("elsewhere"), |cx| select("s", rect, &opts).build(cx));
    h.frame(&idle(), |cx| select("s", rect, &opts).build(cx));
    assert!(h.coord.widget_rect(&WidgetId::from("s:list:item:0")).is_none());
}

#[test]
fn menu_reports_pick_and_closes() {
    let mut h = Harness::default();
    let mut open = true;
    let items = ["Copy", "Delete"];
    h.frame(&idle(), |cx| menu("m", (50.0, 50.0), &items, &mut open).danger(1).build(cx));
    assert!(open && h.coord.widget_rect(&WidgetId::from("m:item:1")).is_some());
    let r = h.frame(&click("m:item:1"), |cx| menu("m", (50.0, 50.0), &items, &mut open).build(cx));
    assert_eq!((r.index, open), (Some(1), false));
    let mut open = true;
    h.frame(&click("other"), |cx| menu("m", (50.0, 50.0), &items, &mut open).build(cx));
    assert!(!open, "a click outside dismisses");
}

#[test]
fn dialog_reports_footer_and_close() {
    let mut h = Harness::default();
    let rect = Rect::new(100.0, 100.0, 400.0, 240.0);
    let r = h.frame(&click("d:footer:1"), |cx| dialog("d", rect).title("Rename").footer(&["Save", "Cancel"]).build(cx));
    assert_eq!((r.index, r.clicked), (Some(1), false));
    let r = h.frame(&click("d:close"), |cx| dialog("d", rect).title("Rename").build(cx));
    assert!(r.clicked && r.changed);
}

#[test]
fn splitter_drags_within_range() {
    let mut h = Harness::default();
    let span = Rect::new(0.0, 0.0, 800.0, 600.0);
    let mut pos = 200.0;
    let mut press = VisualView::<K>::default();
    press.pressed = Some(WidgetId::from("sp"));
    press.button_down = true;
    press.pointer = Some((900.0, 10.0));
    let r = h.frame(&press, |cx| splitter("sp", Axis::X, span, &mut pos).range(100.0, 600.0).build(cx));
    assert!(r.pressed && r.changed);
    assert_eq!(pos, 600.0);
    let r = h.frame(&idle(), |cx| splitter("sp", Axis::X, span, &mut pos).build(cx));
    assert!(!r.pressed, "release ends the drag");
}

#[test]
fn toasts_keep_frames_coming_until_they_expire() {
    let mut h = Harness::default();
    let mut stack = ToastStackState::new();
    stack.push(ToastType { title: None, message: "Saved".into(), timestamp_ms: 0, duration_ms: 1000, severity: ToastSeverity::Info }, 0);
    let area = Rect::new(0.0, 0.0, 800.0, 600.0);
    assert!(h.frame(&idle(), |cx| toasts("toasts", area, &mut stack, 500).build(cx)).changed);
    assert!(!h.frame(&idle(), |cx| toasts("toasts", area, &mut stack, 60_000).build(cx)).changed);
}

#[test]
fn input_is_focusable_and_reports_focus() {
    let mut h = Harness::default();
    let mut v = VisualView::<K>::default();
    v.focused = Some(WidgetId::from("name"));
    let mut name = String::from("Ann");
    let r = h.frame(&v, |cx| input("name", Rect::new(0.0, 0.0, 200.0, 28.0), &mut name).placeholder("Name").build(cx));
    assert!(r.focused);
    assert!(h.coord.focusable_ids(None).contains(&WidgetId::from("name")));
}

#[test]
fn input_edits_itself_with_undo_and_syncs_both_ways() {
    let mut h = Harness { keep_coord: true, ..Default::default() };
    let rect = Rect::new(0.0, 0.0, 200.0, 28.0);
    let mut name = String::from("Ann");
    let id = WidgetId::from("name");
    h.frame(&idle(), |cx| input("name", rect, &mut name).build(cx));
    assert_eq!(h.coord.text_fields().text(&id), "Ann", "the app's value seeds the field");
    let f = h.coord.text_fields_mut();
    f.focus(id.clone());
    for c in "a b".chars() {
        f.on_char(c);
    }
    let r = h.frame(&idle(), |cx| input("name", rect, &mut name).build(cx));
    assert!(r.changed && r.focused);
    assert_eq!(name, "Anna b");
    h.coord.text_fields_mut().on_key(uzor::KeyPress::Undo);
    let r = h.frame(&idle(), |cx| input("name", rect, &mut name).build(cx));
    assert!(r.changed);
    assert_eq!(name, "Anna ");
    name = "Bob".into();
    let r = h.frame(&idle(), |cx| input("name", rect, &mut name).build(cx));
    assert!(!r.changed, "an app write is not a user change");
    assert_eq!(h.coord.text_fields().text(&id), "Bob");
    assert_eq!(h.coord.text_fields_mut().on_key(uzor::KeyPress::Undo), uzor::TextAction::None);
}

#[test]
fn disabled_input_is_not_a_text_field() {
    let mut h = Harness::default();
    let mut name = String::new();
    h.frame(&idle(), |cx| input("name", Rect::new(0.0, 0.0, 200.0, 28.0), &mut name).disabled(true).build(cx));
    assert!(!h.coord.text_fields().has_field(&WidgetId::from("name")));
    assert!(!h.coord.focusable_ids(None).contains(&WidgetId::from("name")));
}

#[test]
fn button_reports_like_the_rest() {
    let mut h = Harness::default();
    let r = h.frame(&click("ok"), |cx| button("ok", Rect::new(0.0, 0.0, 80.0, 28.0)).text("OK").build_response(cx));
    assert!(r.clicked);
}

#[test]
fn checkbox_and_switch_report_the_new_state_and_are_named() {
    let mut h = Harness::default();
    let mut on = false;
    let r = h.frame(&click("cb"), |cx| checkbox("cb", Rect::new(0.0, 0.0, 120.0, 20.0)).label("Notify").bind(&mut on).build_response(cx));
    assert!(on && r.checked && r.changed);
    let mut sw = true;
    let r = h.frame(&click("sw"), |cx| switch("sw", Rect::new(0.0, 0.0, 40.0, 20.0)).label("Dark").disabled(true).bind(&mut sw).build_response(cx));
    assert!(sw && r.checked && !r.changed, "a disabled switch does not flip");
}

#[test]
fn table_reports_rows_and_header_columns() {
    let mut h = Harness::default();
    let rows = vec![vec!["a".to_string(), "1".into()], vec!["b".into(), "2".into()]];
    let rect = Rect::new(0.0, 0.0, 300.0, 200.0);
    let mut sel = None;
    let r = h.frame(&click("t:row:1"), |cx| table("t", rect, &["Name", "N"], &rows).columns("2fr 80px").bind(&mut sel).build(cx));
    assert_eq!((r.index, r.changed, sel), (Some(1), true, Some(1)));
    let r = h.frame(&click("t:col:0"), |cx| table("t", rect, &["Name", "N"], &rows).build(cx));
    assert_eq!(r.column, Some(0));
    let ids = h.coord.focusable_ids(None);
    assert!(ids.contains(&WidgetId::from("t:col:1")) && ids.contains(&WidgetId::from("t:row:0")));
}

#[test]
fn drawer_closes_on_scrim_and_slides_with_progress() {
    let mut h = Harness::default();
    let area = Rect::new(0.0, 0.0, 800.0, 600.0);
    let mut open = true;
    let d = drawer("d", area, &mut open).width(300.0).progress(0.5);
    assert_eq!(d.body_rect().x, 650.0);
    assert_eq!(drawer("d", area, &mut true).side(Side::Left).body_rect().x, 0.0);
    let r = h.frame(&click("d"), |cx| drawer("d", area, &mut open).build(cx));
    assert!(open && !r.changed, "a click inside the panel keeps it open");
    let r = h.frame(&click("d:scrim"), |cx| drawer("d", area, &mut open).build(cx));
    assert!(!open && r.changed);
}

#[test]
fn field_registers_names_masks_and_feeds_the_store() {
    let mut h = Harness { keep_coord: true, ..Default::default() };
    let rect = Rect::new(10.0, 0.0, 200.0, 28.0);
    let id = WidgetId::from("pw");
    let pw = || field("pw", rect).config(uzor::TextFieldConfig::password()).placeholder("Password").masked(true).clip(true).colors("white", "gray");
    let r = h.frame(&idle(), |cx| pw().build(cx));
    assert_eq!(r, FieldResponse::default());
    assert!(h.coord.focusable_ids(None).contains(&id));
    assert!(h.coord.a11y_tree().nodes().iter().any(|n| n.name == "Password"));
    let f = h.coord.text_fields_mut();
    f.focus(id.clone());
    for c in "abc".chars() {
        f.on_char(c);
    }
    let mut v = idle();
    v.focused = Some(id.clone());
    let r = h.frame(&v, |cx| pw().build(cx));
    assert_eq!(r, FieldResponse { text: "abc".into(), focused: true });
    let st = h.coord.text_fields().field_state(&id).unwrap();
    assert_eq!(st.text, "abc");
    let r = h.frame(&v, |cx| pw().set(Some("xy")).build(cx));
    assert_eq!(r.text, "xy");
    let r = h.frame(&v, |cx| pw().set(Some("")).build(cx));
    assert_eq!(r.text, "");
}

/// Each `fill_text` / `fill_rect` with the clip in force when it ran (the intersection of
/// every `rect` + `clip` under the open `save`s; `None` = unclipped).
fn painted_with_clips(ops: &[uzor::testing::DrawOp]) -> Vec<(String, f64, Option<Rect>)> {
    use uzor::testing::DrawOp as D;
    let (mut stack, mut cur, mut path, mut out) = (Vec::new(), None::<Rect>, None::<Rect>, Vec::new());
    for op in ops {
        match op {
            D::Save => stack.push(cur),
            D::Restore => cur = stack.pop().flatten(),
            D::BeginPath => path = None,
            D::Rect { x, y, w, h } => path = Some(Rect::new(*x, *y, *w, *h)),
            D::Clip => cur = path.map(|p| cur.map_or(p, |c: Rect| c.intersect(p))),
            D::FillText { text, x, .. } => out.push((text.clone(), *x, cur)),
            D::FillRect { x, .. } => out.push(("<rect>".into(), *x, cur)),
            _ => {}
        }
    }
    out
}

#[test]
fn field_clips_scrolls_with_the_caret_and_stays_inside_its_viewport() {
    // 10 px a char: 60 chars of a pasted token in a 200 px field.
    let rect = Rect::new(10.0, 100.0, 200.0, 28.0);
    let id = WidgetId::from("tok");
    let long = format!("hsreq1.{}", "x".repeat(53));
    let mut h = Harness { keep_coord: true, record: Some(uzor::testing::RecordingRenderContext::with_char_width(10.0)), ..Default::default() };
    let mut v = idle();
    v.focused = Some(id.clone());
    h.frame(&idle(), |cx| field("tok", rect).placeholder("hsreq1.…").set(Some(&long)).build(cx));
    h.coord.text_fields_mut().focus(id.clone());
    let viewport = Rect::new(0.0, 0.0, 400.0, 300.0);
    let frame = |h: &mut Harness, v: &VisualView<K>, r: Rect, vp: Rect| {
        h.record.as_mut().unwrap().ops.clear();
        h.frame(v, |cx| field("tok", r).placeholder("hsreq1.…").clip_to(vp).build(cx));
        painted_with_clips(&h.record.as_ref().unwrap().ops)
    };
    // Focused, caret at the end: the text scrolls left so the caret shows, all inside the field.
    let p = frame(&mut h, &v, rect, viewport);
    let (t, x, clip) = p.iter().find(|(t, ..)| t == &long).cloned().expect("text painted");
    assert_eq!(clip, Some(rect), "text clipped to the field: {t}");
    assert_eq!(x, rect.x - (600.0 - 199.0), "scrolled so the end shows");
    let caret = p.iter().find(|(t, ..)| t == "<rect>").map(|c| (c.1, c.2));
    if let Some((cx, Some(c))) = caret {
        assert!(cx >= c.x && cx < c.x + c.width, "caret {cx} inside {c:?}");
    }
    // Caret home: back to the start.
    h.coord.text_fields_mut().field_state_mut(&id).unwrap().cursor = 0;
    let p = frame(&mut h, &v, rect, viewport);
    assert_eq!(p.iter().find(|(t, ..)| t == &long).unwrap().1, rect.x);
    // Not focused: from the start, still clipped.
    let p = frame(&mut h, &idle(), rect, viewport);
    assert_eq!(p.iter().find(|(t, ..)| t == &long).map(|e| (e.1, e.2)), Some((rect.x, Some(rect))));
    // Scrolled half under a footer: clipped to the viewport, and hit only there.
    let half = Rect::new(0.0, 0.0, 400.0, 114.0);
    let p = frame(&mut h, &idle(), rect, half);
    assert_eq!(p.iter().find(|(t, ..)| t == &long).unwrap().2, Some(Rect::new(10.0, 100.0, 200.0, 14.0)));
    assert_eq!(h.coord.widget_rect(&id), Some(Rect::new(10.0, 100.0, 200.0, 14.0)));
    // Scrolled out of the viewport: nothing painted (no placeholder or text under the footer).
    h.coord.text_fields_mut().clear(&id);
    let p = frame(&mut h, &idle(), rect, Rect::new(0.0, 0.0, 400.0, 90.0));
    assert!(p.is_empty(), "{p:?}");
    let p = frame(&mut h, &idle(), rect, viewport);
    assert_eq!(p.iter().find(|(t, ..)| t == "hsreq1.…").unwrap().2, Some(rect), "placeholder clipped too");
}

#[test]
fn field_scroll_keeps_the_caret_in_view() {
    assert_eq!(field_scroll(0.0, 50.0, 100.0, 200.0), 0.0);
    assert_eq!(field_scroll(0.0, 600.0, 600.0, 200.0), 401.0);
    assert_eq!(field_scroll(401.0, 500.0, 600.0, 200.0), 401.0, "caret still in view: no jump");
    assert_eq!(field_scroll(401.0, 300.0, 600.0, 200.0), 300.0);
    assert_eq!(field_scroll(401.0, 100.0, 100.0, 200.0), 0.0, "text shrank: back to the start");
}

fn key(code: uzor::input::keyboard::KeyCode, text: Option<&str>) -> crate::KeyInput {
    crate::KeyInput { code, text: text.map(str::to_string), state: crate::KeyState::Down, mods: Default::default() }
}

#[test]
fn select_keyboard_search_escape_and_stays_inside_its_container() {
    use uzor::input::keyboard::KeyCode as K;
    let mut h = Harness::default();
    let zones: Vec<String> = (0..30).map(|i| format!("Zone/City_{i:02}")).collect();
    let opts: Vec<&str> = zones.iter().map(String::as_str).collect();
    let mut choice = 3usize;
    // The trigger sits near the bottom-right of a 400x300 dialog.
    let dlg = Rect::new(0.0, 0.0, 400.0, 300.0);
    let rect = Rect::new(300.0, 240.0, 90.0, 28.0);
    let none: Option<&crate::KeyInput> = None;
    let frame = |h: &mut Harness, ev: &_, k: Option<&crate::KeyInput>, c: &mut usize| h.frame(ev, |cx| select("tz", rect, &opts).within(dlg).key(k).bind(c).build(cx));
    let r = frame(&mut h, &click("tz"), none, &mut choice);
    assert!(r.checked, "a click opens it");
    frame(&mut h, &idle(), none, &mut choice);
    // Searchable (30 > 10 rows): 280 wide, flipped above and shifted left, inside the dialog.
    let list = h.coord.widget_rect(&WidgetId::from("tz:list")).expect("list registered");
    assert!(list.x >= 0.0 && list.x + list.width <= 400.0 && list.y >= 0.0 && list.y + list.height <= 300.0, "{list:?}");
    assert!(list.y + list.height <= 240.0, "opens above the trigger: {list:?}");
    // The chosen option is highlighted; ArrowDown moves; Enter picks it.
    let down = key(K::ArrowDown, None);
    let r = frame(&mut h, &idle(), Some(&down), &mut choice);
    assert!(r.pressed && r.checked);
    let enter = key(K::Enter, None);
    let r = frame(&mut h, &idle(), Some(&enter), &mut choice);
    assert_eq!((r.index, r.changed, choice, r.checked), (Some(4), true, 4, false));
    // Enter on the focused trigger is not handled here (not focused in the harness): reopen by click,
    // type to filter, then Enter picks the first match.
    frame(&mut h, &click("tz"), none, &mut choice);
    for t in ["2", "7"] {
        let k = key(K::Num2, Some(t));
        frame(&mut h, &idle(), Some(&k), &mut choice);
    }
    frame(&mut h, &idle(), none, &mut choice);
    assert!(h.coord.widget_rect(&WidgetId::from("tz:list:item:27")).is_some());
    assert!(h.coord.widget_rect(&WidgetId::from("tz:list:item:26")).is_none(), "filtered out");
    let r = frame(&mut h, &idle(), Some(&enter), &mut choice);
    assert_eq!((r.index, choice), (Some(27), 27));
    // Escape closes without picking, and says it used the key.
    frame(&mut h, &click("tz"), none, &mut choice);
    let esc = key(K::Escape, None);
    let r = frame(&mut h, &idle(), Some(&esc), &mut choice);
    assert!(r.pressed && !r.checked && r.index.is_none());
    frame(&mut h, &idle(), none, &mut choice);
    assert!(h.coord.widget_rect(&WidgetId::from("tz:list")).is_none());
}

#[test]
fn pointer_over_answers_only_for_the_topmost_target() {
    let term = WidgetId::from("term");
    let mut v = VisualView::<K>::default();
    v.pointer = Some((300.0, 100.0));
    v.scroll = (0.0, -2.0);
    // A drawer covers the terminal: its card is the hover target.
    v.hovered = Some(WidgetId::from("bd-card"));
    v.hover_path = vec![WidgetId::from("bd-card")];
    assert_eq!(v.pointer_over(&term), None);
    assert_eq!(v.scroll_over(&term), (0.0, 0.0));
    assert_eq!(v.raw_pointer(), Some((300.0, 100.0)), "the raw position stays available, opt-in");
    v.hovered = Some(term.clone());
    v.hover_path = vec![term.clone()];
    assert_eq!(v.pointer_over(&term), Some((300.0, 100.0)));
    assert_eq!(v.scroll_over(&term), (0.0, -2.0));
    // Capture: the pressed widget keeps the pointer while a drag crosses a cover.
    v.hovered = Some(WidgetId::from("bd-card"));
    v.hover_path = vec![WidgetId::from("bd-card")];
    v.pressed = Some(term.clone());
    assert_eq!(v.pointer_over(&term), Some((300.0, 100.0)));
}

#[test]
fn press_origin_is_reported_only_for_a_held_press() {
    let mut v = VisualView::<K>::default();
    v.press_origin = Some((12.0, 3.0));
    assert_eq!(v.press_origin(), None, "no button held");
    v.button_down = true;
    assert_eq!(v.press_origin(), None, "held over nothing pressable");
    v.pressed = Some(WidgetId::from("bar"));
    v.pointer = Some((40.0, 9.0));
    assert_eq!(v.press_origin(), Some((12.0, 3.0)));
    assert_eq!(v.pressed_at(&WidgetId::from("bar")), Some((12.0, 3.0)));
    assert_eq!(v.pressed_at(&WidgetId::from("other")), None);
}

#[test]
fn dom_tree_registers_controls_inputs_and_reports_clicks() {
    use domkit::{self, SelectOpt};
    let sheet = domkit::sheet();
    let tree = |open: bool| {
        let opts = [SelectOpt::new("Low"), SelectOpt::new("Mid").sub("default"), SelectOpt::new("High").disabled(true)];
        let mut root = uzor::ui::dom::El::new("div.k-col")
            .child(domkit::switch("notify", true, "Notifications"))
            .child(domkit::input("nick", uzor::ui::dom::Edit::new("ann").placeholder("Nick")))
            .child(domkit::select_trigger("lvl", "Mid", open, "Level"));
        if open {
            root = root.child(domkit::select_popover("lvl", &opts, Some(1), domkit::popover_at(Rect::new(0.0, 80.0, 160.0, 30.0), Rect::new(0.0, 0.0, 800.0, 600.0), 160.0, 120.0)));
        }
        root
    };
    let mut h = Harness { keep_coord: true, ..Default::default() };
    let area = Rect::new(0.0, 0.0, 400.0, 600.0);
    let r = h.frame(&click("lvl"), |cx| dom(area, &sheet, tree(false)).build(cx));
    assert_eq!(r.clicked.as_deref(), Some("lvl"));
    assert!(h.coord.focusable_ids(None).contains(&WidgetId::from("notify")));
    let r = h.frame(&click("lvl:opt:0"), |cx| dom(area, &sheet, tree(true)).build(cx));
    assert_eq!(domkit::picked_opt("lvl", r.clicked.as_deref().unwrap_or("")), Some(0));
    assert!(h.coord.widget_rect(&WidgetId::from("lvl:opt:2")).is_none(), "disabled rows are not targets");
    // The input is a text-store field seeded with its value.
    let st = h.coord.text_fields().field_state(&WidgetId::from("nick")).expect("field");
    assert_eq!(st.text, "ann");
    // Accessible names come from El::name, then text.
    let a11y = r.dom.a11y();
    assert!(a11y.iter().any(|n| n.id == "notify" && n.name == "Notifications" && n.checked == Some(true)));
}

#[test]
fn area_lines_wrap_at_spaces_and_hard_breaks() {
    let mut r = uzor::testing::RecordingRenderContext::with_char_width(10.0);
    // 10 px a char in a 60 px box: "hello world" wraps after the space.
    let l = area_lines(&mut r, "hello world\nab", 60.0);
    assert_eq!(l, vec![AreaLine { start: 0, end: 6, hard: false }, AreaLine { start: 6, end: 11, hard: true }, AreaLine { start: 12, end: 14, hard: false }]);
    // A word longer than the box breaks between chars; empty text is one line.
    assert_eq!(area_lines(&mut r, "abcdefghij", 40.0).len(), 3);
    assert_eq!(area_lines(&mut r, "", 40.0), vec![AreaLine::default()]);
    assert_eq!(area_lines(&mut r, "a\n", 40.0).len(), 2);
}

#[test]
fn area_paints_lines_and_moves_by_them() {
    use uzor::input::keyboard::keyboard::KeyPress;
    let rect = Rect::new(10.0, 100.0, 60.0, 80.0);
    let id = WidgetId::from("msg");
    let mut h = Harness { keep_coord: true, record: Some(uzor::testing::RecordingRenderContext::with_char_width(10.0)), ..Default::default() };
    let a = || area("msg", rect).placeholder("Message").line_height(20.0).font(13.0, "Inter");
    let r = h.frame(&idle(), |cx| a().set(Some("hello world\nab")).build(cx));
    assert_eq!((r.lines, r.content_h), (3, 60.0));
    let texts: Vec<String> = painted_with_clips(&h.record.as_ref().unwrap().ops).into_iter().map(|t| t.0).filter(|t| t != "<rect>").collect();
    assert_eq!(texts, ["hello ", "world", "ab"]);
    let f = h.coord.text_fields_mut();
    assert!(f.has_lines(&id));
    // A click on the third line at x = 10 + 15 puts the caret after "a"/"b" (char 13 or 14).
    f.begin_drag_at_xy(id.clone(), 10.0 + 11.0, 100.0 + 45.0);
    f.on_drag_end();
    assert_eq!(f.cursor(&id), 13);
    // Up: onto "world" at the same x; Up again: "hello "; Up past the first line: start.
    f.on_key(KeyPress::ArrowUp);
    assert_eq!(f.cursor(&id), 7);
    f.on_key(KeyPress::ArrowUp);
    assert_eq!(f.cursor(&id), 1);
    f.on_key(KeyPress::End);
    assert_eq!(f.cursor(&id), 5, "End stops at the soft wrap");
    f.on_key(KeyPress::ArrowDown);
    f.on_key(KeyPress::Home);
    assert_eq!(f.cursor(&id), 6);
    f.on_key(KeyPress::ArrowDown);
    f.on_key(KeyPress::ArrowDown);
    assert_eq!(f.cursor(&id), 14, "past the last line: the end");
    let mut v = idle();
    v.focused = Some(id.clone());
    let r = h.frame(&v, |cx| a().build(cx));
    assert!(r.focused && r.caret_top == 40.0);
}