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
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
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

//! `SpinBox` — numeric input with increment/decrement buttons.
//!
//! A generic composite over [`SpinValue`]
//! (integer and floating-point primitives), pairing the
//! [`TextInputField`] editing
//! primitive with a stacked pair of up/down step buttons. Semantics
//! are a synthesis of Qt's `QSpinBox` / `QDoubleSpinBox`, WinUI 3's
//! `NumberBox`, GTK's `GtkSpinButton`, and the W3C ARIA
//! `spinbutton` role.
//!
//! # Behaviour
//!
//! - **Value binding**: a `Signal<T>` is the single source of truth.
//!   Typing and stepping update it; external writes re-format the
//!   editable text.
//! - **Commit model**: the user can type freely (subject to the
//!   per-character input filter). The value is *committed* on
//!   [`Enter`](teksilo_core::event::Key::Enter) or on focus loss —
//!   at commit time the text is parsed, clamped into `[min, max]`
//!   (or wrapped, per [`WrapMode`]), and reformatted. Invalid input
//!   reverts to the last known good value.
//! - **Keyboard**:
//!   - `Up` / `Down` → ±[`single_step`](SpinBox::single_step)
//!   - `PageUp` / `PageDown` → ±[`page_step`](SpinBox::page_step)
//!     (default: `10 × single_step`)
//!   - `Enter` → commit (stays focused)
//!   - `Home` / `End` stay bound to the text cursor (Qt-compatible).
//! - **Mouse wheel**: adjusts by `single_step` — wheel **down**
//!   decreases, wheel **up** increases, matching `QAbstractSpinBox`,
//!   `GtkSpinButton` and WinUI's `NumberBox`. Gated by
//!   [`wheel_mode`](SpinBox::wheel_mode) (default: only when
//!   focused, to avoid accidental scroll changes).
//! - **Buttons**: up/down buttons stack to the right of the field
//!   by default; can be hidden with
//!   [`button_layout`](SpinBox::button_layout).
//! - **Special value text**: when the current value equals `min`
//!   and [`special_value_text`](SpinBox::special_value_text) is
//!   set, the field shows that string instead of the formatted
//!   number — Qt's "Auto" / "None" / "Unlimited" affordance.
//! - **Adaptive step**: with
//!   [`StepType::Adaptive`], the effective step
//!   tracks the decimal magnitude of the current value (Qt's
//!   `AdaptiveDecimalStepType`). Useful for values that span many
//!   orders of magnitude in the same control.
//! - **Locale**: the number follows the active locale's decimal
//!   separator, digits and minus sign
//!   ([`localized`](SpinBox::localized), on by default); thousands
//!   separators are opt-in
//!   ([`use_grouping`](SpinBox::use_grouping), off by default, as in
//!   Qt). Display, commit parse and the per-character input filter
//!   all resolve from one `NumberPresentation`, so they cannot
//!   disagree about which separator the field is using — a French
//!   user sees `12,5`, types `12,5`, and the numeric keypad's `.`
//!   still works. Rendering is a string transform over the value's
//!   own `Display`, never an `f64` round-trip, so a `SpinBox<i64>`
//!   stays exact past 2^53. Turn it off for a number that is an
//!   *identifier* rather than a quantity (port, version component,
//!   database id). With no `I18nManager` installed the active locale
//!   is the C locale and this is a no-op.
//! - **Custom formatter / parser**: full override via
//!   [`text_from_value`](SpinBox::text_from_value) and
//!   [`value_from_text`](SpinBox::value_from_text); together they
//!   let you implement currency, percentages with stored fraction,
//!   hex, duration, anything. A custom formatter/parser owns the
//!   whole convention — it is not re-punctuated by the locale layer.
//!
//! # Accessibility
//!
//! The composite exposes itself as
//! [`Role::SpinButton`](teksilo_core::accesskit::Role::SpinButton)
//! with numeric value, min, max, step, and jump properties set on
//! the AccessKit node; the AT receives
//! [`Increment`](teksilo_core::accesskit::Action::Increment),
//! [`Decrement`](teksilo_core::accesskit::Action::Decrement),
//! [`SetValue`](teksilo_core::accesskit::Action::SetValue), and
//! [`Focus`](teksilo_core::accesskit::Action::Focus) actions. The
//! step buttons are structurally part of the SpinBox and publish
//! no separate a11y nodes.
//!
//! # Example
//!
//! ```ignore
//! use teksilo::widgets::{SpinBox, WrapMode};
//!
//! let font_size = ctx.signal(12_i32);
//! ctx.add(
//!     SpinBox::new(font_size, 4, 72)
//!         .single_step(1)
//!         .page_step(10)
//!         .suffix(" pt"),
//! );
//!
//! let gain_db = ctx.signal(0.0_f32);
//! ctx.add(
//!     SpinBox::new(gain_db, -60.0, 12.0)
//!         .single_step(0.5)
//!         .decimals(1)
//!         .suffix(" dB")
//!         .wrap_mode(WrapMode::Clamp),
//! );
//! ```

mod step_button;
#[cfg(test)]
mod tests;
mod value;

use std::rc::Rc;

pub use self::value::SpinValue;

use teksilo_canvas::{Path, Point, Rect, Size, SizeProposal};
use teksilo_core::accessibility::AccessNodeBuilder;
use teksilo_core::build_context::BuildContext;
use teksilo_core::event::{EventResponse, Key, ScrollDelta, WidgetEvent};
use teksilo_core::signal::{Prop, Signal};
use teksilo_core::widget::{EventContext, LayoutContext, Widget, WidgetPlacement};
use teksilo_core::widget_builder::HandlerSet;
use teksilo_core::widget_id::WidgetId;
use teksilo_text::SharedTypesetter;
use teksilo_tokens::{CornerRadius, TextStyle};

use crate::primitives::icon_widget::IconWidget;
use crate::primitives::text_input_field::TextInputField;
use crate::primitives::{MinSize, Padding};

use self::step_button::StepButton;

// ── Enums ──────────────────────────────────────────────────────────

/// Out-of-range behavior when stepping past `min` or `max`.
///
/// Set via [`SpinBox::wrap_mode`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum WrapMode {
    /// Clamp to `min` / `max` (default).
    #[default]
    Clamp,
    /// Wrap around: past `max` jumps to `min`, past `min` jumps to
    /// `max`. Matches Qt's `QAbstractSpinBox::wrapping`.
    Wrap,
}

/// Step-size policy for each key/button press.
///
/// Set via [`SpinBox::step_type`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum StepType {
    /// Always step by `single_step` (default).
    #[default]
    Fixed,
    /// Step by the decimal power-of-ten immediately below the
    /// current value's magnitude — e.g. values 1–9 step by 1,
    /// 10–99 by 10, 100–999 by 100. Matches Qt's
    /// `AdaptiveDecimalStepType`. Integer types honor the same
    /// rule using the magnitude of the absolute value.
    Adaptive,
}

pub use teksilo_core::styles::ButtonLayout;
use teksilo_i18n::LocalizedString;

/// When the mouse wheel is allowed to adjust the value.
///
/// Set via [`SpinBox::wheel_mode`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum WheelMode {
    /// Wheel adjusts only when the field is focused. Default —
    /// prevents accidental changes when the user is scrolling a
    /// larger surrounding view.
    #[default]
    Focused,
    /// Wheel adjusts whenever the pointer is over the widget.
    Hover,
    /// Wheel never adjusts the value; events bubble to the
    /// surrounding scroll container.
    Disabled,
}

/// How the SpinBox decides its horizontal size envelope.
///
/// Chosen via the [`width`](SpinBox::width),
/// [`width_chars`](SpinBox::width_chars), and
/// [`fill_width`](SpinBox::fill_width) builder methods — the enum
/// itself is the storage, not a separate public configuration
/// API.
#[derive(Debug, Clone)]
pub enum WidthPolicy {
    /// Cap the widget at a fixed logical-pixel width. Default is
    /// `DEFAULT_PREFERRED_WIDTH` (120 dp), matching Qt's
    /// `QSpinBox` sizeHint.
    Pixels(f32),
    /// Size the widget to fit this many reference digits (`'0'`)
    /// plus the configured suffix, padding, and step buttons.
    /// Measurement uses the theme font at build time.
    Chars(u32),
    /// Let the widget expand horizontally to fill whatever space
    /// the parent offers. Equivalent to an infinite pixel cap.
    Fill,
}

