teksilo-widgets 0.9.0

Widget library for Teksilo — over a hundred widgets and layout primitives, from Button to TreeTableView.
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
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

//! Headless integration tests for `SpinBox`.

use teksilo_canvas::SizeProposal;
use teksilo_core::event::{Key, Modifiers};
use teksilo_core::signal::Signal;
use teksilo_core::widget_tree::WidgetTree;
use teksilo_i18n::lit;

use super::{SpinBox, StepType, WrapMode};

fn tick(tree: &mut WidgetTree) {
    tree.request_frame();
    tree.tick_animations(std::time::Duration::from_millis(16));
    tree.layout(SizeProposal::exact(300.0, 60.0));
}

fn setup_int(
    initial: i32,
    min: i32,
    max: i32,
) -> (WidgetTree, Signal<i32>, teksilo_core::widget_id::WidgetId) {
    let value = Signal::new(initial);
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let id = tree.add(SpinBox::new(value.clone(), min, max));
    tree.layout(SizeProposal::exact(300.0, 60.0));
    tick(&mut tree);
    (tree, value, id)
}

fn focus_field(tree: &mut WidgetTree, spin_id: teksilo_core::widget_id::WidgetId) {
    let field = tree
        .first_focusable_descendant(spin_id)
        .expect("SpinBox should have a focusable inner field");
    tree.focus(field);
}

// ── Construction ────────────────────────────────────────────────────

#[test]
fn constructs_and_lays_out() {
    let (tree, _v, id) = setup_int(0, 0, 100);
    let bounds = tree.bounds(id);
    assert!(bounds.width > 0.0);
    assert!(bounds.height > 0.0);
}

/// Regression: the value text grows with the global text scale, so the
/// SpinBox's width cap must grow too — otherwise the scaled digits clip.
#[test]
fn width_grows_with_text_scale() {
    let value = Signal::new(50);
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let id = tree.add(SpinBox::new(value, 0, 100).width_chars(3).suffix(" %"));
    tree.layout(SizeProposal::unspecified());
    let w1 = tree.bounds(id).width;
    tree.set_user_text_scale(2.0);
    tree.layout(SizeProposal::unspecified());
    let w2 = tree.bounds(id).width;
    assert!(
        w2 > w1 * 1.4,
        "spinbox width should grow with the text scale: {w1} -> {w2}"
    );
}

// ── Keyboard stepping ──────────────────────────────────────────────

#[test]
fn arrow_up_increments() {
    let (mut tree, value, id) = setup_int(10, 0, 100);
    focus_field(&mut tree, id);
    tree.press_key(Key::ArrowUp, Modifiers::NONE);
    tick(&mut tree);
    assert_eq!(value.get(), 11);
}

#[test]
fn arrow_down_decrements() {
    let (mut tree, value, id) = setup_int(10, 0, 100);
    focus_field(&mut tree, id);
    tree.press_key(Key::ArrowDown, Modifiers::NONE);
    tick(&mut tree);
    assert_eq!(value.get(), 9);
}

#[test]
fn page_up_uses_page_step() {
    let value = Signal::new(10_i32);
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let id = tree.add(SpinBox::new(value.clone(), 0, 100).page_step(25));
    tree.layout(SizeProposal::exact(300.0, 60.0));
    tick(&mut tree);
    focus_field(&mut tree, id);
    tree.press_key(Key::PageUp, Modifiers::NONE);
    tick(&mut tree);
    assert_eq!(value.get(), 35);
}

#[test]
fn page_step_defaults_to_ten_times_single_step() {
    let value = Signal::new(10_i32);
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let id = tree.add(SpinBox::new(value.clone(), 0, 1000).single_step(3));
    tree.layout(SizeProposal::exact(300.0, 60.0));
    tick(&mut tree);
    focus_field(&mut tree, id);
    tree.press_key(Key::PageUp, Modifiers::NONE);
    tick(&mut tree);
    assert_eq!(value.get(), 40, "page step default must be 10x single step");
}

// ── Clamping & wrapping ────────────────────────────────────────────

#[test]
fn clamp_mode_blocks_past_max() {
    let (mut tree, value, id) = setup_int(99, 0, 100);
    focus_field(&mut tree, id);
    tree.press_key(Key::ArrowUp, Modifiers::NONE);
    tick(&mut tree);
    tree.press_key(Key::ArrowUp, Modifiers::NONE); // would go to 101
    tick(&mut tree);
    assert_eq!(value.get(), 100);
}

#[test]
fn clamp_mode_blocks_below_min() {
    let (mut tree, value, id) = setup_int(1, 0, 100);
    focus_field(&mut tree, id);
    tree.press_key(Key::ArrowDown, Modifiers::NONE);
    tick(&mut tree);
    tree.press_key(Key::ArrowDown, Modifiers::NONE); // would go to -1
    tick(&mut tree);
    assert_eq!(value.get(), 0);
}

#[test]
fn wrap_mode_wraps_past_max() {
    let value = Signal::new(9_i32);
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let id = tree.add(SpinBox::new(value.clone(), 0, 9).wrap_mode(WrapMode::Wrap));
    tree.layout(SizeProposal::exact(300.0, 60.0));
    tick(&mut tree);
    focus_field(&mut tree, id);
    tree.press_key(Key::ArrowUp, Modifiers::NONE);
    tick(&mut tree);
    assert_eq!(value.get(), 0, "wrap past max jumps to min");
}

#[test]
fn wrap_mode_wraps_past_min() {
    let value = Signal::new(0_i32);
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let id = tree.add(SpinBox::new(value.clone(), 0, 9).wrap_mode(WrapMode::Wrap));
    tree.layout(SizeProposal::exact(300.0, 60.0));
    tick(&mut tree);
    focus_field(&mut tree, id);
    tree.press_key(Key::ArrowDown, Modifiers::NONE);
    tick(&mut tree);
    assert_eq!(value.get(), 9, "wrap past min jumps to max");
}

// ── Read-only / disabled ───────────────────────────────────────────

#[test]
fn read_only_blocks_keyboard_step() {
    let value = Signal::new(10_i32);
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let id = tree.add(SpinBox::new(value.clone(), 0, 100).read_only(true));
    tree.layout(SizeProposal::exact(300.0, 60.0));
    tick(&mut tree);
    focus_field(&mut tree, id);
    tree.press_key(Key::ArrowUp, Modifiers::NONE);
    tick(&mut tree);
    assert_eq!(value.get(), 10, "read_only must block stepping");
}

// ── Adaptive step ──────────────────────────────────────────────────

#[test]
fn adaptive_step_scales_to_magnitude() {
    // value ∈ [100, 999) → step = 100
    let value = Signal::new(250_i32);
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let id = tree.add(
        SpinBox::new(value.clone(), 0, 10_000)
            .single_step(1)
            .step_type(StepType::Adaptive),
    );
    tree.layout(SizeProposal::exact(300.0, 60.0));
    tick(&mut tree);
    focus_field(&mut tree, id);
    tree.press_key(Key::ArrowUp, Modifiers::NONE);
    tick(&mut tree);
    assert_eq!(value.get(), 350);
}

#[test]
fn adaptive_step_small_values_use_base_step() {
    let value = Signal::new(3_i32);
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let id = tree.add(
        SpinBox::new(value.clone(), 0, 1000)
            .single_step(1)
            .step_type(StepType::Adaptive),
    );
    tree.layout(SizeProposal::exact(300.0, 60.0));
    tick(&mut tree);
    focus_field(&mut tree, id);
    tree.press_key(Key::ArrowUp, Modifiers::NONE);
    tick(&mut tree);
    assert_eq!(value.get(), 4, "adaptive under 10 should keep base step");
}

// ── External value changes ────────────────────────────────────────

#[test]
fn external_value_set_reformats_text() {
    let value = Signal::new(0_i32);
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let _id = tree.add(SpinBox::new(value.clone(), 0, 100));
    tree.layout(SizeProposal::exact(300.0, 60.0));
    tick(&mut tree);

    // Changing the external signal should not panic, and should
    // propagate through the reformat effect.
    value.set(42);
    tick(&mut tree);
    tick(&mut tree);
    assert_eq!(value.get(), 42);
}

// ── Accessibility ──────────────────────────────────────────────────

#[test]
fn a11y_role_is_spin_button() {
    let (tree, _v, id) = setup_int(50, 0, 100);
    let info = tree.accessibility_node(id);
    assert_eq!(info.role(), teksilo_core::accesskit::Role::SpinButton);
    // Increment / Decrement / SetValue / Focus actions all exposed.
    let actions = info.actions();
    assert!(actions.contains(&teksilo_core::accesskit::Action::Increment));
    assert!(actions.contains(&teksilo_core::accesskit::Action::Decrement));
    assert!(actions.contains(&teksilo_core::accesskit::Action::Focus));
}