// ── Type aliases for builder closures ──────────────────────────────

type TextFromValue<T> = Rc<dyn Fn(T) -> LocalizedString>;
type ValueFromText<T> = Rc<dyn Fn(&str) -> Option<T>>;
type OnValueChangedFn<T> = Rc<dyn Fn(T, &mut EventContext)>;

/// Minimum total width. Below this the stacked step buttons stop
/// fitting next to the field. Widgets narrower than this are
/// enforced to the minimum at layout time via `MinSize`.
const MIN_WIDTH_WITH_BUTTONS: f32 = 72.0;
/// Minimum total width when buttons are hidden — the field alone
/// plus padding still reads as a numeric control.
const MIN_WIDTH_NO_BUTTONS: f32 = 48.0;
/// Default maximum width. Matches Qt's `QSpinBox` sizeHint for a
/// 4-digit value + unit suffix and stays tight in Int UI-style
/// dense forms.
const DEFAULT_PREFERRED_WIDTH: f32 = 120.0;

// ── SpinBox ────────────────────────────────────────────────────────

/// Numeric input with step buttons. Generic over
/// [`SpinValue`] — pre-implemented for `i32`, `i64`, `u32`, `u64`,
/// `usize`, `f32`, and `f64`.
pub struct SpinBox<T: SpinValue> {
    // ── Required configuration ──────────────────────────────────────
    value: Signal<T>,
    min: T,
    max: T,

    // ── Optional configuration (builders) ───────────────────────────
    single_step: T,
    page_step: Option<T>,
    decimals: u8,
    suffix: String,
    /// Whether the displayed number follows the active locale's
    /// conventions. See [`localized`](SpinBox::localized).
    localized: bool,
    /// Whether the displayed number carries thousands separators.
    /// Off by default — see [`use_grouping`](SpinBox::use_grouping).
    use_grouping: bool,
    special_value_text: Option<LocalizedString>,
    wrap_mode: WrapMode,
    step_type: StepType,
    button_layout: ButtonLayout,
    wheel_mode: WheelMode,
    /// Horizontal sizing policy. One of [`WidthPolicy::Pixels`]
    /// (fixed cap), [`WidthPolicy::Chars`] (font-metric-based),
    /// or [`WidthPolicy::Fill`] (stretch to parent). Set by the
    /// [`width`](SpinBox::width), [`width_chars`](SpinBox::width_chars),
    /// and [`fill_width`](SpinBox::fill_width) builder methods.
    width_policy: WidthPolicy,
    label: Option<LocalizedString>,
    placeholder: LocalizedString,
    /// Enabled state, static or reactive; forwarded to the arena at
    /// build time. Also captured as a build-time snapshot for the
    /// several build-time decisions inside `build()` that need a
    /// plain `bool` (seeding the inner `TextInputField`'s read-only
    /// mode, deriving the step buttons' enabled signals, and gating
    /// the key-preview / scroll handlers alongside `read_only`).
    enabled: Prop<bool>,
    read_only: bool,
    text_from_value: Option<TextFromValue<T>>,
    value_from_text: Option<ValueFromText<T>>,
    on_value_changed: Option<OnValueChangedFn<T>>,

    // ── Internal state (set during build) ───────────────────────────
    text_signal: Signal<String>,
    /// Tracks whether any descendant of the SpinBox root holds focus —
    /// in practice, the inner `TextInputField`. Driven by
    /// `WidgetBuilder::focus_within` on the root frame; replaces the
    /// previous multi-state `InteractionState` signal that was piped
    /// in/out of the field via `interaction_signal()`. The outer SpinBox
    /// only ever cared about Focused vs not.
    focused: Signal<bool>,
    can_step_up: Signal<bool>,
    can_step_down: Signal<bool>,
    /// Cached horizontal cap in pixels, resolved from `width_policy`
    /// at build time (Chars mode measures the theme font). `None`
    /// when the policy is `Fill`. Applied by `size_that_fits` by
    /// narrowing the proposal before delegating to the child — this
    /// replaces wrapping the subtree in a `MaxSize`, which clips
    /// children and would truncate the focus-state border stroke
    /// against its own shape quad.
    pixel_cap: Option<f32>,
    /// Floor width so the field and step buttons always fit. Also
    /// resolved at build from `button_layout`.
    min_width: f32,
    /// Per-call style override for the SpinBox chrome. Higher
    /// precedence than the theme-wide `style_slots.spin_box` slot.
    style_override: Option<teksilo_core::styles::SharedSpinBoxStyle>,
    root_child_id: Option<WidgetId>,
    field_id: Option<WidgetId>,

    // ── Tooltip slots (mutually exclusive; last setter wins) ─────────
    /// Optional plain tooltip text shown after a hover delay. Mutually
    /// exclusive with the rich / composite slots — every setter clears
    /// the other two so the last call wins.
    tooltip_text: Option<LocalizedString>,
    /// Optional rich tooltip source (registry key or inline content).
    rich_tooltip_source: Option<crate::tooltip::RichTooltipSource>,
    /// Optional composite tooltip body (arbitrary widget tree).
    composite_tooltip_content: Option<Box<dyn Widget>>,
}

impl<T: SpinValue> std::fmt::Debug for SpinBox<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SpinBox")
            .field("min", &self.min)
            .field("max", &self.max)
            .field("single_step", &self.single_step)
            .field("decimals", &self.decimals)
            .field("localized", &self.localized)
            .field("use_grouping", &self.use_grouping)
            .field("wrap_mode", &self.wrap_mode)
            .finish_non_exhaustive()
    }
}

impl<T: SpinValue> SpinBox<T> {
    /// Construct a new SpinBox bound to `value` with the given
    /// inclusive range. `min` must be ≤ `max`.
    pub fn new(value: Signal<T>, min: T, max: T) -> Self {
        // `single_step` defaults to 1 on the value's f64 scale —
        // works naturally for integers and for decimal floats.
        // Callers with a different natural step (0.1, 0.5, 10, …)
        // override via `single_step(...)`.
        let default_step = T::from_f64_saturating(1.0);
        Self {
            value,
            min,
            max,
            single_step: default_step,
            page_step: None,
            decimals: if T::is_integer() { 0 } else { 2 },
            suffix: String::new(),
            localized: true,
            use_grouping: false,
            special_value_text: None,
            wrap_mode: WrapMode::Clamp,
            step_type: StepType::Fixed,
            button_layout: ButtonLayout::Stacked,
            wheel_mode: WheelMode::Focused,
            width_policy: WidthPolicy::Pixels(DEFAULT_PREFERRED_WIDTH),
            label: None,
            placeholder: LocalizedString::literal(String::new()),
            enabled: Prop::Static(true),
            read_only: false,
            text_from_value: None,
            value_from_text: None,
            on_value_changed: None,
            text_signal: Signal::new(String::new()),
            focused: Signal::new(false),
            can_step_up: Signal::new(true),
            can_step_down: Signal::new(true),
            pixel_cap: None,
            min_width: MIN_WIDTH_WITH_BUTTONS,
            style_override: None,
            root_child_id: None,
            field_id: None,
            tooltip_text: None,
            rich_tooltip_source: None,
            composite_tooltip_content: None,
        }
    }

    /// Per-call style override. Higher precedence than the theme-wide
    /// `style_slots.spin_box` slot.
    pub fn style(mut self, style: impl teksilo_core::styles::SpinBoxStyle) -> Self {
        self.style_override = Some(Rc::new(style));
        self
    }

    // ── Builder methods ─────────────────────────────────────────────

    /// Set the step size for `Up` / `Down` / single wheel tick /
    /// button tap.
    pub fn single_step(mut self, step: T) -> Self {
        self.single_step = step;
        self
    }

    /// Set the step size for `PageUp` / `PageDown`. When unset,
    /// defaults to `10 × single_step` at build time.
    pub fn page_step(mut self, step: T) -> Self {
        self.page_step = Some(step);
        self
    }

    /// Number of decimal places shown for floating-point types.
    /// Ignored for integer types.
    pub fn decimals(mut self, decimals: u8) -> Self {
        self.decimals = decimals;
        self
    }