#[test]
fn disabled_blocks_keyboard_step() {
    // Built-in arena-level `is_disabled` relies on an
    // `enabled_state` signal that containers like `GroupBox`
    // bind, which SpinBox does not opt into by default. What we
    // do guarantee is that the step paths short-circuit when
    // `enabled = false`; the value signal stays put.
    let value = Signal::new(10_i32);
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let id = tree.add(SpinBox::new(value.clone(), 0, 100).enabled(false));
    tree.layout(SizeProposal::exact(300.0, 60.0));
    tick(&mut tree);
    // Inner field isn't focusable when the SpinBox is disabled
    // (TextInputField propagates enabled), so we can't rely on
    // focus_field here. Hit the field with a direct key press via
    // a focused-or-not attempt and check the value is unchanged.
    if let Some(field) = tree.first_focusable_descendant(id) {
        tree.focus(field);
    }
    tree.press_key(Key::ArrowUp, Modifiers::NONE);
    tick(&mut tree);
    assert_eq!(value.get(), 10, "disabled SpinBox must not step");
}

// ── Floats ─────────────────────────────────────────────────────────

#[test]
fn float_type_formats_with_decimals() {
    let value = Signal::new(0.25_f64);
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let _id = tree.add(
        SpinBox::new(value.clone(), 0.0, 1.0)
            .single_step(0.05)
            .decimals(2),
    );
    tree.layout(SizeProposal::exact(300.0, 60.0));
    tick(&mut tree);
    // The value signal round-trip is what we can assert here.
    // Full text-signal inspection needs access to the inner field,
    // which is not exposed by the public API.
    assert!((value.get() - 0.25).abs() < 1e-9);
}

#[test]
fn float_arrow_steps_by_single_step() {
    let value = Signal::new(0.5_f32);
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let id = tree.add(
        SpinBox::new(value.clone(), 0.0, 1.0)
            .single_step(0.1)
            .decimals(2),
    );
    tree.layout(SizeProposal::exact(300.0, 60.0));
    tick(&mut tree);
    focus_field(&mut tree, id);
    tree.press_key(Key::ArrowUp, Modifiers::NONE);
    tick(&mut tree);
    assert!((value.get() - 0.6).abs() < 1e-5, "got {}", value.get());
}

// ── on_value_changed callback ──────────────────────────────────────

#[test]
fn on_value_changed_fires_on_step() {
    use std::cell::Cell;
    use std::rc::Rc;
    let value = Signal::new(0_i32);
    let fired = Rc::new(Cell::new(0_i32));
    let c = fired.clone();
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let id =
        tree.add(SpinBox::new(value.clone(), 0, 100).on_value_changed(move |v, _ctx| c.set(v)));
    tree.layout(SizeProposal::exact(300.0, 60.0));
    tick(&mut tree);
    focus_field(&mut tree, id);
    tree.press_key(Key::ArrowUp, Modifiers::NONE);
    tick(&mut tree);
    assert_eq!(fired.get(), 1);
}

// ── Hidden buttons ────────────────────────────────────────────────

#[test]
fn hidden_buttons_still_step_via_keyboard() {
    // Int UI-style dense form: no visible step buttons, keyboard
    // (and wheel) must still work.
    use super::ButtonLayout;
    let value = Signal::new(10_i32);
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let id = tree.add(SpinBox::new(value.clone(), 0, 100).button_layout(ButtonLayout::Hidden));
    tree.layout(SizeProposal::exact(300.0, 60.0));
    tick(&mut tree);
    focus_field(&mut tree, id);
    tree.press_key(Key::ArrowUp, Modifiers::NONE);
    tick(&mut tree);
    assert_eq!(value.get(), 11);
}

#[test]
fn show_buttons_sugar_matches_button_layout() {
    use super::ButtonLayout;
    // Both builders must produce the same behavior.
    let a = Signal::new(0_i32);
    let b = Signal::new(0_i32);
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let ia = tree.add(SpinBox::new(a.clone(), 0, 10).show_buttons(false));
    let ib = tree.add(SpinBox::new(b.clone(), 0, 10).button_layout(ButtonLayout::Hidden));
    tree.layout(SizeProposal::exact(300.0, 120.0));
    tick(&mut tree);
    // Both widgets should have identical focusable-descendant
    // counts: one focusable field each, no focusable buttons.
    fn count_focusable(tree: &WidgetTree, root: teksilo_core::widget_id::WidgetId) -> usize {
        // walk widgets under root and count those that expose
        // focusable=true via the test API
        let mut count = 0;
        // first_focusable_descendant returns only the first; to
        // compare we just check it's Some for both.
        if tree.first_focusable_descendant(root).is_some() {
            count += 1;
        }
        count
    }
    assert_eq!(count_focusable(&tree, ia), count_focusable(&tree, ib));
}

// ── Width control ─────────────────────────────────────────────────
//
// `width()` / `fill_width()` behaviour is exercised visually in
// `examples/spin_box` rather than unit-tested here: the test harness
// uses `SizeProposal::exact` for the tree root, which pins the root
// widget to that exact size and bypasses the SpinBox's internal
// `MaxSize` cap. Validating the cap needs a multi-child parent
// (HStack row) that distributes space — covered by the demo.

// ── Suffix & special value text coexist ───────────────────────────

// ── Accessibility numeric properties ─────────────────────────────

#[test]
fn a11y_numeric_value_matches_signal() {
    let value = Signal::new(42_i32);
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let id = tree.add(SpinBox::new(value.clone(), 0, 100).single_step(2));
    tree.layout(SizeProposal::exact(300.0, 60.0));
    tick(&mut tree);

    // We can't inspect the raw AccessKit `Node` through the public
    // API, but we can round-trip via the Role + Action set and
    // confirm the value updates the a11y string published by
    // `builder.set_value`. The Info wrapper doesn't expose the
    // numeric_value itself, so the closest smoke test is that the
    // node exists and advertises the expected actions.
    let info = tree.accessibility_node(id);
    assert_eq!(info.role(), teksilo_core::accesskit::Role::SpinButton);
    let actions = info.actions();
    for required in [
        teksilo_core::accesskit::Action::Increment,
        teksilo_core::accesskit::Action::Decrement,
        teksilo_core::accesskit::Action::SetValue,
        teksilo_core::accesskit::Action::Focus,
    ] {
        assert!(
            actions.contains(&required),
            "missing a11y action {:?}",
            required
        );
    }
}

#[test]
fn a11y_name_uses_label() {
    let value = Signal::new(0_i32);
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let id = tree.add(SpinBox::new(value, 0, 100).label(lit!("Font size")));
    tree.layout(SizeProposal::exact(300.0, 60.0));
    tick(&mut tree);
    let info = tree.accessibility_node(id);
    assert_eq!(info.name(), Some("Font size"));
}

// ── Reactive suffix + special_value_text ──────────────────────────
//
// The Qt-compat bug was: with `value == min` and
// `special_value_text` set, the suffix was still rendered —
// producing visible "Never s" instead of "Never". The fix lives in
// two places:
//
//   1. `TextInputField::suffix` — lets the composite swap
//      the suffix to an empty string reactively.
//   2. `SpinBox::build` — wires a derived `Signal<String>` that
//      resolves to `""` exactly when the value equals `min` and
//      the field is not currently focused.
//
// We can't inspect the raw a11y string from the public
// `AccessibilityInfo` wrapper, and the inner `text_signal` is
// private to the field, so the regression coverage here focuses
// on the wiring surface — (1) the composite builds without panic
// for the full `suffix + special` path, (2) stepping off `min`
// and back works without crashing, and (3) the a11y role / actions
// stay correct.

#[test]
fn reactive_suffix_survives_value_transitions() {
    let value = Signal::new(0_i32);
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let id = tree.add(
        SpinBox::new(value.clone(), 0, 3600)
            .suffix(" s")
            .special_value_text(lit!("Never"))
            .label(lit!("Timeout")),
    );
    tree.layout(SizeProposal::exact(300.0, 60.0));
    tick(&mut tree);
    // Cross the special-text boundary a few times.
    value.set(30);
    tick(&mut tree);
    value.set(0);
    tick(&mut tree);
    value.set(120);
    tick(&mut tree);
    // Widget is still alive and value signal intact.
    assert_eq!(value.get(), 120);
    let info = tree.accessibility_node(id);
    assert_eq!(info.role(), teksilo_core::accesskit::Role::SpinButton);
}

// ── Tooltip ───────────────────────────────────────────────────────