    /// Whether the number follows the active locale's conventions —
    /// decimal separator, digits, and minus sign. **On by default.**
    ///
    /// A French user sees `12,5`, not `12.5`, and can type either: the
    /// commit path de-localizes before parsing, and the input filter
    /// accepts both the locale's separator and the ASCII one, so a
    /// numeric keypad still works.
    ///
    /// Turn it **off** for a number that is an identifier rather than a
    /// quantity — a port number, a version component, a database id, a
    /// pixel offset in a file format. Those read wrong grouped or
    /// re-punctuated, and their conventional form is the C-locale one.
    ///
    /// Localization is a string transform over the value's own
    /// `Display`, not a round-trip through `f64`, so a `SpinBox<i64>`
    /// keeps full precision past 2^53.
    ///
    /// With no `I18nManager` installed the active locale resolves to the
    /// C locale, so this is a no-op in tests and in apps that have not
    /// opted into i18n.
    pub fn localized(mut self, on: bool) -> Self {
        self.localized = on;
        self
    }

    /// Whether the displayed number carries thousands separators.
    /// **Off by default**, matching Qt (`QAbstractSpinBox::
    /// isGroupSeparatorShown` is false unless asked for).
    ///
    /// Separators help a large read-only quantity and get in the way of
    /// a field being typed into, so this is opt-in per SpinBox rather
    /// than a locale-wide default. Grouping follows the locale's own
    /// group sizes, including the Indic lakh system (`12,34,567`).
    ///
    /// Has no effect when [`localized`](Self::localized) is off.
    pub fn use_grouping(mut self, on: bool) -> Self {
        self.use_grouping = on;
        self
    }

    /// Qt-style non-editable trailing unit (e.g. `" %"`, `" px"`,
    /// `" dB"`). Rendered flush-right inside the field's border;
    /// the caret cannot enter it.
    pub fn suffix(mut self, text: impl Into<String>) -> Self {
        self.suffix = text.into();
        self
    }

    /// Text shown in place of the formatted value when the current
    /// value equals `min`. Use for "Auto", "None", "Off",
    /// "Unlimited" affordances where the minimum has special
    /// semantics. When the field is focused the real number is
    /// shown instead so the user can type.
    pub fn special_value_text(mut self, text: impl Into<LocalizedString>) -> Self {
        self.special_value_text = Some(text.into());
        self
    }

    /// Set the out-of-range behavior when stepping past `min` or `max`
    /// (default: `Clamp`).
    pub fn wrap_mode(mut self, mode: WrapMode) -> Self {
        self.wrap_mode = mode;
        self
    }

    /// Set the step-size policy (default: `Fixed`). Use
    /// `StepType::Adaptive` for values that span many orders of magnitude.
    pub fn step_type(mut self, step_type: StepType) -> Self {
        self.step_type = step_type;
        self
    }

    /// Override the step-button layout (default: `Stacked` — stacked
    /// up/down buttons to the right of the field).
    pub fn button_layout(mut self, layout: ButtonLayout) -> Self {
        self.button_layout = layout;
        self
    }

    /// Convenience wrapper over [`button_layout`](Self::button_layout):
    /// `true` → `ButtonLayout::Stacked`, `false` → `ButtonLayout::Hidden`.
    /// Matches the Int UI guideline that SpinBoxes in dense forms
    /// often hide the step buttons to reduce visual noise and let
    /// keyboard / wheel carry the affordance — pass
    /// `.show_buttons(false)` on those call sites.
    pub fn show_buttons(mut self, show: bool) -> Self {
        self.button_layout = if show {
            ButtonLayout::Stacked
        } else {
            ButtonLayout::Hidden
        };
        self
    }

    /// Set when the mouse wheel adjusts the value (default: `Focused` —
    /// only when the inner field holds focus).
    pub fn wheel_mode(mut self, mode: WheelMode) -> Self {
        self.wheel_mode = mode;
        self
    }

    /// Cap the widget's horizontal size at a fixed logical-pixel
    /// width. If the parent offers less, the SpinBox shrinks (down
    /// to the internal 72 dp / 48 dp floor that keeps the buttons
    /// and field from overlapping). Default: 120 dp, matching Qt
    /// `QSpinBox` sizeHint and Int UI form density.
    ///
    /// ```rust
    /// # use teksilo_widgets::SpinBox;
    /// # use teksilo_core::signal::Signal;
    /// # let v = Signal::new(0_i32);
    /// let _w = SpinBox::new(v.clone(), 0, 9999).width(80.0);        // narrow
    /// let _w = SpinBox::new(v.clone(), 0, 9999).width(200.0);       // wider
    /// let _w = SpinBox::new(v.clone(), 0, 9999).fill_width();       // stretch to parent
    /// let _w = SpinBox::new(v.clone(), 0, 9999).width_chars(5);     // "fits 5 digits"
    /// ```
    pub fn width(mut self, width: f32) -> Self {
        self.width_policy = WidthPolicy::Pixels(width.max(0.0));
        self
    }

    /// Size the widget to fit exactly `chars` reference digits plus
    /// the configured suffix, padding, and step buttons. The
    /// measurement uses the actual theme font at build time (same
    /// `SharedTypesetter` the field draws with), so values stay
    /// right under runtime theme switches and HiDPI scale changes.
    ///
    /// ```rust
    /// # use teksilo_widgets::SpinBox;
    /// # use teksilo_core::signal::Signal;
    /// # let port = Signal::new(8080_i32);
    /// # let pct = Signal::new(0_i32);
    /// let _w = SpinBox::new(port, 0, 65_535).width_chars(5);           // 5 digits
    /// let _w = SpinBox::new(pct, 0, 100).suffix(" %").width_chars(3);  // 3 + " %"
    /// ```
    pub fn width_chars(mut self, chars: u32) -> Self {
        self.width_policy = WidthPolicy::Chars(chars);
        self
    }

    /// Let the widget expand to fill the horizontal space offered
    /// by its parent, instead of capping at [`width`](Self::width).
    /// Use inside toolbars, inspector panels, or an
    /// `Expand::horizontal` column that should stretch with the
    /// surrounding layout.
    pub fn fill_width(mut self) -> Self {
        self.width_policy = WidthPolicy::Fill;
        self
    }

    /// Set the accessible name announced by screen readers as the
    /// control's label. ARIA requires spin buttons to have a label;
    /// when none is set here the caller is responsible for labelling
    /// via a wrapping element or `access_label`.
    pub fn label(mut self, label: impl Into<LocalizedString>) -> Self {
        let ls: LocalizedString = label.into();
        self.label = Some(ls);
        self
    }

    /// Set the placeholder text shown in the field when it is empty.
    pub fn placeholder(mut self, text: impl Into<LocalizedString>) -> Self {
        let ls: LocalizedString = text.into();
        self.placeholder = ls;
        self
    }

    /// Set the enabled state, statically or reactively. Forwarded to
    /// the arena at build time via
    /// `ctx.enabled_when(spinbox_id, self.enabled.clone())`.
    pub fn enabled(mut self, enabled: impl Into<Prop<bool>>) -> Self {
        self.enabled = enabled.into();
        self
    }

    /// Prevent the user from typing in the field while still allowing
    /// keyboard and button stepping.
    pub fn read_only(mut self, read_only: bool) -> Self {
        self.read_only = read_only;
        self
    }

    /// Override the value → display-string conversion. Receives the
    /// raw value; returns whatever string should appear in the
    /// field. Suffix and `special_value_text` still apply on top of
    /// the returned string.
    pub fn text_from_value(mut self, f: impl Fn(T) -> LocalizedString + 'static) -> Self {
        self.text_from_value = Some(Rc::new(f));
        self
    }

    /// Override the parse step. Receives the field's raw text
    /// (without the suffix, which is never part of the editable
    /// content); returns `Some(value)` to accept or `None` to
    /// reject. Invalid input reverts to the last good value on
    /// commit.
    pub fn value_from_text(mut self, f: impl Fn(&str) -> Option<T> + 'static) -> Self {
        self.value_from_text = Some(Rc::new(f));
        self
    }