#[test]
fn tooltip_appears_on_hover() {
    let value = Signal::new(0_i32);
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let id = tree.add(SpinBox::new(value, 0, 100).tooltip(lit!("Tip")));
    tree.layout(SizeProposal::exact(300.0, 60.0));
    tree.pointer_move(tree.bounds(id).center());
    tree.advance_time(std::time::Duration::from_secs(1));
    assert_eq!(
        tree.active_overlays().len(),
        1,
        "tooltip should appear on hover"
    );
    assert!(tree.find_by_label("Tip").is_some());
}

// ── Disabled appearance ───────────────────────────────────────────
//
// A SpinBox frames its `TextInputField` in *neutral* roles
// (`SurfaceRole::Content` / `BorderRole::Default`), and the disabled-role
// substitution in `ColorProp::resolve` only rewrites the *accent* family —
// so unlike a Filled Button it gets no automatic greying and must opt in via
// `SurfaceRole::Disabled`. It once did not, and stayed fully lit after
// `.enabled(false)`. These pin the painted pixels, not the intent.
//
// Match on the frame rect + stroke width rather than "some quad has this
// colour": the IntUI light palette reuses `#EBECF0` for `border`,
// `surface_hover` and `surface_disabled` alike, so a bare colour scan cannot
// tell an enabled field's *border* from a disabled field's *fill*.

/// The frame's fill (`stroke_width == 0`) and outline (`stroke_width > 0`),
/// identified as the quads covering the SpinBox's own bounds.
fn frame_colors(
    tree: &mut WidgetTree,
    id: teksilo_core::widget_id::WidgetId,
) -> (Option<[f32; 4]>, Option<[f32; 4]>) {
    let b = tree.bounds(id);
    let covers = |s: &[f32; 4]| {
        (s[0] - b.x).abs() < 0.5
            && (s[1] - b.y).abs() < 0.5
            && (s[2] - b.width).abs() < 0.5
            && (s[3] - b.height).abs() < 0.5
    };
    let frame = tree.render();
    let fill = frame
        .shapes
        .iter()
        .find(|s| covers(&s.screen) && s.stroke_width == 0.0)
        .map(|s| s.color);
    let border = frame
        .shapes
        .iter()
        .find(|s| covers(&s.screen) && s.stroke_width > 0.0)
        .map(|s| s.color);
    (fill, border)
}

fn assert_color(got: Option<[f32; 4]>, want: teksilo_tokens::Color, what: &str) {
    let want = want.to_array();
    let got = got.unwrap_or_else(|| panic!("no {what} quad painted at the SpinBox bounds"));
    assert!(
        got.iter()
            .zip(want.iter())
            .all(|(a, b)| (a - b).abs() < 1e-4),
        "{what}: expected {want:?}, painted {got:?}"
    );
}

fn spin_box_tree(enabled: bool) -> (WidgetTree, teksilo_core::widget_id::WidgetId) {
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let id = tree.add(SpinBox::new(Signal::new(5_i32), 0, 100).enabled(enabled));
    tree.layout(SizeProposal::exact(300.0, 60.0));
    (tree, id)
}

#[test]
fn disabled_spin_box_paints_the_neutral_disabled_frame() {
    let theme = teksilo_core::presets::intui::light();
    let (mut tree, id) = spin_box_tree(false);
    let (fill, border) = frame_colors(&mut tree, id);

    assert_color(fill, theme.colors.surface_disabled, "fill");
    assert_color(border, theme.colors.border_disabled, "border");

    // `accent_disabled` is a washed-out *accent* (pale cyan in IntUI) — right
    // for a Filled Button, wrong for a neutral field.
    let accent_disabled = theme.colors.accent_disabled.to_array();
    assert_ne!(fill.unwrap(), accent_disabled);
    assert_ne!(border.unwrap(), accent_disabled);
}

#[test]
fn enabled_spin_box_frame_is_unchanged() {
    let theme = teksilo_core::presets::intui::light();
    let (mut tree, id) = spin_box_tree(true);
    let (fill, border) = frame_colors(&mut tree, id);
    assert_color(fill, theme.colors.surface_content, "fill");
    assert_color(border, theme.colors.border, "border");
}