    /// Closure fired each time the value is committed (keyboard
    /// step, button tap, wheel tick, Enter, blur). Bound observers
    /// on the value signal also see every change; use this hook
    /// when the caller needs an `EventContext` (e.g. to fire an
    /// intent).
    pub fn on_value_changed(mut self, f: impl Fn(T, &mut EventContext) + 'static) -> Self {
        self.on_value_changed = Some(Rc::new(f));
        self
    }

    // ── Tooltip builder methods ─────────────────────────────────────

    /// Attach a plain single-line tooltip shown after a hover delay.
    ///
    /// Mutually exclusive with [`rich_tooltip`](Self::rich_tooltip),
    /// [`rich_tooltip_content`](Self::rich_tooltip_content), and
    /// [`composite_tooltip`](Self::composite_tooltip) — each setter
    /// clears the other two so the last call wins.
    pub fn tooltip(mut self, text: impl Into<LocalizedString>) -> Self {
        self.tooltip_text = Some(text.into());
        self.rich_tooltip_source = None;
        self.composite_tooltip_content = None;
        self
    }

    /// Attach a rich tooltip looked up by registry key.
    ///
    /// The key must match a [`TooltipContent`](crate::tooltip::TooltipContent)
    /// registered in the application's tooltip registry. Mutually
    /// exclusive with [`tooltip`](Self::tooltip),
    /// [`rich_tooltip_content`](Self::rich_tooltip_content), and
    /// [`composite_tooltip`](Self::composite_tooltip).
    pub fn rich_tooltip(mut self, key: impl Into<String>) -> Self {
        self.rich_tooltip_source = Some(crate::tooltip::RichTooltipSource::Key(key.into()));
        self.tooltip_text = None;
        self.composite_tooltip_content = None;
        self
    }

    /// Attach a rich tooltip with inline content (no registry key
    /// required). Mutually exclusive with [`tooltip`](Self::tooltip),
    /// [`rich_tooltip`](Self::rich_tooltip), and
    /// [`composite_tooltip`](Self::composite_tooltip).
    pub fn rich_tooltip_content(mut self, content: crate::tooltip::TooltipContent) -> Self {
        self.rich_tooltip_source = Some(crate::tooltip::RichTooltipSource::Content(content));
        self.tooltip_text = None;
        self.composite_tooltip_content = None;
        self
    }

    /// Attach a composite tooltip whose body is an arbitrary widget
    /// tree. Mutually exclusive with [`tooltip`](Self::tooltip),
    /// [`rich_tooltip`](Self::rich_tooltip), and
    /// [`rich_tooltip_content`](Self::rich_tooltip_content).
    pub fn composite_tooltip(mut self, content: impl Widget + 'static) -> Self {
        self.composite_tooltip_content = Some(Box::new(content));
        self.tooltip_text = None;
        self.rich_tooltip_source = None;
        self
    }

    /// Like [`composite_tooltip`](Self::composite_tooltip) but accepts
    /// an already-boxed widget body. Used by wrapper widgets that
    /// forward a boxed composite body.
    pub(crate) fn composite_tooltip_boxed(mut self, content: Box<dyn Widget>) -> Self {
        self.composite_tooltip_content = Some(content);
        self.tooltip_text = None;
        self.rich_tooltip_source = None;
        self
    }

    // ── Signal accessors (call before add to tree) ──────────────────

    /// The bound numeric value signal.
    pub fn value(&self) -> Signal<T> {
        self.value.clone()
    }
}

impl<T: SpinValue> Widget for SpinBox<T> {
    fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
        // Sanity-check the range once. A malformed range is a
        // programming error, not a runtime user error.
        debug_assert!(self.min <= self.max, "SpinBox min must be <= max");

        // SpinBox reads theme tokens once for static layout params
        // (padding, focus-ring width, body typography). Colors resolve
        // through role props against the current theme at paint time,
        // so runtime theme switches re-paint without riding through
        // per-widget zips.
        //
        // The snapshot is OWNED (`theme_signal.get()` clones), because the
        // body typography is read further down in `build()` — past many
        // `ctx.add(...)` / `ctx.effect(...)` calls that need a mutable
        // borrow of `ctx`. A `ctx.theme()` borrow would hold `ctx`
        // immutable across those calls and fail the borrow checker.
        let theme = ctx.theme_signal().get();
        use crate::styles::recipe_text_input_style as field_dims;
        let field_border_width = field_dims::TEXT_FIELD_BORDER_WIDTH;
        let focus_ring_width = theme.shape.focus_ring_width;

        // Capture configuration into owned clones for the effect
        // closures. The builder closures are `Rc`-wrapped already.
        let min = self.min;
        let max = self.max;
        let decimals = self.decimals;
        let suffix_str = self.suffix.clone();
        let special_text = self.special_value_text.clone();
        let text_from_value = self.text_from_value.clone();
        let value_from_text = self.value_from_text.clone();
        let wrap_mode = self.wrap_mode;
        let step_type = self.step_type;
        let single_step = self.single_step;
        let page_step = self
            .page_step
            .unwrap_or_else(|| single_step.saturating_mul_u32(10));
        let on_value_changed = self.on_value_changed.clone();
        let self_id = ctx.self_id();
        // Forward the enabled state into the arena; see IconButton.
        ctx.enabled_when(self_id, self.enabled.clone());
        // Snapshot the build-time enabled state into a local for
        // closures that capture it for read-only-style guards on
        // wheel events / step buttons. The framework's event gate
        // already refuses to dispatch to disabled subtrees, so the
        // value here only matters for the few build-time decisions
        // (e.g. seeding the inner TextInputField's read_only mode).
        let enabled = self.enabled.get();
        let read_only = self.read_only;
        let wheel_mode = self.wheel_mode;

        // Resolve the locale's number conventions once, and hand the
        // *same* value to the display path, the commit parse and the
        // input filter. Split resolution would let the three disagree
        // about which separator this field uses — the failure mode
        // `DateEdit` avoids by deriving format, parse and mask from one
        // `ParsedPattern`.
        //
        // Rebuild-level reactivity is not needed: the effect on
        // `ctx.locale_signal()` below re-formats the text in place, and
        // the closures below re-resolve on the next build.
        let presentation = NumberPresentation::resolve(self.localized, self.use_grouping);

        // Seed the text signal from the current value.
        {
            let initial = format_for_display(
                self.value.get(),
                decimals,
                special_text.as_ref(),
                text_from_value.as_deref(),
                min,
                false,
                &presentation,
            );
            self.text_signal.set(initial);
        }

        // Effect: when the value signal changes externally, reformat
        // the text. This also fires on startup with the initial value
        // (guaranteed by `ctx.effect`). Skipped when the field is
        // focused so typing isn't interrupted by our own round-trip
        // writes — on commit we explicitly re-sync.
        {
            let text_signal = self.text_signal.clone();
            let text_from_value = text_from_value.clone();
            let special_text = special_text.clone();
            let focused = self.focused.clone();
            let can_up = self.can_step_up.clone();
            let can_down = self.can_step_down.clone();
            let min_cap = min;
            let max_cap = max;
            let presentation = presentation.clone();
            ctx.effect(&self.value, move |new_value| {
                // Update the can-step signals any time the value
                // changes so the buttons and a11y reflect whether
                // further stepping is possible under clamp mode.
                let is_focused = focused.get();
                if wrap_mode == WrapMode::Wrap {
                    can_up.set(true);
                    can_down.set(true);
                } else {
                    can_up.set(*new_value < max_cap);
                    can_down.set(*new_value > min_cap);
                }
                if !is_focused {
                    let formatted = format_for_display(
                        *new_value,
                        decimals,
                        special_text.as_ref(),
                        text_from_value.as_deref(),
                        min_cap,
                        false,
                        &presentation,
                    );
                    if text_signal.get() != formatted {
                        text_signal.set(formatted);
                    }
                }
            });
        }

        // Effect: re-format on locale change so special_value_text
        // and custom formatters re-resolve with the new locale.
        {
            let text_signal = self.text_signal.clone();
            let text_from_value = text_from_value.clone();
            let special_text = special_text.clone();
            let value_signal = self.value.clone();
            let focused = self.focused.clone();
            let locale_signal = ctx.locale_signal();
            // A locale switch re-renders the number in place. The
            // presentation resolved at build time is stale by then, so
            // re-resolve inside the effect rather than capturing it.
            let localized = self.localized;
            let grouping = self.use_grouping;
            ctx.effect(&locale_signal, move |_| {
                let presentation = NumberPresentation::resolve(localized, grouping);
                let formatted = format_for_display(
                    value_signal.get(),
                    decimals,
                    special_text.as_ref(),
                    text_from_value.as_deref(),
                    min,
                    focused.get(),
                    &presentation,
                );
                if text_signal.get() != formatted {
                    text_signal.set(formatted);
                }
            });
        }

        // Commit helper: called on Enter and on blur. Parses the
        // current text; on success, clamps and writes the value and
        // reformats the text. On failure, reverts the text to the
        // formatted current value.
        let commit: Rc<dyn Fn(&mut EventContext)> = {
            let value_signal = self.value.clone();
            let text_signal = self.text_signal.clone();
            let value_from_text = value_from_text.clone();
            let text_from_value = text_from_value.clone();
            let special_text = special_text.clone();
            let on_value_changed = on_value_changed.clone();
            let commit_presentation = presentation.clone();
            Rc::new(move |ctx: &mut EventContext| {
                let raw = text_signal.get();
                // A user-supplied parser gets the raw text: it owns the
                // whole convention, and de-localizing first would hand it
                // a string it never agreed to read.
                let parsed: Option<T> = match value_from_text.as_deref() {
                    Some(f) => f(raw.trim()),
                    None => commit_presentation.parse::<T>(&raw),
                };
                let old = value_signal.get();
                let new_value = match parsed {
                    Some(v) => v.clamp_value(min, max),
                    None => old, // revert
                };
                let formatted = format_for_display(
                    new_value,
                    decimals,
                    special_text.as_ref(),
                    text_from_value.as_deref(),
                    min,
                    false,
                    &commit_presentation,
                );
                if text_signal.get() != formatted {
                    text_signal.set(formatted);
                }
                if approx_ne(new_value, old) {
                    value_signal.set(new_value);
                    if let Some(cb) = on_value_changed.as_ref() {
                        cb(new_value, ctx);
                    }
                }
            })
        };

        // ── Step helpers ───────────────────────────────────────────
        //
        // Two closures cover the two firing pathways:
        //
        // - `step` is called from event handlers (keyboard, wheel,
        //   button tap, a11y action) and takes an `EventContext`
        //   so it can fire the user's `on_value_changed` callback
        //   and request a frame.
        //
        // - `step_silent` is called from signal-only contexts
        //   (hold-to-repeat on the step buttons, which lives in a
        //   frame-tick effect that has no `EventContext` to hand).
        //   It mutates `value` and `text_signal` and lets the
        //   bindings on those signals trigger the redraw. The
        //   user's `on_value_changed` callback is deliberately
        //   skipped — signal observers still see every change,
        //   which is the primary notification channel.
        //
        // `can_step_up` / `can_step_down` are kept in sync by the
        // value-effect above.

        fn apply_step<T: SpinValue>(
            dir: i32,
            page: bool,
            step_type: StepType,
            wrap_mode: WrapMode,
            single_step: T,
            page_step: T,
            min: T,
            max: T,
            current: T,
        ) -> T {
            let base_step = if page { page_step } else { single_step };
            let effective = resolve_effective_step(step_type, current, base_step);
            let stepped = if dir > 0 {
                current.saturating_add(effective)
            } else {
                current.saturating_sub(effective)
            };
            if stepped < min || stepped > max {
                match wrap_mode {
                    WrapMode::Clamp => stepped.clamp_value(min, max),
                    WrapMode::Wrap => {
                        if stepped > max {
                            min
                        } else {
                            max
                        }
                    }
                }
            } else {
                stepped
            }
        }

        // Signal-only step: mutates `value` and `text_signal` and
        // returns the previous/new pair so the caller can fire any
        // extra side-effect (e.g. `on_value_changed`) after the
        // fact. When nothing changed returns `None`.
        let step_silent: Rc<dyn Fn(i32, bool) -> Option<T>> = {
            let value_signal = self.value.clone();
            let text_signal = self.text_signal.clone();
            let text_from_value = text_from_value.clone();
            let special_text = special_text.clone();
            let presentation = presentation.clone();
            Rc::new(move |dir: i32, page: bool| {
                if read_only {
                    return None;
                }
                let current = value_signal.get();
                let new_value = apply_step(
                    dir,
                    page,
                    step_type,
                    wrap_mode,
                    single_step,
                    page_step,
                    min,
                    max,
                    current,
                );
                if approx_eq(new_value, current) {
                    return None;
                }
                value_signal.set(new_value);
                let formatted = format_for_display(
                    new_value,
                    decimals,
                    special_text.as_ref(),
                    text_from_value.as_deref(),
                    min,
                    false,
                    &presentation,
                );
                if text_signal.get() != formatted {
                    text_signal.set(formatted);
                }
                Some(new_value)
            })
        };

        // Contextful step: wraps `step_silent` and fires the user
        // callback + frame request on change.
        let step: Rc<dyn Fn(i32, bool, &mut EventContext)> = {
            let step_silent = step_silent.clone();
            let on_value_changed = on_value_changed.clone();
            Rc::new(move |dir: i32, page: bool, ctx: &mut EventContext| {
                if let Some(new_value) = step_silent(dir, page) {
                    if let Some(cb) = on_value_changed.as_ref() {
                        cb(new_value, ctx);
                    }
                    ctx.request_frame();
                }
            })
        };

        // ── Inner editing field ────────────────────────────────────
        //
        // Uses `TextInputField` directly rather than the `TextInput`
        // composite — the composite's border / padding / placeholder
        // overlay is reproduced here around both the field and the
        // buttons in one shared frame, instead of framing the text
        // by itself.
        let inner_height =
            (field_dims::TEXT_FIELD_HEIGHT - 2.0 * field_dims::TEXT_FIELD_BORDER_WIDTH).max(0.0);
        let text_area_height =
            (inner_height - 2.0 * field_dims::TEXT_FIELD_PADDING_VERTICAL).max(0.0);

        let mut field = TextInputField::new(self.text_signal.clone())
            .enabled(enabled)
            .read_only(read_only)
            .placeholder(self.placeholder.clone())
            .text_height(text_area_height)
            .char_filter({
                let presentation = presentation.clone();
                move |c| presentation.accepts_char::<T>(c)
            });
        // Suffix wiring:
        //   • plain static suffix              → `.suffix(..)` (no signal)
        //   • static suffix + special_value    → reactive: hide suffix when
        //     `value == min` AND the field isn't focused, so `"Auto"` reads
        //     cleanly without a trailing unit but typing at `min` still
        //     shows the unit. Matches Qt's `QSpinBox::specialValueText`
        //     behavior.
        //   • no suffix and no special         → nothing to do.
        //
        // The reactive case uses a mutable intermediate signal
        // rather than feeding `TextInputField::suffix` a
        // derived signal directly — `ctx.effect` requires a
        // mutable source, and the field needs to drive a
        // relayout + re-measure when the suffix flips on/off.
        if !suffix_str.is_empty() {
            if self.special_value_text.is_some() {
                let suffix_live = ctx.signal(suffix_str.clone());
                let resolve = {
                    let suffix_str = suffix_str.clone();
                    let min_cap = min;
                    move |v: T, focused: bool| -> String {
                        let at_min = approx_eq(v, min_cap);
                        if at_min && !focused {
                            String::new()
                        } else {
                            suffix_str.clone()
                        }
                    }
                };
                // Seed from the current state.
                {
                    let current_focused = self.focused.get();
                    suffix_live.set(resolve(self.value.get(), current_focused));
                }
                // Observe value.
                {
                    let suffix_live = suffix_live.clone();
                    let focused = self.focused.clone();
                    let resolve = resolve.clone();
                    ctx.effect(&self.value, move |v| {
                        let is_focused = focused.get();
                        let next = resolve(*v, is_focused);
                        if suffix_live.get() != next {
                            suffix_live.set(next);
                        }
                    });
                }
                // Observe focus.
                {
                    let suffix_live = suffix_live.clone();
                    let value_signal = self.value.clone();
                    let resolve = resolve.clone();
                    ctx.effect(&self.focused, move |is_focused| {
                        let next = resolve(value_signal.get(), *is_focused);
                        if suffix_live.get() != next {
                            suffix_live.set(next);
                        }
                    });
                }
                field = field.suffix(suffix_live);
            } else {
                field = field.suffix(suffix_str.clone());
            }
        }
        // Submit on Enter: commit in-place, keep focus.
        {
            let commit = commit.clone();
            field = field.on_submit_fn(move |ctx| commit(ctx));
        }
        // Commit on blur: after the field clears its selection and
        // resets scroll.
        {
            let commit = commit.clone();
            field = field.on_blur_fn(move |ctx| commit(ctx));
        }