#[test]
fn spin_box_dims_reactively_without_a_rebuild() {
    // The chrome binds `effective_enabled_signal`, so flipping a bound
    // `Signal<bool>` must re-tint on the next paint — no rebuild.
    let theme = teksilo_core::presets::intui::light();
    let enabled = Signal::new(true);
    let mut tree = WidgetTree::new().with_theme(theme.clone());
    let id = tree.add(SpinBox::new(Signal::new(5_i32), 0, 100).enabled(enabled.clone()));
    tree.layout(SizeProposal::exact(300.0, 60.0));

    let (fill, _) = frame_colors(&mut tree, id);
    assert_color(fill, theme.colors.surface_content, "fill (enabled)");

    enabled.set(false);
    tree.layout(SizeProposal::exact(300.0, 60.0));
    let (fill, border) = frame_colors(&mut tree, id);
    assert_color(fill, theme.colors.surface_disabled, "fill (after disable)");
    assert_color(
        border,
        theme.colors.border_disabled,
        "border (after disable)",
    );
}

/// A SpinBox inside a disabled *form* must dim, even though it is itself
/// `enabled`. This is the case the obvious implementation gets wrong: a
/// `cfg.is_disabled` signal derived from `effective_enabled_signal` reflects
/// only the widget's OWN `enabled` prop, because that walk captures the
/// ancestor chain at call time and a widget's parent is not wired yet during
/// its own `build()`. The frame therefore paints `SurfaceRole::Field`, which
/// dims inside `ColorProp::resolve` from the paint walker's live arena chain.
#[test]
fn spin_box_dims_inside_a_disabled_ancestor() {
    use crate::primitives::VStack;

    let theme = teksilo_core::presets::intui::light();
    let enabled = Signal::new(true);
    let mut tree = WidgetTree::new().with_theme(theme.clone());
    let form = tree.add(VStack::new().child(SpinBox::new(Signal::new(5_i32), 0, 100)));
    tree.enabled_when(form, enabled.clone());
    tree.layout(SizeProposal::exact(300.0, 60.0));
    let spin = tree
        .children(form)
        .first()
        .copied()
        .expect("VStack should hold the SpinBox");

    enabled.set(false);
    tree.layout(SizeProposal::exact(300.0, 60.0));
    let (fill, _) = frame_colors(&mut tree, spin);
    assert_color(fill, theme.colors.surface_disabled, "fill");
}

// ── Mouse wheel ─────────────────────────────────────────────────────

/// Dispatch one wheel notch over `spin_id`.
///
/// `lines` is in Teksilo's own `ScrollDelta` sign, which is a *scroll
/// offset* delta rather than a raw wheel reading: `translate_mouse_wheel`
/// negates winit's natural sign, so a physical wheel-**down** notch arrives
/// here as `+3.0` (one notch × `LINES_PER_NOTCH`).
fn wheel(tree: &mut WidgetTree, spin_id: teksilo_core::widget_id::WidgetId, lines: f32) {
    use teksilo_canvas::Point;
    use teksilo_core::event::{ScrollDelta, WidgetEvent};

    // Scroll routes to the hovered widget, so park the pointer first.
    let b = tree.bounds(spin_id);
    tree.dispatch_event(WidgetEvent::PointerMove {
        position: Point::new(b.x + b.width * 0.5, b.y + b.height * 0.5),
    });
    tree.dispatch_event(WidgetEvent::Scroll {
        delta: ScrollDelta::Lines { x: 0.0, y: lines },
        modifiers: Modifiers::NONE,
    });
    tick(tree);
}

fn hover_wheel_spin(initial: i32) -> (WidgetTree, Signal<i32>, teksilo_core::widget_id::WidgetId) {
    let value = Signal::new(initial);
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let id = tree.add(
        SpinBox::new(value.clone(), 0, 100)
            .single_step(1)
            .wheel_mode(super::WheelMode::Hover),
    );
    tree.layout(SizeProposal::exact(300.0, 60.0));
    tick(&mut tree);
    (tree, value, id)
}

/// Wheel **down** must decrease the value, as it does in every desktop
/// stepper (Qt's `QAbstractSpinBox`, GTK's `GtkSpinButton`, WinUI's
/// `NumberBox`).
///
/// The trap this guards is the sign convention. `ScrollDelta` is not winit's
/// raw wheel reading — the platform layer negates it so that positive y
/// *increases a scroll offset*, i.e. scrolls down, which is why `ScrollArea`
/// and every data view add it straight to their scroll position. Reading
/// positive y as "the user scrolled up" therefore inverts the control, and
/// does so identically under every theme.
#[test]
fn wheel_down_decrements_and_wheel_up_increments() {
    let (mut tree, value, id) = hover_wheel_spin(50);

    // One physical wheel-down notch.
    wheel(&mut tree, id, 3.0);
    assert_eq!(value.get(), 49, "wheel down must decrease the value");

    // …and back up.
    wheel(&mut tree, id, -3.0);
    assert_eq!(value.get(), 50, "wheel up must increase the value");
}

/// The wheel must agree with the arrow keys: both are "one step", so
/// scrolling down and pressing ArrowDown have to move the same way.
#[test]
fn the_wheel_agrees_with_the_arrow_keys() {
    let (mut tree, value, id) = hover_wheel_spin(10);

    wheel(&mut tree, id, 3.0);
    assert_eq!(value.get(), 9, "one wheel-down notch is one step down");

    focus_field(&mut tree, id);
    tree.press_key(Key::ArrowDown, Modifiers::NONE);
    tick(&mut tree);
    assert_eq!(
        value.get(),
        8,
        "ArrowDown must move the same direction as wheel down"
    );
}

/// `WheelMode::Disabled` lets the notch bubble to a surrounding scroll
/// container instead of quietly changing a value the user was scrolling past.
#[test]
fn wheel_mode_disabled_ignores_the_notch() {
    let value = Signal::new(50_i32);
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let id = tree.add(
        SpinBox::new(value.clone(), 0, 100)
            .single_step(1)
            .wheel_mode(super::WheelMode::Disabled),
    );
    tree.layout(SizeProposal::exact(300.0, 60.0));
    tick(&mut tree);

    wheel(&mut tree, id, 3.0);
    assert_eq!(value.get(), 50);
}

// ── Locale-aware display and input ─────────────────────────────────

/// The SpinBox publishes its displayed text (number + suffix) as the AT
/// node's value, so that is the observable for the rendered form.
fn at_value(tree: &mut WidgetTree, id: teksilo_core::widget_id::WidgetId) -> String {
    let update = tree.sync_accessibility();
    let target = teksilo_core::accessibility::widget_id_to_node_id(id);
    update
        .nodes
        .iter()
        .find(|(nid, _)| *nid == target)
        .and_then(|(_, n)| n.value().map(str::to_string))
        .expect("spin box AT value")
}

fn with_locale<R>(tag: &str, f: impl FnOnce() -> R) -> R {
    teksilo_i18n::thread_local::clear();
    let cfg = teksilo_i18n::I18nConfig::test_only(tag, &[("x", "x")]);
    teksilo_i18n::thread_local::install(teksilo_i18n::I18nManager::from_config(&cfg));
    let out = f();
    teksilo_i18n::thread_local::clear();
    out
}

#[test]
fn displays_the_locale_decimal_separator() {
    with_locale("fr-FR", || {
        let value = Signal::new(12.5_f64);
        let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
        let id = tree.add(SpinBox::new(value, 0.0, 100.0).decimals(1));
        tree.layout(SizeProposal::exact(300.0, 60.0));
        tick(&mut tree);
        assert_eq!(at_value(&mut tree, id), "12,5");
    });
}

#[test]
fn grouping_is_off_by_default_and_opt_in() {
    with_locale("en-US", || {
        let value = Signal::new(1_234_567_i64);
        let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
        let plain = tree.add(SpinBox::new(value.clone(), 0, 9_999_999));
        let grouped = tree.add(SpinBox::new(value, 0, 9_999_999).use_grouping(true));
        tree.layout(SizeProposal::exact(600.0, 200.0));
        tick(&mut tree);
        assert_eq!(at_value(&mut tree, plain), "1234567");
        assert_eq!(at_value(&mut tree, grouped), "1,234,567");
    });
}

#[test]
fn localized_false_pins_the_c_locale() {
    // The escape hatch for a number that is an identifier rather than a
    // quantity — a port, a version component, a database id.
    with_locale("fr-FR", || {
        let value = Signal::new(8080.5_f64);
        let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
        let id = tree.add(
            SpinBox::new(value, 0.0, 99999.0)
                .decimals(1)
                .localized(false),
        );
        tree.layout(SizeProposal::exact(300.0, 60.0));
        tick(&mut tree);
        assert_eq!(at_value(&mut tree, id), "8080.5");
    });
}

#[test]
fn grouping_keeps_large_integers_exact() {
    // The display path is a string transform over the value's own
    // `Display`, never a round-trip through `f64`, so an i64 past 2^53
    // survives being shown.
    with_locale("en-US", || {
        let value = Signal::new(9_007_199_254_740_993_i64);
        let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
        let id = tree.add(SpinBox::new(value, 0, i64::MAX).use_grouping(true));
        tree.layout(SizeProposal::exact(400.0, 60.0));
        tick(&mut tree);
        assert_eq!(at_value(&mut tree, id), "9,007,199,254,740,993");
    });
}