        // Also: when the field gains focus, show the raw editable
        // text instead of any `special_value_text`. TextInputField
        // itself doesn't know about our formatter so we bind a
        // secondary effect on the SpinBox's focus_within signal.
        {
            let focused_for_text = self.focused.clone();
            let text_signal = self.text_signal.clone();
            let value_signal = self.value.clone();
            let text_from_value = text_from_value.clone();
            let min_cap = min;
            ctx.effect(&focused_for_text, move |is_focused| {
                if *is_focused {
                    // On focus, swap any special_value_text out for
                    // the plain formatted number so the user can
                    // edit it with the keyboard.
                    let plain = format_for_display(
                        value_signal.get(),
                        decimals,
                        None,
                        text_from_value.as_deref(),
                        min_cap,
                        true,
                        &presentation,
                    );
                    if text_signal.get() != plain {
                        text_signal.set(plain);
                    }
                }
            });
        }

        let field_id = ctx.add(field);
        self.field_id = Some(field_id);

        // Wrap field in vertical padding so it aligns inside the frame.
        // (Horizontal Expand is owned by the active SpinBoxStyle so a
        // custom recipe can re-arrange the row.)
        let padded_field_id = ctx.add(
            Padding::new(
                field_dims::TEXT_FIELD_PADDING_VERTICAL,
                0.0,
                field_dims::TEXT_FIELD_PADDING_VERTICAL,
                0.0,
            )
            .child_id(field_id),
        );

        // ── Step buttons ───────────────────────────────────────────
        let (step_up_id, step_down_id) = if self.button_layout != ButtonLayout::Hidden {
            let (u, d) = build_step_buttons(
                ctx,
                &step,
                &step_silent,
                self.can_step_up.clone(),
                self.can_step_down.clone(),
                enabled && !read_only,
                field_dims::TEXT_FIELD_HEIGHT,
                field_dims::TEXT_FIELD_CORNER_RADIUS,
            );
            (Some(u), Some(d))
        } else {
            (None, None)
        };

        // ── Delegate visual chrome (row layout + divider + bordered
        // surface) to the active SpinBoxStyle.
        let style =
            crate::styles::recipe_spin_box_style::resolve_spin_box_style(&self.style_override, ctx);
        // Derive the disabled state from the arena rather than from the
        // build-time `enabled` snapshot above, so a bound `Signal<bool>`
        // (or a disabled *ancestor*) re-tints the chrome with no rebuild.
        let is_disabled = ctx.effective_enabled_signal(self_id).map(|on| !*on);
        let cfg = teksilo_core::styles::SpinBoxStyleConfig {
            field: padded_field_id,
            step_up: step_up_id,
            step_down: step_down_id,
            layout: self.button_layout,
            is_focused: self.focused.clone(),
            is_disabled,
        };
        let zstack_id = style.make_body(&cfg, ctx);
        let _ = focus_ring_width;
        let _ = field_border_width;

        // Resolve the width policy into a concrete pixel cap (or
        // `None` for `Fill`). Char-mode measurement uses the app-
        // wide `SharedTypesetter` — same backend the field paints
        // with — so the result tracks runtime theme switches and
        // HiDPI scale changes. `'0'` is the reference digit since
        // Inter and most UI sans-serifs ship tabular-figure
        // numerals; the suffix is measured separately because it
        // may have different glyph advances (e.g. `" %"`).
        let min_width = match self.button_layout {
            ButtonLayout::Stacked => MIN_WIDTH_WITH_BUTTONS,
            ButtonLayout::Hidden => MIN_WIDTH_NO_BUTTONS,
        };
        let pixel_cap: Option<f32> = match self.width_policy {
            WidthPolicy::Fill => None,
            WidthPolicy::Pixels(px) => Some(px.max(min_width)),
            WidthPolicy::Chars(chars) => {
                let style = &theme.typography.body;
                let sample: String = "0".repeat(chars as usize);
                let digits_w = measure_width_px(ctx, &sample, style);
                let suffix_w = if suffix_str.is_empty() {
                    0.0
                } else {
                    measure_width_px(ctx, &suffix_str, style)
                };
                let button_chrome = match self.button_layout {
                    // 18 dp button + 4 dp divider padding + 1 dp divider
                    ButtonLayout::Stacked => 18.0 + 4.0 + 1.0,
                    ButtonLayout::Hidden => 0.0,
                };
                // 2 dp slack so the caret and a trailing zero never
                // paint flush against the right edge.
                let chrome = field_dims::TEXT_FIELD_PADDING_HORIZONTAL * 2.0 + button_chrome + 2.0;
                Some((digits_w + suffix_w + chrome).max(min_width))
            }
        };

        // Size envelope:
        //   MinSize  → enforce a floor so the field and buttons
        //              still fit even when a narrow parent would
        //              otherwise squash the widget.
        //   The horizontal cap (when `pixel_cap` is `Some`) is
        //   applied by `SpinBox::size_that_fits` narrowing the
        //   proposal, NOT by wrapping in `MaxSize`. `MaxSize`
        //   clips its children, which would truncate the outer
        //   half of the focus-state border stroke against the
        //   widget's own shape quad (visible as a ring clipped on
        //   all four sides).
        let sized_id =
            ctx.add(MinSize::new(min_width, field_dims::TEXT_FIELD_HEIGHT).child_id(zstack_id));
        // Stash the resolved cap + floor on `self` for
        // `size_that_fits` to read at layout time.
        self.pixel_cap = pixel_cap;
        self.min_width = min_width;

        // ── Root: attach key + wheel handlers on the outer sized id ─
        //
        // Bubble-phase `on_key` catches Up / Down / PageUp / PageDown
        // after the `TextInputField` declines them (the field's
        // keyboard dispatch falls through to `_ =>` for arrow keys,
        // returning `Ignored` so the bubble loop continues up).
        let root_id = sized_id;
        self.root_child_id = Some(root_id);

        let step_for_key = step.clone();
        let step_for_wheel = step.clone();
        let value_for_a11y = self.value.clone();
        let field_id_for_access = field_id;

        let handlers = HandlerSet::new()
            // The SpinBox is not itself focusable — focus lands inside the
            // inner TextInputField. `focus_within` writes `true` whenever
            // any descendant (in practice, the field) holds focus, driving
            // the unified outer focus ring + the suffix / text-formatting
            // effects that previously read an `interaction_signal` piped
            // out of the field.
            .focus_within(self.focused.clone())
            // Preview-pass dispatch — claims ArrowUp/ArrowDown/PageUp/PageDown
            // for stepping BEFORE the focused TextInputField sees them. The
            // bubble-pass `on_key` previously relied on the field happening
            // not to bind arrow keys; preview makes the contract explicit so
            // future field changes (multiline caret motion, etc.) cannot
            // silently break stepping. Non-arrow keys return `Ignored` and
            // fall through to the field for normal text input.
            .on_key_preview(move |event, ctx| {
                if !enabled || read_only {
                    return EventResponse::Ignored;
                }
                let WidgetEvent::KeyDown { key, .. } = event else {
                    return EventResponse::Ignored;
                };
                match key {
                    Key::ArrowUp => {
                        (step_for_key)(1, false, ctx);
                        EventResponse::Handled
                    }
                    Key::ArrowDown => {
                        (step_for_key)(-1, false, ctx);
                        EventResponse::Handled
                    }
                    Key::PageUp => {
                        (step_for_key)(1, true, ctx);
                        EventResponse::Handled
                    }
                    Key::PageDown => {
                        (step_for_key)(-1, true, ctx);
                        EventResponse::Handled
                    }
                    _ => EventResponse::Ignored,
                }
            })
            .on_scroll({
                let focused = self.focused.clone();
                move |event, ctx| {
                    if !enabled || read_only || wheel_mode == WheelMode::Disabled {
                        return EventResponse::Ignored;
                    }
                    // `Focused` wheel mode only fires when the
                    // inner field currently holds focus. `Hover` is
                    // the natural fallthrough — scroll events reach
                    // the widget only when the pointer is over it.
                    if wheel_mode == WheelMode::Focused && !focused.get() {
                        return EventResponse::Ignored;
                    }
                    let WidgetEvent::Scroll { delta, .. } = event else {
                        return EventResponse::Ignored;
                    };
                    let y = match delta {
                        ScrollDelta::Lines { y, .. } => *y,
                        ScrollDelta::Pixels { y, .. } => *y,
                    };
                    if y == 0.0 {
                        return EventResponse::Ignored;
                    }
                    // Teksilo's `ScrollDelta` is a *scroll offset* delta, not
                    // a raw wheel reading: `translate_mouse_wheel` negates
                    // winit's natural sign so that **positive y scrolls
                    // down** (the offset grows, content moves up) — which is
                    // what `ScrollArea` and every data view add straight to
                    // their scroll position. So a wheel-down notch arrives
                    // as `y > 0` and must *decrement*, matching every other
                    // stepper on the platform.
                    let dir = if y > 0.0 { -1 } else { 1 };
                    (step_for_wheel)(dir, false, ctx);
                    EventResponse::Handled
                }
            })
            .on_access_action(move |action, ctx| {
                use teksilo_core::accesskit::Action;
                match action {
                    Action::Increment => {
                        (step.clone())(1, false, ctx);
                        EventResponse::Handled
                    }
                    Action::Decrement => {
                        (step.clone())(-1, false, ctx);
                        EventResponse::Handled
                    }
                    Action::Focus => {
                        ctx.request_focus(field_id_for_access);
                        EventResponse::Handled
                    }
                    _ => EventResponse::Ignored,
                }
            });
        // Bind `value` so the SpinButton a11y node refreshes on
        // every change (numeric_value setter reads it live).
        let self_id = ctx.self_id();
        value_for_a11y.bind_to(
            self_id,
            ctx.binding_registry(),
            teksilo_core::binding::BindingLevel::AccessibilityOnly,
        );

        ctx.apply_self_handlers(handlers);

        // ── Tooltip attachment ─────────────────────────────────────
        if let Some(content) = self.composite_tooltip_content.take() {
            let delay = ctx.theme().motion.tooltip_delay_heavy;
            crate::tooltip::attach_composite_tooltip_boxed(ctx, root_id, content, delay);
        } else if let Some(source) = self.rich_tooltip_source.clone() {
            let delay = ctx.theme().motion.tooltip_delay;
            crate::tooltip::attach_rich_tooltip_source(ctx, root_id, source, delay);
        } else if let Some(text) = self.tooltip_text.clone() {
            let delay = ctx.theme().motion.tooltip_delay;
            crate::tooltip::attach_plain_tooltip(ctx, root_id, text, delay);
        }

        vec![root_id]
    }

    fn layout_response(
        &self,
        proposal: SizeProposal,
        ctx: &LayoutContext,
    ) -> teksilo_core::widget::LayoutResponse {
        // Narrow the parent's proposal by `pixel_cap` (if any)
        // before delegating. This enforces the `.width(...)` /
        // `.width_chars(...)` caps without wrapping the subtree
        // in a clipping `MaxSize` — the focus-state border stroke
        // can then extend 1 dp outside the visual bounds
        // (Int UI focus thickening) without being chopped off
        // against the shape quad.
        // `pixel_cap` / `min_width` are measured at 1.0 scale in `build()`. The
        // inner field grows its text by `ctx.text_scale`, so the cap must grow
        // too or the scaled digits clip against an un-grown width cap.
        let scale = ctx.text_scale;
        let pixel_cap = self.pixel_cap.map(|c| c * scale);
        let min_width = self.min_width * scale;
        let effective_proposal = SizeProposal {
            width: match (proposal.width, pixel_cap) {
                (Some(w), Some(cap)) => Some(w.min(cap).max(min_width)),
                (None, Some(cap)) => Some(cap.max(min_width)),
                (w, None) => w,
            },
            height: proposal.height,
        };
        let child_size = self
            .root_child_id
            .and_then(|id| ctx.child_size(id, effective_proposal))
            .unwrap_or_else(|| effective_proposal.resolve(0.0, 0.0));
        // Claim the (cap-narrowed) proposal width on the cross axis — the
        // inner `ZStack` queries its children with `SizeProposal::unspecified`,
        // so the offered width never reaches the inner `HStack` during
        // measurement; without this clamp the chain returns just
        // `MinSize`'s floor and the SpinBox collapses regardless of
        // `WidthPolicy::Fill` or `Pixels`/`Chars` caps.
        let w = match effective_proposal.width {
            Some(pw) => pw.max(child_size.width),
            None => child_size.width,
        };
        Size::new(w, child_size.height).into()
    }

    fn place_children(
        &self,
        bounds: Rect,
        _proposal: SizeProposal,
        children: &mut [WidgetPlacement],
        _ctx: &LayoutContext,
    ) {
        if let Some(p) = children.first_mut() {
            p.origin = Point::new(bounds.x, bounds.y);
            p.size = bounds.size();
        }
    }

    fn children(&self) -> Vec<WidgetId> {
        self.root_child_id.into_iter().collect()
    }

    fn accessibility(&self, builder: &mut AccessNodeBuilder) {
        use teksilo_core::accesskit::{Action, Role};

        builder.set_role(Role::SpinButton);
        if let Some(ref label) = self.label {
            builder.set_name(label.resolve_now());
        }
        builder.set_numeric_value(self.value.get().to_f64());
        builder.set_min_numeric_value(self.min.to_f64());
        builder.set_max_numeric_value(self.max.to_f64());
        builder.set_numeric_value_step(self.single_step.to_f64());
        if let Some(page) = self.page_step {
            builder.set_numeric_value_jump(page.to_f64());
        } else {
            builder.set_numeric_value_jump(self.single_step.saturating_mul_u32(10).to_f64());
        }
        // String-valued representation so screen readers can read
        // out the suffix / special-value text when applicable. The
        // suffix is elided when `special_value_text` has kicked in
        // (value == min), matching the visual rendering.
        let value = self.value.get();
        let using_special = self.special_value_text.is_some() && approx_eq(value, self.min);
        let display = format_for_display(
            value,
            self.decimals,
            self.special_value_text.as_ref(),
            self.text_from_value.as_deref(),
            self.min,
            false,
            &NumberPresentation::resolve(self.localized, self.use_grouping),
        );
        let full = if !self.suffix.is_empty() && !using_special {
            format!("{}{}", display, self.suffix)
        } else {
            display
        };
        builder.set_value(full);

        // Framework a11y walker sets `set_disabled` from arena state.
        if self.read_only {
            builder.set_read_only();
        }
        builder.add_action(Action::Increment);
        builder.add_action(Action::Decrement);
        builder.add_action(Action::SetValue);
        builder.add_action(Action::Focus);
    }
}

// ── Helpers ────────────────────────────────────────────────────────