#[test]
fn a_locale_switch_re_renders_the_number_in_place() {
    // SpinBox already re-formats on `set_locale` via a `ctx.effect` on
    // the locale signal — this pins that the effect now has something
    // locale-dependent to re-render, and that it re-resolves the
    // conventions rather than reusing the ones captured at build time.
    with_locale("en-US", || {
        let value = Signal::new(12.5_f64);
        let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
        tree.set_locale("en-US".to_string());
        let id = tree.add(SpinBox::new(value, 0.0, 100.0).decimals(1));
        tree.layout(SizeProposal::exact(300.0, 60.0));
        tick(&mut tree);
        assert_eq!(at_value(&mut tree, id), "12.5");

        teksilo_i18n::thread_local::clear();
        let cfg = teksilo_i18n::I18nConfig::test_only("fr-FR", &[("x", "x")]);
        teksilo_i18n::thread_local::install(teksilo_i18n::I18nManager::from_config(&cfg));
        tree.set_locale("fr-FR".to_string());
        tree.layout(SizeProposal::exact(300.0, 60.0));
        tick(&mut tree);
        assert_eq!(at_value(&mut tree, id), "12,5");
    });
}

#[test]
fn the_commit_path_reads_the_locale_form_back() {
    // The display and parse directions share one `NumberPresentation`,
    // so whatever the field shows, the commit can read.
    with_locale("fr-FR", || {
        let p = super::NumberPresentation::resolve(true, false);
        assert_eq!(p.parse::<f64>("12,5"), Some(12.5));
        assert_eq!(p.parse::<f64>("-12,5"), Some(-12.5));
        // A numeric keypad still works: `.` is neither separator in
        // fr-FR, so it reads as the decimal point.
        assert_eq!(p.parse::<f64>("12.5"), Some(12.5));
        assert_eq!(p.parse::<f64>("nope"), None);
    });
}

#[test]
fn the_commit_path_reads_grouped_input() {
    with_locale("en-US", || {
        let p = super::NumberPresentation::resolve(true, true);
        assert_eq!(p.parse::<i64>("1,234,567"), Some(1_234_567));
        // Past 2^53 — the parse never goes through f64 either.
        assert_eq!(
            p.parse::<i64>("9,007,199,254,740,993"),
            Some(9_007_199_254_740_993)
        );
    });
}

#[test]
fn the_input_filter_admits_the_locale_separator_and_ascii_both() {
    with_locale("fr-FR", || {
        let p = super::NumberPresentation::resolve(true, false);
        assert!(p.accepts_char::<f64>(','), "the locale decimal separator");
        assert!(p.accepts_char::<f64>('.'), "the numeric keypad dot");
        assert!(p.accepts_char::<f64>('-'));
        assert!(p.accepts_char::<f64>('7'));
        assert!(!p.accepts_char::<f64>('q'));
    });
    with_locale("ar-EG", || {
        let p = super::NumberPresentation::resolve(true, false);
        assert!(p.accepts_char::<f64>('٧'), "an Arabic-Indic digit");
        assert!(p.accepts_char::<f64>('٫'), "the locale decimal separator");
        assert!(p.accepts_char::<f64>('7'), "an ASCII digit still types");
    });
}

#[test]
fn the_input_filter_admits_the_group_separator_only_when_grouping() {
    // fr-FR groups with U+202F, a character `f64`'s own filter rejects,
    // so the grouping flag is the only thing that can admit it.
    with_locale("fr-FR", || {
        let ungrouped = super::NumberPresentation::resolve(true, false);
        let grouped = super::NumberPresentation::resolve(true, true);
        assert!(!ungrouped.accepts_char::<f64>('\u{202f}'));
        assert!(grouped.accepts_char::<f64>('\u{202f}'));
    });
}

#[test]
fn localized_false_neither_renders_nor_reads_the_locale_form() {
    with_locale("fr-FR", || {
        let p = super::NumberPresentation::resolve(false, false);
        assert_eq!(p.parse::<f64>("12.5"), Some(12.5));
        assert_eq!(p.parse::<f64>("12,5"), None);
        assert!(!p.accepts_char::<f64>(','));
    });
}