/// Build the stacked up/down step-button column. Returns its root
/// `WidgetId` for the caller to drop into the HStack.
///
/// `step` (with `EventContext`) is called on the initial tap;
/// `step_silent` is called from the hold-to-repeat timer, which
/// runs inside a frame-tick effect with no `EventContext` to hand.
fn build_step_buttons<T: SpinValue>(
    ctx: &mut BuildContext,
    step: &Rc<dyn Fn(i32, bool, &mut EventContext)>,
    step_silent: &Rc<dyn Fn(i32, bool) -> Option<T>>,
    can_up: Signal<bool>,
    can_down: Signal<bool>,
    enabled: bool,
    frame_height: f32,
    corner_radius: f32,
) -> (WidgetId, WidgetId) {
    // Each button is half of the field's inner height (minus the
    // borders and a 1 px gutter between the two).
    let button_height = ((frame_height - 2.0) * 0.5).max(8.0);
    let button_width = 18.0;

    let up_icon = chevron_up_icon(8.0);
    let down_icon = chevron_down_icon(8.0);

    // Derived enabled signals: OR with the caller-wide `enabled`.
    let up_enabled = if enabled { can_up } else { Signal::new(false) };
    let down_enabled = if enabled {
        can_down
    } else {
        Signal::new(false)
    };

    let step_for_up_tap = step.clone();
    let silent_for_up_auto = step_silent.clone();
    let up_button = StepButton::new(up_icon, up_enabled, move |ctx| {
        (step_for_up_tap)(1, false, ctx);
    })
    .on_auto_repeat(move || {
        (silent_for_up_auto)(1, false);
    })
    .size(button_width, button_height)
    .corner_radius(CornerRadius {
        top_left: 0.0,
        top_right: corner_radius,
        bottom_left: 0.0,
        bottom_right: 0.0,
    });

    let step_for_down_tap = step.clone();
    let silent_for_down_auto = step_silent.clone();
    let down_button = StepButton::new(down_icon, down_enabled, move |ctx| {
        (step_for_down_tap)(-1, false, ctx);
    })
    .on_auto_repeat(move || {
        (silent_for_down_auto)(-1, false);
    })
    .size(button_width, button_height)
    .corner_radius(CornerRadius {
        top_left: 0.0,
        top_right: 0.0,
        bottom_left: 0.0,
        bottom_right: corner_radius,
    });

    (ctx.add(up_button), ctx.add(down_button))
}

/// Small chevron-up icon at `size` px. Mirrors the shape of the
/// `chevron_down` icon provided by `IconWidget`.
fn chevron_up_icon(size: f32) -> IconWidget {
    let mut path = Path::new();
    let s = size;
    path.move_to(Point::new(s * 0.25, s * 0.65));
    path.line_to(Point::new(s * 0.5, s * 0.35));
    path.line_to(Point::new(s * 0.75, s * 0.65));
    IconWidget::from_path(path, size)
}

fn chevron_down_icon(size: f32) -> IconWidget {
    let mut path = Path::new();
    let s = size;
    path.move_to(Point::new(s * 0.25, s * 0.35));
    path.line_to(Point::new(s * 0.5, s * 0.65));
    path.line_to(Point::new(s * 0.75, s * 0.35));
    IconWidget::from_path(path, size)
}

/// How the number itself is rendered and read back: the locale's
/// conventions, or the C locale.
///
/// Resolved once per `build()` and threaded through the format and
/// parse paths together, so the two can never disagree about which
/// separator this field is using — the same single-source discipline
/// `DateEdit` gets from its one `ParsedPattern`.
#[derive(Clone)]
pub(crate) struct NumberPresentation {
    symbols: Option<Rc<teksilo_i18n::NumberSymbols>>,
    grouping: bool,
}

impl NumberPresentation {
    /// Resolve against the active locale. `localized == false` yields a
    /// presentation that is the identity in both directions.
    pub(crate) fn resolve(localized: bool, grouping: bool) -> Self {
        Self {
            symbols: localized.then(teksilo_i18n::NumberSymbols::current),
            grouping,
        }
    }

    /// C-locale digits in, display string out.
    fn render(&self, plain: String) -> String {
        match &self.symbols {
            Some(sym) => sym.localize(&plain, self.grouping),
            None => plain,
        }
    }

    /// Display string in, C-locale digits out. `None` when the text
    /// cannot be a number in this locale.
    fn read(&self, raw: &str) -> Option<String> {
        match &self.symbols {
            Some(sym) => sym.delocalize(raw),
            None => Some(raw.trim().to_string()),
        }
    }

    /// Parse user input into a value, going through the locale first.
    fn parse<T: SpinValue>(&self, raw: &str) -> Option<T> {
        T::parse(&self.read(raw)?)
    }

    /// Per-character input filter. Widens the type's own filter with the
    /// characters this locale writes numbers with, so a French user can
    /// type `,` and an Egyptian user can type `٫` or Arabic-Indic
    /// digits — while the ASCII forms keep working everywhere, because
    /// people type on the keyboard they have.
    fn accepts_char<T: SpinValue>(&self, c: char) -> bool {
        if T::is_valid_input_char(c) {
            return true;
        }
        let Some(sym) = &self.symbols else {
            return false;
        };
        if sym.has_non_ascii_digits() && sym.delocalize(&c.to_string()).is_some() {
            return true;
        }
        // The group separator is only typeable when this field shows
        // groups; otherwise it is noise the user cannot have meant.
        [
            Some(sym.decimal_separator()),
            Some(sym.minus_sign()),
            Some(sym.plus_sign()),
            self.grouping.then(|| sym.group_separator()),
        ]
        .into_iter()
        .flatten()
        .any(|sep| sep.chars().any(|sc| sc == c))
    }
}

/// Format `value` for display, honoring `special_value_text` when
/// applicable and deferring to a user-supplied formatter when set.
///
/// `force_plain` bypasses `special_value_text` even when the value
/// equals `min` — used when the field is focused so the user can
/// edit the number instead of a placeholder string.
///
/// A user-supplied `custom` formatter owns the whole string and is
/// **not** localized afterwards: it already returns exactly what the
/// caller wants shown, and re-punctuating it would corrupt formats the
/// caller composed deliberately.
fn format_for_display<T: SpinValue>(
    value: T,
    decimals: u8,
    special: Option<&LocalizedString>,
    custom: Option<&dyn Fn(T) -> LocalizedString>,
    min: T,
    force_plain: bool,
    presentation: &NumberPresentation,
) -> String {
    if !force_plain
        && let Some(special_text) = special
        && approx_eq(value, min)
    {
        return special_text.resolve_now();
    }
    match custom {
        Some(f) => f(value).resolve_now(),
        None => presentation.render(value.format(decimals)),
    }
}

/// Decide the effective step for an [`Adaptive`](StepType::Adaptive)
/// step type given the current value. For a value ∈ [10^n,
/// 10^(n+1)) the effective step is 10^n; inside [0, 1) the
/// step stays at `base_step` to avoid vanishing.
fn resolve_effective_step<T: SpinValue>(step_type: StepType, current: T, base_step: T) -> T {
    if step_type == StepType::Fixed {
        return base_step;
    }
    let abs = current.to_f64().abs();
    if abs < 10.0 {
        return base_step;
    }
    let pow = abs.log10().floor();
    let magnitude = 10f64.powf(pow);
    let adaptive = T::from_f64_saturating(magnitude);
    // Fall back to the user's base step if adaptive truncates to
    // zero (possible for integer types when pow < 0).
    let adaptive_f = adaptive.to_f64();
    if adaptive_f.abs() < 1e-12 {
        base_step
    } else {
        adaptive
    }
}

/// Approximate equality. Integer types compare bit-exactly;
/// floats tolerate sub-unit-in-last-place jitter. Used throughout
/// to suppress redundant signal sets.
fn approx_eq<T: SpinValue>(a: T, b: T) -> bool {
    if T::is_integer() {
        a.to_f64() == b.to_f64()
    } else {
        // Relative epsilon scaled by value magnitude so both near-zero
        // and large-value comparisons behave.
        let af = a.to_f64();
        let bf = b.to_f64();
        let scale = af.abs().max(bf.abs()).max(1.0);
        (af - bf).abs() <= scale * 1e-9
    }
}

fn approx_ne<T: SpinValue>(a: T, b: T) -> bool {
    !approx_eq(a, b)
}

/// Measure the advance width of `text` in logical pixels using the
/// app-wide `SharedTypesetter` (the same backend the field paints
/// with). Falls back to a rough heuristic when no typesetter is
/// installed (headless tests) so the caller still gets a non-zero
/// width and the `MaxSize` cap behaves reasonably.
fn measure_width_px(ctx: &mut BuildContext, text: &str, style: &TextStyle) -> f32 {
    if text.is_empty() {
        return 0.0;
    }
    if let Some(ts) = ctx.app_state::<SharedTypesetter>() {
        let backend = ts.as_text_backend();
        let layout = backend.borrow_mut().layout_single_line(text, style, None);
        return layout.width;
    }
    // Headless fallback: ~0.55 × font size per ASCII char is a
    // close approximation for Inter Regular at body weight.
    text.chars().count() as f32 * style.size * 0.55
}