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
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

//! Button — a labelled, activatable action trigger.
//!
//! `Button` is the primary action surface in Teksilo. It renders a text
//! label (optionally with a leading, trailing, top, or bottom icon), fires
//! a closure on click / Space / Enter / AT click, and advertises seven
//! design-language variants via [`ButtonVariant`]. Chrome (fill, border,
//! focus ring, padding) is delegated to the active [`ButtonStyle`]; the
//! default `RecipeButtonStyle` implements the Int UI token ladder.
//!
//! ## When to use
//!
//! - Primary action: `.variant(ButtonVariant::Filled)` — one per context.
//! - Secondary / cancel: default `ButtonVariant::Plain`.
//! - Danger: `ButtonVariant::Destructive` (IntUI maps this to Filled).
//! - Text-only link: `ButtonVariant::Link` / `ButtonVariant::Ghost`.
//!
//! ## Accessibility
//!
//! Announces as `Role::Button` with the resolved label as its AT name.
//! Keyboard: Space / Enter activate; the lone-KeyUp guard prevents spurious
//! re-activation when a shortcut consumes the KeyDown and returns focus here.
//!
//! ```rust
//! # use teksilo_widgets::{Button, ButtonVariant};
//! # use teksilo_i18n::lit;
//! # use teksilo_core::Intent;
//! let _btn = Button::new(lit!("Save"))
//!     .variant(ButtonVariant::Filled)
//!     .on_activate_fn(|ctx| ctx.send_intent(Intent::new("app.save")));
//! ```

use std::rc::Rc;
use teksilo_i18n::lit;

use teksilo_canvas::{Rect, SizeProposal};
use teksilo_core::accessibility::AccessNodeBuilder;
use teksilo_core::build_context::BuildContext;
use teksilo_core::event::{EventResponse, Key, WidgetEvent};
use teksilo_core::signal::{Prop, Signal};
use teksilo_core::styles::{ButtonStyle, ButtonStyleConfig, SharedButtonStyle};
use teksilo_core::widget::{CursorIcon, EventContext, LayoutContext, Widget, WidgetPlacement};
use teksilo_core::widget_builder::HandlerSet;
use teksilo_core::widget_id::WidgetId;
use teksilo_tokens::TextRole;

use crate::primitives::icon_widget::IconWidget;
use crate::primitives::{HStack, TextWidget, VStack};

/// Closed enum naming the design-language variants of `Button`. See
/// [`teksilo_core::styles::ButtonVariant`] for the canonical definition.
///
/// Int UI does **not** ship filled red "destructive" buttons —
/// destructive actions in IntelliJ are plain buttons in confirmation
/// dialogs where the title/body carry the warning. The IntUI default
/// `RecipeButtonStyle` collapses `Destructive → Filled`, `Tinted /
/// Outlined → Plain`, and `Link → Ghost` accordingly. Other design
/// languages (Material 3, macOS) honour the variants distinctly.
pub use teksilo_core::styles::ButtonVariant;
use teksilo_i18n::LocalizedString;

/// Internal interaction state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InteractionState {
    Idle,
    Hovered,
    Pressed,
    Focused,
    Disabled,
}

/// Build the interaction handler set shared by every activatable button
/// (`Button`, `IconButton`, `CommandLinkButton`, and any future sibling).
///
/// Centralizes the parts that MUST stay identical across the family and
/// historically drifted when copy-pasted:
/// - hover/focus state tracking,
/// - keyboard `Space`/`Enter` activation with the **lone-KeyUp guard**
///   (a `KeyUp` with no preceding `KeyDown` — e.g. a shortcut consumed
///   the `KeyDown` and focus returned here — must NOT activate),
/// - the AT `Click` action.
///
/// `on_activate` runs on tap, keyboard activation, and AT click. Callers
/// bundle their command action (and any extra side effect, e.g.
/// `IconButton`'s toggle flip) into this single closure so the guard
/// gates all activation paths uniformly. `focusable` is the node's
/// focusability (`Button` is always focusable; `IconButton` exposes it).
pub(crate) fn build_interaction_handlers(
    interaction: Signal<InteractionState>,
    on_activate: Rc<dyn Fn(&mut EventContext)>,
    focusable: bool,
) -> HandlerSet {
    let act_tap = on_activate.clone();
    let act_key = on_activate.clone();
    let act_access = on_activate;
    HandlerSet::new()
        .on_tap({
            let interaction = interaction.clone();
            move |_pos: &teksilo_core::TapEvent, ctx: &mut EventContext| {
                act_tap(ctx);
                interaction.set(InteractionState::Hovered);
            }
        })
        .on_hover({
            let interaction = interaction.clone();
            move |entered: bool, _ctx: &mut EventContext| {
                interaction.set(if entered {
                    InteractionState::Hovered
                } else {
                    InteractionState::Idle
                });
            }
        })
        // Pointer-down press state. The family PROVIDES the Pressed state
        // on mouse-down so the *theme* decides whether to render it: Int
        // UI regular buttons have no pressed state (their recipe resolves
        // pressed → hover), while Int UI icon buttons and other themes do.
        // Returns `Ignored` so the event still reaches the tap recognizer
        // and `on_tap` activation fires. Reverts to Hovered on release
        // only if still Pressed — a drag-out release already went to Idle
        // via `on_hover(false)`, so the guard leaves it there.
        .on_pointer_event({
            let interaction = interaction.clone();
            move |event: &WidgetEvent, _ctx: &mut EventContext| -> EventResponse {
                match event {
                    WidgetEvent::PointerDown { .. } => {
                        interaction.set(InteractionState::Pressed);
                    }
                    WidgetEvent::PointerUp { .. }
                        if interaction.get() == InteractionState::Pressed =>
                    {
                        interaction.set(InteractionState::Hovered);
                    }
                    _ => {}
                }
                EventResponse::Ignored
            }
        })
        .on_key({
            let interaction = interaction.clone();
            move |event: &WidgetEvent, ctx: &mut EventContext| -> EventResponse {
                match event {
                    WidgetEvent::KeyDown {
                        key: Key::Space | Key::Enter,
                        ..
                    } => {
                        interaction.set(InteractionState::Pressed);
                        EventResponse::Handled
                    }
                    WidgetEvent::KeyUp {
                        key: Key::Space | Key::Enter,
                        ..
                    } => {
                        // Lone-KeyUp guard: only activate if we saw the
                        // matching KeyDown (state is Pressed).
                        if interaction.get() != InteractionState::Pressed {
                            return EventResponse::Ignored;
                        }
                        act_key(ctx);
                        interaction.set(InteractionState::Focused);
                        EventResponse::Handled
                    }
                    _ => EventResponse::Ignored,
                }
            }
        })
        .on_focus({
            let interaction = interaction.clone();
            move |gained: bool, _ctx: &mut EventContext| {
                if gained {
                    if interaction.get() == InteractionState::Idle {
                        interaction.set(InteractionState::Focused);
                    }
                } else {
                    interaction.set(InteractionState::Idle);
                }
            }
        })
        .on_access_action(
            move |action: teksilo_core::accesskit::Action,
                  ctx: &mut EventContext|
                  -> EventResponse {
                if action == teksilo_core::accesskit::Action::Click {
                    act_access(ctx);
                    EventResponse::Handled
                } else {
                    EventResponse::Ignored
                }
            },
        )
        .focusable(focusable)
        .cursor(CursorIcon::Pointer)
}

/// Where an optional icon is placed relative to the button label.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum IconLocation {
    /// No icon (default).
    #[default]
    None,
    /// Icon only, no label.
    IconOnly,
    /// Icon to the left of the label (default).
    Leading,
    /// Icon to the right of the label.
    Trailing,
    /// Icon above the label.
    Top,
    /// Icon below the label.
    Bottom,
}

/// Type-erased activation closure. Stored as `Box<dyn Fn>` so the
/// same button type works for any handler — typed intent send,
/// direct side effect, window mutation, etc.
type CommandFactory = Box<dyn Fn(&mut EventContext)>;

/// A labelled action trigger; use [`Button::new`] and chain builder methods.
pub struct Button {
    /// Button label as a `Prop<String>`. `new(tr!(...))` stores a
    /// `Prop::Bound` (locale-reactive) when an i18n manager is installed,
    /// falling back to `Prop::Static` for `lit!(...)` or no manager;
    /// `label(signal)` overrides with a caller-supplied source. Either
    /// way the inner `TextWidget` re-renders reactively without rebuilding
    /// the Button. The accessibility node's `set_name` reads the current
    /// value via `Prop::get()`, keeping AT in sync with bound updates.
    label: teksilo_core::signal::Prop<String>,
    /// Tier-1 design-language variant hint (Filled, Plain, Ghost, …).
    /// The active [`ButtonStyle`] decides what to do with it.
    variant: ButtonVariant,
    /// Optional per-call override for the active [`ButtonStyle`]. When
    /// `None`, falls through to the theme slot or the
    /// built-in [`crate::styles::RecipeButtonStyle`] default.
    style_override: Option<SharedButtonStyle>,
    action: Option<CommandFactory>,
    /// Enabled state, static or reactive. Forwarded into the arena via
    /// `ctx.enabled_when(self_id, self.enabled.clone())` at build time;
    /// not kept as a runtime snapshot. After `build()` the arena's
    /// `enabled_state` is the single source of truth — leaves resolve
    /// colors via `PaintContext::effective_enabled`, events are gated
    /// by `arena.is_enabled()`, the a11y walker reads it for
    /// `set_disabled()`.
    enabled: Prop<bool>,
    icon: Option<IconWidget>,
    icon_location: IconLocation,
    /// Leave the icon's own colour alone instead of tinting it to the label's.
    /// See [`Button::icon_keeps_color`].
    icon_keeps_color: bool,
    tooltip_text: Option<LocalizedString>,
    /// Optional rich tooltip source (registry key or inline content).
    /// Mutually exclusive with `tooltip_text` and `composite_tooltip_content`
    /// — every tooltip setter clears the other two so last-call wins.
    rich_tooltip_source: Option<crate::tooltip::RichTooltipSource>,
    /// Optional composite tooltip body. Hosts an arbitrary widget
    /// tree (charts, grids, conditional rows). Mutually exclusive
    /// with `tooltip_text` and `rich_tooltip_source` per the
    /// last-call-wins matrix.
    composite_tooltip_content: Option<Box<dyn teksilo_core::widget::Widget>>,
    /// Optional `has_popup` hint used when this button acts as a
    /// disclosure trigger for a popup (menu, dialog, listbox, etc.).
    /// Surfaced via `set_has_popup` in `accessibility()`.
    has_popup: Option<teksilo_core::accesskit::HasPopup>,
    /// Arbitrary widget rendered to the leading edge of the button's
    /// content (left in LTR, right in RTL). Composes with `.icon(...)`:
    /// the order is `[leading_slot, icon+label, trailing_slot]`. Slot
    /// widgets paint and report a11y on their own — Button does not
    /// retint them and does not auto-suppress their AT roles. Apps
    /// whose slot widgets would otherwise pollute the AT tree
    /// (e.g. ColorSwatch with `Role::ColorWell`) should pass
    /// `widget.access_hidden(true)` so the Button's
    /// `Role::Button` stays the single declared role.
    leading: Option<Box<dyn Widget>>,
    /// Same shape as `leading`, rendered to the trailing edge.
    trailing: Option<Box<dyn Widget>>,
    /// Optional signal reporting whether the button's popup is
    /// currently visible. Surfaced via `set_expanded` in
    /// `accessibility()`. Used alongside `has_popup` for the
    /// standard ARIA disclosure pattern.
    expanded_signal: Option<Prop<bool>>,
    /// Optional caller-supplied interaction signal. When set, `build()`
    /// uses this signal instead of allocating its own — letting an
    /// external widget (e.g. `PopoverButton`'s disclosure caret)
    /// observe hover / press / focus / disabled state and match the
    /// label's color exactly. See [`Button::share_interaction`].
    shared_interaction: Option<Signal<InteractionState>>,
    /// Optional caller-supplied label/icon color override. When `Some`,
    /// both the label text and any icon are bound to this `ColorProp`
    /// regardless of `style` / interaction state — the auto-derived
    /// cascade is replaced. Used by chrome that has to match a host's
    /// enforced text role (e.g. tab-bar overflow dropdown trigger
    /// inheriting `idle_text_role`). See [`Button::text_role`].
    text_role_override: Option<teksilo_core::color_prop::ColorProp>,
    /// Optional per-call override for the label's text style (font, size,
    /// weight). When `Some`, applied to the inner label `TextWidget` via
    /// its `.style(...)`; when `None`, the `TextWidget` default is used.
    /// Accepts a `TextStyleRole`, a `TextStyle`, or a `Signal` of either
    /// (anything `Into<TextStyleProp>`). See [`Button::text_style`].
    label_style: Option<teksilo_core::color_prop::TextStyleProp>,
    /// Interaction state signal — set during build().
    interaction: Signal<InteractionState>,
    /// Root child ID — set during build().
    root_child_id: Option<WidgetId>,
}

impl Button {
    /// Construct a button from a `LocalizedString` label. The label may
    /// come from `tr!(...)` (translated) or `lit!(...)`
    /// (explicit non-translated). When an `I18nManager` is installed, a
    /// `tr!(...)` label becomes a `Prop::Bound` that observes the locale
    /// version signal, so the inner `TextWidget` re-renders on a locale
    /// switch without rebuilding the Button — matching `TextWidget::new`.
    /// `lit!(...)` and the no-manager case resolve to a static `String`.
    pub fn new(label: impl Into<LocalizedString>) -> Self {
        let ls: LocalizedString = label.into();
        Self {
            // `Prop::from(LocalizedString)` yields `Prop::Bound` (reactive)
            // when a manager is installed, `Prop::Static` otherwise — the
            // same conversion `TextWidget::new` uses. A locale change then
            // updates the label live; without this it stayed frozen because
            // `set_locale` marks the tree dirty (relayout/repaint) but does
            // NOT rebuild composites.
            label: teksilo_core::signal::Prop::from(ls),
            // Int UI default is a Plain (non-primary) button; the caller
            // opts into `ButtonVariant::Filled` for the one primary action.
            variant: ButtonVariant::Plain,
            style_override: None,
            action: None,
            enabled: Prop::Static(true),
            icon: None,
            icon_location: IconLocation::None,
            icon_keeps_color: false,
            tooltip_text: None,
            rich_tooltip_source: None,
            composite_tooltip_content: None,
            has_popup: None,
            expanded_signal: None,
            shared_interaction: None,
            text_role_override: None,
            label_style: None,
            leading: None,
            trailing: None,
            interaction: Signal::new(InteractionState::Idle),
            root_child_id: None,
        }
    }

    /// Returns the configured visual variant. Used by wrappers like
    /// [`PopoverButton`](crate::popover_widget::PopoverButton) that
    /// derive their own chrome colors from the same recipe-resolution
    /// path the inner Button uses.
    pub fn current_variant(&self) -> ButtonVariant {
        self.variant
    }

    /// Bind the button's internal interaction state to a caller-owned
    /// `Signal<InteractionState>` instead of letting `build()` allocate
    /// its own. Used by wrapper widgets like
    /// [`PopoverButton`](crate::popover_widget::PopoverButton) whose
    /// disclosure caret needs to match the label's color across hover
    /// / press / focus / disabled states.
    ///
    /// The provided signal is reset to `Disabled` when `enabled == false`
    /// during `build()` so the shared signal honors the button's
    /// enabled state without the caller having to seed it.
    pub fn share_interaction(mut self, signal: Signal<InteractionState>) -> Self {
        self.shared_interaction = Some(signal);
        self
    }

    /// Set the Tier-1 design-language variant. The active
    /// [`ButtonStyle`] decides whether to honour or remap it (the IntUI
    /// default `RecipeButtonStyle` collapses Destructive → Filled,
    /// Tinted/Outlined → Plain, Link → Ghost).
    pub fn variant(mut self, variant: ButtonVariant) -> Self {
        self.variant = variant;
        self
    }

    /// Override the active [`ButtonStyle`] for this widget instance
    /// only. Useful for one-off custom-painted buttons (glassmorphism
    /// CTA, Material-3 ripple, etc.) without forking the Button.
    pub fn style(mut self, style: impl ButtonStyle) -> Self {
        self.style_override = Some(Rc::new(style));
        self
    }

    /// Bind the button's label to a reactive source — replaces the
    /// static label captured at `new(...)`. Accepts any
    /// `impl Into<Prop<String>>`: a `Signal<String>` for live
    /// updates, or a plain `String` (which is the same as constructing
    /// the button with that string). Mirrors
    /// [`TextWidget::text`](crate::primitives::TextWidget::text).
    /// The inner label `TextWidget` is built with the bound prop, so
    /// the visible text refreshes without rebuilding the Button. The
    /// AT node's `set_name` reads the current value via `Prop::get`.
    ///
    /// Translation note: derive the signal with
    /// `state.map(|s| tr!(status_label(value = s)).resolve_now())` for translated
    /// reactive labels — Button only sees the resolved `String`.
    pub fn label(mut self, label: impl Into<teksilo_core::signal::Prop<String>>) -> Self {
        self.label = label.into();
        self
    }

    /// Closure invoked on activation. Use `ctx.send_intent(...)` to
    /// route activation through the Action/Intent system, or inline
    /// the behavior directly.
    pub fn on_activate_fn(mut self, f: impl Fn(&mut EventContext) + 'static) -> Self {
        self.action = Some(Box::new(f));
        self
    }

    /// Whether an activation closure has been attached. Used by wrappers
    /// (e.g. `PopoverWidget`) that overwrite the activate slot, so they
    /// can warn when a caller-set handler is about to be discarded.
    pub(crate) fn has_activate_handler(&self) -> bool {
        self.action.is_some()
    }

    /// Attach a tooltip that appears after a hover delay.
    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 resolved from the app-wide tooltip registry.
    /// The `key` is looked up via
    /// [`TooltipRegistry`](crate::tooltip::TooltipRegistry) at build
    /// time; the resolved body text supports inline markup
    /// (`[label](url)`, `*italic*`, `**bold**`) and the entry's
    /// shortcut / long-form "more" fields are rendered automatically.
    ///
    /// Overrides any previously set plain `.tooltip(...)` text.
    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 driven by inline
    /// [`TooltipContent`](crate::tooltip::TooltipContent) — for
    /// one-off tooltips that aren't worth registering in the central
    /// catalog. Overrides any previously set plain `.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 — third tier, hosting an arbitrary
    /// widget tree (Crusader Kings 3 style: tabbed sections, charts,
    /// progress bars, conditional rows). Promotes to a focusable
    /// `Role::Dialog` after the user dwells for the standard
    /// promotion threshold. Overrides any plain or rich tooltip
    /// previously set on this button.
    pub fn composite_tooltip(
        mut self,
        content: impl teksilo_core::widget::Widget + 'static,
    ) -> Self {
        self.composite_tooltip_content = Some(Box::new(content));
        self.tooltip_text = None;
        self.rich_tooltip_source = None;
        self
    }

    /// Boxed variant of [`composite_tooltip`](Self::composite_tooltip).
    /// Used by `Clone` value types (e.g. `ToolbarAction`) that store a
    /// composite-body factory `Rc<dyn Fn() -> Box<dyn Widget>>` and forward
    /// the produced box through at build time.
    pub(crate) fn composite_tooltip_boxed(
        mut self,
        content: Box<dyn teksilo_core::widget::Widget>,
    ) -> Self {
        self.composite_tooltip_content = Some(content);
        self.tooltip_text = None;
        self.rich_tooltip_source = None;
        self
    }

    /// Set the enabled state, statically or reactively. Disabled buttons
    /// ignore input and dim their content (the framework's
    /// `PaintContext::effective_enabled` propagates through to the
    /// label/icon leaves). Forwarded into the arena via
    /// `ctx.enabled_when(self_id, self.enabled.clone())` at build time —
    /// a bound signal updates live as it changes.
    pub fn enabled(mut self, enabled: impl Into<Prop<bool>>) -> Self {
        self.enabled = enabled.into();
        self
    }

    /// Override the label and icon's tint with a static `ColorProp`.
    /// When set, the button ignores its `style` and the auto-derived
    /// idle/hover/press text-role cascade — both the label text and
    /// any icon are bound directly to this prop instead. Use for chrome
    /// whose host enforces a single text role across all of its
    /// sub-widgets (e.g. tab-bar overflow-dropdown triggers that must
    /// match the strip's `idle_text_role` regardless of hover state).
    /// Accepts `Color`, `TextRole`, `Signal<Color>`, or `Signal<TextRole>`.
    pub fn text_role(mut self, role: impl Into<teksilo_core::color_prop::ColorProp>) -> Self {
        self.text_role_override = Some(role.into());
        self
    }

    /// Override the label's text style (font, size, weight). By default the
    /// label uses the inner `TextWidget`'s default style; pass a
    /// `TextStyleRole` (e.g. `TextStyleRole::BodyBold`), a `TextStyle`, or a
    /// `Signal` of either to change it — e.g. to make the label bold.
    /// Orthogonal to [`Button::text_role`], which only sets the color.
    pub fn text_style(mut self, style: impl Into<teksilo_core::color_prop::TextStyleProp>) -> Self {
        self.label_style = Some(style.into());
        self
    }

    /// Add an icon to the button at the specified location.
    pub fn icon(mut self, icon: IconWidget, location: IconLocation) -> Self {
        self.icon = Some(icon);
        self.icon_location = location;
        self
    }

    /// Keep the icon's own colour instead of tinting it to the label's.
    ///
    /// The mirror of [`MenuItem::icon_keeps_color`](crate::menu_item::MenuItem::icon_keeps_color),
    /// and it exists for the same reason: an icon whose colour *is* the information.
    /// A filter chip carrying a user-chosen tag colour, a legend swatch, a status
    /// disc — tinting those to the label's foreground destroys the one thing they
    /// carry, while tinting is exactly right for a glyph that merely repeats the
    /// label.
    ///
    /// Two consequences worth knowing, both inherited from
    /// [`ColorProp`](teksilo_core::color_prop::ColorProp)'s own rules rather than
    /// special-cased here:
    ///
    /// * The colour must clear contrast against **every** fill the button takes —
    ///   an accent-filled selected state as well as the resting surface.
    /// * A literal colour **does not dim when the button is disabled**. An icon
    ///   that should dim wants a role instead, and then it does not need this.
    pub fn icon_keeps_color(mut self) -> Self {
        self.icon_keeps_color = true;
        self
    }

    /// Declare that this button is a disclosure trigger for a
    /// popup (menu, dialog, listbox, tree, grid). Surfaced via
    /// `set_has_popup` in the a11y node so screen readers announce
    /// it as leading into the named popup kind.
    pub fn has_popup(mut self, kind: teksilo_core::accesskit::HasPopup) -> Self {
        self.has_popup = Some(kind);
        self
    }

    /// Bind a signal reporting whether this button's popup is
    /// currently visible. The Popover / Dialog wrapper owns the
    /// signal and flips it on show / dismiss; Button reads it in
    /// `accessibility()` to publish `set_expanded`. Only
    /// meaningful alongside `.has_popup(...)`.
    pub fn expanded_when(mut self, signal: impl Into<Prop<bool>>) -> Self {
        self.expanded_signal = Some(signal.into());
        self
    }

    /// Insert a widget at the leading edge of the button's content
    /// (left in LTR, right in RTL). Composes with `.icon(...)`: the
    /// final order is `[leading_slot, icon+label, trailing_slot]`,
    /// separated by `btn::BUTTON_ICON_LABEL_GAP`. Single-slot —
    /// calling `.leading(...)` again replaces the previous slot.
    /// Stack multiple widgets with an explicit `HStack`.
    ///
    /// The slot widget paints itself and emits its own a11y. Button
    /// does **not** retint it (so e.g. a `ColorSwatch` keeps its own
    /// color through every interaction state). If the slot widget
    /// declares an AT role of its own — `ColorSwatch` is the canonical
    /// case (`Role::ColorWell`) — pass `widget.access_hidden(true)`
    /// so the trigger reads as a single Button node instead of a
    /// Button containing a redundant ColorWell child.
    pub fn leading(mut self, widget: impl Widget + 'static) -> Self {
        self.leading = Some(Box::new(widget));
        self
    }

    /// Same as [`leading`](Self::leading) but at the trailing edge
    /// (right in LTR, left in RTL). Common uses: chevron-down hint
    /// on disclosure triggers, clear-X on search fields, status
    /// badges on segmented control segments.
    pub fn trailing(mut self, widget: impl Widget + 'static) -> Self {
        self.trailing = Some(Box::new(widget));
        self
    }

    /// Construct the label `TextWidget` used inside the button's
    /// content layout. Always routes through `text(prop)` —
    /// `Prop::Static` and `Prop::Bound` are both handled uniformly
    /// by the TextWidget. `new(lit!(""))` seeds the placeholder
    /// initial text; `text` immediately overwrites it with the
    /// prop's current value (and tracks updates for `Prop::Bound`).
    fn make_label_text(&self, color: impl Into<teksilo_core::color_prop::ColorProp>) -> TextWidget {
        let mut text = TextWidget::new(lit!(""))
            .text(self.label.clone())
            .color(color)
            .single_line()
            .a11y_hidden();
        if let Some(style) = &self.label_style {
            text = text.style(style.clone());
        }
        text
    }

    /// Take the configured icon, size it, and bind its tint to `color`.
    /// Shared by every icon-bearing `IconLocation` arm so the size /
    /// color wiring lives in one place.
    ///
    /// A non-`None` `icon_location` with no icon set is a programming
    /// error — `.icon(...)` was never called. In debug builds the
    /// `debug_assert!` surfaces the mistake (mirroring how `Checkbox`
    /// asserts a missing accessible label); release falls back to an
    /// empty path so the button still lays out instead of panicking.
    fn make_icon(&mut self, color: impl Into<teksilo_core::color_prop::ColorProp>) -> IconWidget {
        use crate::styles::recipe_button_style as btn;
        debug_assert!(
            self.icon.is_some(),
            "Button: icon_location is {:?} but no icon was set via .icon(...)",
            self.icon_location,
        );
        let icon = self
            .icon
            .take()
            .unwrap_or_else(|| {
                IconWidget::from_path(teksilo_canvas::Path::new(), btn::BUTTON_ICON_SIZE)
            })
            .icon_size(btn::BUTTON_ICON_SIZE);
        if self.icon_keeps_color {
            icon
        } else {
            icon.color(color)
        }
    }

    /// Assemble the V2 attached-handler set (tap / hover / key / focus /
    /// access-action) wired to `interaction`. Takes `self.action`. The
    /// framework gates pointer / key / access events on
    /// `arena.is_enabled(self_id)` before dispatch and the focus walker
    /// skips disabled subtrees, so none of these closures need a
    /// build-time enabled snapshot — that duality was removed in the
    /// single-sourced-enabled refactor.
    fn build_handler_set(&mut self, interaction: Signal<InteractionState>) -> HandlerSet {
        // Bundle the optional command action into the unified
        // `on_activate` closure consumed by the shared family helper.
        let action: Rc<Option<CommandFactory>> = Rc::new(self.action.take());
        let on_activate: Rc<dyn Fn(&mut EventContext)> = Rc::new(move |ctx: &mut EventContext| {
            if let Some(ref action) = *action {
                action(ctx);
            }
        });
        build_interaction_handlers(interaction, on_activate, true)
    }
}

impl std::fmt::Debug for Button {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Button")
            .field("label", &self.label.get())
            .field("variant", &self.variant)
            .field("enabled", &self.enabled.get())
            .finish()
    }
}

// --- Label / icon color resolution ---
//
// The active `ButtonStyle` owns chrome (background fill, border, focus
// ring) but the inner content (label + icon) belongs to the Button
// itself, so it picks the text role. The mapping is intentionally
// minimal: `OnAccent` for variants that paint an accent fill, `Primary`
// for everything else, `Disabled` when the button is disabled. Custom
// `ButtonStyle` impls that paint a different background can request
// the Button to use a specific text role via `Button::text_role(...)`.

pub(crate) fn resolve_text_role(variant: ButtonVariant, _state: InteractionState) -> TextRole {
    // Disabled substitution happens at the leaf paint via
    // `ColorProp::resolve(theme, ctx.effective_enabled)` — see
    // `crates/teksilo-core/src/color_prop.rs`. The composite no
    // longer carries `InteractionState::Disabled`; the framework's
    // arena enabled-state drives the dim, and the leaves convert it
    // into `TextRole::Disabled` at paint time.
    match variant {
        ButtonVariant::Filled | ButtonVariant::Destructive => TextRole::OnAccent,
        ButtonVariant::Tinted
        | ButtonVariant::Outlined
        | ButtonVariant::Plain
        | ButtonVariant::Ghost => TextRole::Primary,
        ButtonVariant::Link => TextRole::Link,
    }
}

impl teksilo_core::widget::Widget for Button {
    fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
        // Layout constants for the inner content (icon size,
        // icon-label gap) come from the button recipe. The chrome
        // (padding, corner radius, fill, border) lives on the active
        // `ButtonStyle` impl.
        use crate::styles::recipe_button_style as btn;
        let variant = self.variant;
        let self_id = ctx.self_id();

        // Forward the enabled state into the arena. After this point the
        // arena is the single source of truth — events, focus, a11y, and
        // the leaves' role-resolution all consult
        // `arena.is_enabled(self_id)` / `PaintContext::effective_enabled`.
        // The interaction signal no longer carries Disabled: that was
        // the snapshot duality the architecture refactor removed.
        ctx.enabled_when(self_id, self.enabled.clone());

        // Reactive view of "is this widget effectively enabled?".
        let effective_enabled = ctx.effective_enabled_signal(self_id);

        // Create interaction signal — caller-supplied via
        // `share_interaction` when set (so a wrapping widget's chrome
        // can mirror the label's color), otherwise allocated locally.
        // Seeded to Idle; the arena's enabled-state is consulted
        // separately via `effective_enabled`.
        let interaction = match self.shared_interaction.take() {
            Some(shared) => shared,
            None => ctx.signal(InteractionState::Idle),
        };
        self.interaction = interaction.clone();

        // If an `expanded_signal` was wired up (disclosure
        // pattern — see `.has_popup()` / `.expanded_when()`),
        // register it with the framework so changes trigger a
        // repaint/a11y refresh on this button. Without the
        // binding registration, the signal updates but the
        // widget's `accessibility()` output won't be re-queried.
        if let Some(ref expanded_signal) = self.expanded_signal {
            let self_id = ctx.self_id();
            let registry = ctx.binding_registry();
            expanded_signal.register_if_bound(
                self_id,
                registry,
                teksilo_core::binding::BindingLevel::RepaintOnly,
            );
        }

        // If `label(signal)` was used, register the prop on the
        // Button itself at AccessibilityOnly so `set_name` re-runs
        // when the signal changes. The inner `TextWidget` already
        // re-renders via its own `text` plumbing — this binding
        // is purely for the AT name.
        let self_id = ctx.self_id();
        let registry = ctx.binding_registry();
        self.label.register_if_bound(
            self_id,
            registry,
            teksilo_core::binding::BindingLevel::AccessibilityOnly,
        );

        // Resolve the active `ButtonStyle` (per-call override > theme
        // slot > IntUI default). Both the label color (immediately below)
        // and the chrome (`make_body`, further down) consult it. The
        // lookup reads only `self.style_override` + `ctx.theme()`, so
        // resolving it here instead of just before `make_body` changes
        // nothing for existing styles.
        let style: SharedButtonStyle = self
            .style_override
            .clone()
            .or_else(|| ctx.theme().style_slots.button.clone())
            .unwrap_or_else(|| Rc::new(crate::styles::RecipeButtonStyle::default()));

        // Label/icon color: a caller-supplied override wins over the
        // auto cascade. The override replaces ALL states (idle / hover /
        // press / focus / disabled) — chrome that uses this opts out of
        // interaction-driven color feedback in exchange for matching a
        // host's enforced text role. Both label and icon read this same
        // prop, so a one-line override re-tints the whole button.
        //
        // Chrome (background fill, border, focus ring) is no longer
        // resolved here — the active `ButtonStyle` owns it via
        // `make_body(cfg, ctx)` below. This widget only resolves the
        // CONTENT color (label + icon) since that's part of the inner
        // subtree we hand to the style as `cfg.label`. The active style
        // may also redirect the content role (`label_text_role`) — e.g.
        // Material 3 paints text/outlined buttons in the accent color.
        let text_role: teksilo_core::color_prop::ColorProp =
            if let Some(ref over) = self.text_role_override {
                over.clone()
            } else if let Some(role) = style.label_text_role(variant) {
                role.into()
            } else {
                interaction
                    .map(move |s| resolve_text_role(variant, *s))
                    .into()
            };

        // Build the content (icon + label) based on icon_location. The
        // four directional arms (Leading/Trailing/Top/Bottom) share one
        // body: build the icon + label, then assemble them into an
        // HStack or VStack in icon-first / text-first order. Icon size /
        // color wiring is centralized in `make_icon`.
        let icon_location = self.icon_location;
        let content_id = match icon_location {
            IconLocation::None => ctx.add(self.make_label_text(text_role)),
            IconLocation::IconOnly => {
                let icon = self.make_icon(text_role);
                ctx.add(icon)
            }
            // Leading | Trailing | Top | Bottom
            loc => {
                let icon_first = matches!(loc, IconLocation::Leading | IconLocation::Top);
                let vertical = matches!(loc, IconLocation::Top | IconLocation::Bottom);
                let icon = self.make_icon(text_role.clone());
                let icon_id = ctx.add(icon);
                let text_id = ctx.add(self.make_label_text(text_role));
                let (first, second) = if icon_first {
                    (icon_id, text_id)
                } else {
                    (text_id, icon_id)
                };
                let row: Box<dyn Widget> = if vertical {
                    Box::new(
                        VStack::new()
                            .spacing(btn::BUTTON_ICON_LABEL_GAP)
                            .add_child(first)
                            .add_child(second),
                    )
                } else {
                    Box::new(
                        HStack::new()
                            .spacing(btn::BUTTON_ICON_LABEL_GAP)
                            .add_child(first)
                            .add_child(second),
                    )
                };
                ctx.add_boxed(row)
            }
        };

        // If leading or trailing slots are set, wrap the icon+label
        // content in an HStack: `[leading?, content, trailing?]`. When
        // both slots are absent, the wrap is skipped — the original
        // content node goes straight into the padding, keeping the
        // node count identical to the pre-slot Button for the common
        // case.
        let content_id = if self.leading.is_some() || self.trailing.is_some() {
            let mut row = HStack::new().spacing(btn::BUTTON_ICON_LABEL_GAP);
            if let Some(leading) = self.leading.take() {
                let id = ctx.add_boxed(leading);
                row = row.add_child(id);
            }
            row = row.add_child(content_id);
            if let Some(trailing) = self.trailing.take() {
                let id = ctx.add_boxed(trailing);
                row = row.add_child(id);
            }
            ctx.add(row)
        } else {
            content_id
        };

        // Delegate chrome (background fill, border, focus ring,
        // padding, min size) to the active `ButtonStyle` (resolved
        // above). The four boolean signals derive from the local
        // `interaction` state signal so the style can `.zip` them and
        // pick a per-state recipe slot.
        let is_pressed = interaction.map(|s| matches!(s, InteractionState::Pressed));
        let is_hovered = interaction.map(|s| matches!(s, InteractionState::Hovered));
        // `:focus-visible`: reveal the focus ring during keyboard navigation
        // only, not on a mouse click. Gate raw focus on the input-modality
        // signal (true after a key event, false after pointer-down).
        let is_focused = interaction
            .map(|s| matches!(s, InteractionState::Focused))
            .and(&ctx.focus_visible());
        // `is_disabled` derives from the arena's effective enabled
        // state — NOT from the interaction signal. The interaction
        // signal never carries Disabled anymore (the snapshot-based
        // duality was removed). Style chrome uses this to pick its
        // disabled-background role.
        let is_disabled = effective_enabled.map(|on| !*on);
        let cfg = ButtonStyleConfig {
            label: content_id,
            is_pressed,
            is_hovered,
            is_focused,
            is_disabled,
            variant,
        };
        let root_id = style.make_body(&cfg, ctx);

        // Attach tooltip if configured. The three setters
        // (`tooltip`, `rich_tooltip*`, `composite_tooltip`) are
        // mutually exclusive — every setter clears the other two so
        // exactly one branch runs.
        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.take() {
            let delay = ctx.theme().motion.tooltip_delay;
            crate::tooltip::attach_rich_tooltip_source(ctx, root_id, source, delay);
        } else if let Some(tooltip_text) = self.tooltip_text.clone() {
            let delay = ctx.theme().motion.tooltip_delay;
            crate::tooltip::attach_plain_tooltip(ctx, root_id, tooltip_text, delay);
        }

        self.root_child_id = Some(root_id);

        ctx.apply_self_handlers(self.build_handler_set(interaction));

        vec![root_id]
    }

    fn layout_response(
        &self,
        proposal: SizeProposal,
        ctx: &LayoutContext,
    ) -> teksilo_core::widget::LayoutResponse {
        // A Button is rigid: it sizes to its content and does NOT shrink in an
        // over-constrained row (a truncated action label reads
        // poorly — the desktop convention is to overflow excess actions into a
        // menu; see `Toolbar`). We therefore take only the content's SIZE and
        // drop its grow/shrink weights. The label still truncates if a caller
        // explicitly constrains the button (e.g. via `FixedSize` / `Shrinkable`).
        match self.root_child_id {
            Some(root_id) => ctx
                .child_size(root_id, proposal)
                .unwrap_or_else(|| proposal.resolve(0.0, 0.0)),
            None => proposal.resolve(0.0, 0.0),
        }
        .into()
    }

    fn place_children(
        &self,
        bounds: Rect,
        _proposal: SizeProposal,
        children: &mut [WidgetPlacement],
        _ctx: &LayoutContext,
    ) {
        // Single child fills our bounds
        for child in children.iter_mut() {
            child.origin = bounds.origin();
            child.size = bounds.size();
        }
    }

    fn accessibility(&self, builder: &mut AccessNodeBuilder) {
        builder.set_role(teksilo_core::accesskit::Role::Button);
        // Read the current label value uniformly through `Prop::get`
        // — Static returns the captured `String`; Bound returns the
        // signal's current value. Keeps AT in sync with `label`.
        builder.set_name(self.label.get());
        // `set_disabled()` is now driven by the framework's
        // accessibility walker from `arena.is_enabled(self_id)`. The
        // composite no longer needs to mirror it — the snapshot path
        // was redundant with the arena and broke under reactive
        // `enabled_when(id, signal)` flips.
        // ARIA disclosure pattern: a button that opens a popup
        // should declare `has_popup` and, if the wrapper tracks
        // it, `expanded`. Both are opt-in — regular buttons with
        // no popup stay silent on these properties.
        if let Some(kind) = self.has_popup {
            builder.set_has_popup(kind);
        }
        if let Some(ref signal) = self.expanded_signal {
            builder.set_expanded(signal.get());
        }
        builder.add_action(teksilo_core::accesskit::Action::Click);
        builder.add_action(teksilo_core::accesskit::Action::Focus);
    }

    fn children(&self) -> Vec<WidgetId> {
        match self.root_child_id {
            Some(id) => vec![id],
            None => Vec::new(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::cell::Cell;
    use std::rc::Rc;
    use teksilo_core::event::{Modifiers, WidgetEvent};
    use teksilo_core::widget_tree::WidgetTree;

    #[test]
    fn focus_ring_only_under_focus_visible() {
        // `:focus-visible`: the focus ring shows during keyboard navigation
        // but not when focus arrived via a pointer click. Programmatic focus
        // leaves `focus_visible` false, so a focused-but-not-keyboard button
        // shows no ring; a key press flips the modality and reveals it.
        let theme = teksilo_core::presets::intui::light();
        let ring = theme.colors.border_focused.to_array();
        let mut tree = WidgetTree::new().with_theme(theme);
        let btn = tree.add(Button::new(lit!("T")).on_activate_fn(|_| {}));
        tree.layout(SizeProposal::exact(200.0, 80.0));

        // Focused, but `focus_visible` is still false → ring gated OFF even
        // though the widget holds focus.
        tree.focus(btn);
        assert!(
            !frame_has_color(&tree.render(), ring),
            "no focus ring while focus-visible is false (pointer modality)",
        );

        // A key event flips `focus_visible` true → ring appears (focus held).
        tree.press_key(Key::ArrowDown, Modifiers::NONE);
        assert!(
            frame_has_color(&tree.render(), ring),
            "focus ring shows under keyboard modality",
        );
    }

    /// Whether `color` appears in any color-bearing layer of the frame —
    /// borders land in `shapes` (stroked SDF quads), `decorations`
    /// (`DecorationRect`), or `cosmetic_lines` depending on the widget.
    fn frame_has_color(frame: &teksilo_canvas::RenderFrame, color: [f32; 4]) -> bool {
        frame.shapes.iter().any(|s| s.color == color)
            || frame.decorations.iter().any(|d| d.color == color)
            || frame.cosmetic_lines.iter().any(|l| l.color == color)
    }

    #[test]
    fn filled_button_accent_desaturates_when_window_inactive() {
        // The Filled button bakes its fill via the theme signal
        // (`ColorProp::Bound`), which a plain `theme_signal` resolution would
        // freeze at the active accent — so it must resolve against the
        // window-active palette to grey out like the paint-resolving controls.
        let theme = teksilo_core::presets::intui::light();
        let accent = theme.colors.accent.to_array();
        let inactive_accent = theme.colors.for_inactive_window().accent.to_array();
        assert_ne!(accent, inactive_accent);

        let mut tree = WidgetTree::new().with_theme(theme);
        tree.add(Button::new(lit!("Save")).variant(ButtonVariant::Filled));
        tree.layout(SizeProposal::exact(200.0, 80.0));

        // Active: vivid accent fill.
        assert!(
            frame_has_color(&tree.render(), accent),
            "active window: Filled button paints the vivid accent"
        );

        // Inactive: the fill desaturates with every other accent control.
        tree.set_window_active(false);
        let frame = tree.render();
        assert!(
            frame_has_color(&frame, inactive_accent),
            "inactive window: Filled button fill desaturates"
        );
        assert!(
            !frame_has_color(&frame, accent),
            "inactive window: no vivid accent remains"
        );

        // Reactivate: vivid accent returns.
        tree.set_window_active(true);
        assert!(frame_has_color(&tree.render(), accent));
    }

    #[test]
    fn keyup_without_keydown_does_not_fire() {
        // Regression for the MessageBox reopen bug: when a shortcut
        // consumes Enter's KeyDown (dismissing the modal and restoring
        // focus to the trigger button), the trailing KeyUp must not
        // re-activate the trigger.
        let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
        let fired = Rc::new(Cell::new(0_u32));
        let fired_for_btn = fired.clone();
        let btn = tree.add(Button::new(lit!("T")).on_activate_fn(move |_ctx| {
            fired_for_btn.set(fired_for_btn.get() + 1);
        }));
        tree.layout(SizeProposal::exact(200.0, 80.0));
        tree.focus(btn);

        tree.dispatch_event(WidgetEvent::KeyUp {
            key: Key::Enter,
            modifiers: Modifiers::NONE,
        });
        assert_eq!(
            fired.get(),
            0,
            "a lone KeyUp (no matching KeyDown) must not activate the button",
        );

        tree.dispatch_event(WidgetEvent::KeyDown {
            key: Key::Enter,
            modifiers: Modifiers::NONE,
            text: None,
        });
        tree.dispatch_event(WidgetEvent::KeyUp {
            key: Key::Enter,
            modifiers: Modifiers::NONE,
        });
        assert_eq!(
            fired.get(),
            1,
            "a matched KeyDown + KeyUp pair must activate exactly once",
        );
    }

    // Helper: lay out a Target button (left) and an Open trigger (right)
    // side by side, then open a click-opened overlay anchored to the
    // trigger and parked below the bar. Returns the tree plus the pieces
    // the dismiss-passthrough tests assert on.
    fn open_overlay_beside_button() -> (
        WidgetTree,
        teksilo_core::widget_id::WidgetId, // target
        teksilo_core::widget_id::WidgetId, // trigger
        teksilo_core::widget_id::WidgetId, // overlay content
        Rc<Cell<u32>>,                     // target activations
        Rc<Cell<u32>>,                     // trigger activations
    ) {
        use teksilo_core::overlay::{
            DismissBehavior, OverlayLayer, OverlayPlacement, OverlayRequest,
        };

        let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
        let target_fired = Rc::new(Cell::new(0_u32));
        let tf = target_fired.clone();
        let trigger_fired = Rc::new(Cell::new(0_u32));
        let gf = trigger_fired.clone();

        let target =
            tree.add(Button::new(lit!("Target")).on_activate_fn(move |_| tf.set(tf.get() + 1)));
        let trigger =
            tree.add(Button::new(lit!("Open")).on_activate_fn(move |_| gf.set(gf.get() + 1)));
        let content = tree.add(Button::new(lit!("Item")));
        let _root = tree.add(
            crate::primitives::HStack::new()
                .spacing(40.0)
                .add_child(target)
                .add_child(trigger),
        );
        tree.layout(SizeProposal::exact(400.0, 200.0));

        tree.show_overlay(OverlayRequest {
            content_id: content,
            anchor: trigger,
            placement: OverlayPlacement::Below,
            dismiss: DismissBehavior::EscapeOrClickOutside,
            layer: OverlayLayer::InTree,
            parent_overlay: None,
            on_dismiss: None,
            fade_duration: None,
        });
        // Second layout positions the overlay content below the trigger.
        tree.layout(SizeProposal::exact(400.0, 200.0));

        (tree, target, trigger, content, target_fired, trigger_fired)
    }

    #[test]
    fn dismiss_click_activates_button_beneath() {
        // The reported quirk: with a dropdown/menu open, clicking another
        // widget should dismiss the overlay AND activate that widget in a
        // single click — not require a throwaway first click.
        use teksilo_core::event::PointerButton;

        let (mut tree, target, _trigger, _content, target_fired, trigger_fired) =
            open_overlay_beside_button();

        let tb = tree.bounds(target);
        let target_center =
            teksilo_canvas::Point::new(tb.x + tb.width / 2.0, tb.y + tb.height / 2.0);
        // The overlay is parked below the button bar; the dismiss assertion
        // after dispatch confirms this click lands outside it.
        assert_eq!(tree.active_overlays().len(), 1);

        tree.dispatch_event(WidgetEvent::PointerDown {
            position: target_center,
            button: PointerButton::Primary,
            modifiers: Modifiers::NONE,
        });
        tree.dispatch_event(WidgetEvent::PointerUp {
            position: target_center,
            button: PointerButton::Primary,
            modifiers: Modifiers::NONE,
        });

        assert!(
            tree.active_overlays().is_empty(),
            "the press should dismiss the open overlay",
        );
        assert_eq!(
            target_fired.get(),
            1,
            "the same press should activate the button beneath the dismissed overlay",
        );
        assert_eq!(trigger_fired.get(), 0);
    }

    #[test]
    fn dismiss_click_on_trigger_is_consumed_not_reactivated() {
        // The anchor guard: clicking the trigger that owns an open overlay
        // must merely close it. The press is consumed, so it can't reach
        // the trigger's own tap handler and reopen what it just closed.
        use teksilo_core::event::PointerButton;

        let (mut tree, _target, trigger, _content, _target_fired, trigger_fired) =
            open_overlay_beside_button();

        let gb = tree.bounds(trigger);
        let trigger_center =
            teksilo_canvas::Point::new(gb.x + gb.width / 2.0, gb.y + gb.height / 2.0);
        assert_eq!(tree.active_overlays().len(), 1);

        tree.dispatch_event(WidgetEvent::PointerDown {
            position: trigger_center,
            button: PointerButton::Primary,
            modifiers: Modifiers::NONE,
        });
        tree.dispatch_event(WidgetEvent::PointerUp {
            position: trigger_center,
            button: PointerButton::Primary,
            modifiers: Modifiers::NONE,
        });

        assert!(
            tree.active_overlays().is_empty(),
            "clicking the trigger should close its overlay",
        );
        assert_eq!(
            trigger_fired.get(),
            0,
            "the dismiss press on the anchor must be consumed, not delivered to the trigger",
        );
    }

    #[test]
    fn label_updates_at_name_when_signal_changes() {
        // Regression for the calendar header use case: a Button bound
        // to a `Signal<String>` must (1) display the signal's current
        // value and (2) refresh its accessibility name when the
        // signal changes — without rebuilding the parent.
        use teksilo_core::accessibility::widget_id_to_node_id;
        let label = Signal::new("May 2026".to_string());
        let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
        let id = tree.add(
            Button::new(lit!(""))
                .label(label.clone())
                .on_activate_fn(|_| {}),
        );
        tree.layout(SizeProposal::exact(300.0, 80.0));
        let target = widget_id_to_node_id(id);
        let update = tree.sync_accessibility();
        let (_, node) = update
            .nodes
            .iter()
            .find(|(nid, _)| *nid == target)
            .expect("button node");
        assert_eq!(node.label().unwrap_or_default(), "May 2026");

        // Flip the signal — AT name should refresh after the next
        // layout pass (the label registration triggers a
        // re-evaluation of `accessibility()`).
        label.set("2026".to_string());
        tree.layout(SizeProposal::exact(300.0, 80.0));
        let update = tree.sync_accessibility();
        let (_, node) = update
            .nodes
            .iter()
            .find(|(nid, _)| *nid == target)
            .expect("button node after relabel");
        assert_eq!(node.label().unwrap_or_default(), "2026");
    }

    #[test]
    fn slots_widen_button_to_accommodate_their_intrinsic_size() {
        // A button with leading + trailing slots reports a wider
        // intrinsic size than the same button without slots — proves
        // the slots actually entered the layout pass. Layout uses
        // `unspecified()` so each button reports its intrinsic width
        // rather than getting stretched to a parent proposal. Both
        // sides also clear the theme's `min_width` (~72dp) which
        // would otherwise mask the slot contribution on the plain
        // button.
        use crate::primitives::MinSize;
        let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
        let plain = tree.add(Button::new(lit!("X")).on_activate_fn(|_| {}));
        let with_slots = tree.add(
            Button::new(lit!("X"))
                .leading(MinSize::new(120.0, 12.0))
                .trailing(MinSize::new(120.0, 12.0))
                .on_activate_fn(|_| {}),
        );
        tree.layout(SizeProposal::unspecified());
        let plain_w = tree.bounds(plain).width;
        let slot_w = tree.bounds(with_slots).width;
        assert!(
            slot_w >= plain_w + 200.0,
            "expected slot button to be at least 200dp wider than plain (plain={plain_w}, slot={slot_w})",
        );
    }

    #[test]
    fn button_is_rigid_and_does_not_shrink_in_a_tight_row() {
        // A Button is rigid: in an over-constrained row it keeps its natural
        // width (overflows) rather than truncating its action label. The
        // desktop convention is to overflow excess actions into a menu (see
        // `Toolbar`), not to silently truncate buttons.
        use crate::primitives::hstack::HStack;
        let mut tree = WidgetTree::new()
            .with_theme(teksilo_core::presets::intui::light())
            .with_text_backend(std::rc::Rc::new(std::cell::RefCell::new(
                teksilo_canvas::MockTextBackend::new(),
            )));
        let btn = tree.add(Button::new(lit!("Save Document As…")).on_activate_fn(|_| {}));
        let _row = tree.add(HStack::new().add_child(btn));

        tree.layout(SizeProposal::unspecified());
        let natural = tree.bounds(btn).width;
        // Squeeze the row far below natural — the Button keeps its full width.
        tree.layout(SizeProposal::exact(70.0, 40.0));
        let squeezed = tree.bounds(btn).width;

        assert!(
            natural > 100.0,
            "expected a wide natural button, got {natural}"
        );
        assert!(
            (squeezed - natural).abs() < 0.5,
            "button should stay rigid at its natural width \
             (natural={natural}, squeezed={squeezed})"
        );
    }

    #[test]
    fn framework_default_blocks_secondary_tap_on_button() {
        // Framework default: `TapRecognizer::accept = ButtonMask::PRIMARY`.
        // A right-click on a Button does NOT activate. Generalises the
        // tab-specific `primary_click_activates_tab_secondary_does_not`
        // regression to every widget that wires `on_tap`.
        use teksilo_core::event::PointerButton;
        let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
        let fired = Rc::new(Cell::new(0_u32));
        let fired_for_btn = fired.clone();
        let btn = tree.add(Button::new(lit!("T")).on_activate_fn(move |_ctx| {
            fired_for_btn.set(fired_for_btn.get() + 1);
        }));
        tree.layout(SizeProposal::exact(200.0, 80.0));
        let center = tree.bounds(btn).center();

        tree.pointer_down_button(center, PointerButton::Secondary);
        tree.pointer_up_button(center, PointerButton::Secondary);
        assert_eq!(fired.get(), 0, "right-click must not activate a Button");

        tree.pointer_down_button(center, PointerButton::Middle);
        tree.pointer_up_button(center, PointerButton::Middle);
        assert_eq!(fired.get(), 0, "middle-click must not activate a Button");

        // Sanity: primary click still activates.
        tree.pointer_down_button(center, PointerButton::Primary);
        tree.pointer_up_button(center, PointerButton::Primary);
        assert_eq!(fired.get(), 1, "primary-click must activate a Button");
    }

    #[test]
    fn framework_accept_tap_buttons_secondary_fires_handler() {
        // `accept_tap_buttons` opts the auto-wired `TapRecognizer` into
        // a wider button set. With `Secondary` allowed, right-click
        // activates.
        use teksilo_core::event::{ButtonMask, PointerButton};
        use teksilo_core::widget_builder::WidgetBuilder;
        let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
        let fired = Rc::new(Cell::new(0_u32));
        let fired_for_btn = fired.clone();
        let btn = tree.add(
            Button::new(lit!("T"))
                .on_activate_fn(move |_ctx| {
                    fired_for_btn.set(fired_for_btn.get() + 1);
                })
                .accept_tap_buttons(ButtonMask::PRIMARY | ButtonMask::SECONDARY),
        );
        tree.layout(SizeProposal::exact(200.0, 80.0));
        let center = tree.bounds(btn).center();

        tree.pointer_down_button(center, PointerButton::Secondary);
        tree.pointer_up_button(center, PointerButton::Secondary);
        assert_eq!(
            fired.get(),
            1,
            "right-click must activate a Button when accept_tap_buttons includes Secondary",
        );

        tree.pointer_down_button(center, PointerButton::Primary);
        tree.pointer_up_button(center, PointerButton::Primary);
        assert_eq!(fired.get(), 2, "primary-click still activates");
    }

    #[test]
    fn hidden_slot_marks_swatch_node_as_at_hidden() {
        // ColorSwatch declares `Role::ColorWell`. Dropped raw into a
        // Button slot it would appear as a redundant ColorWell child
        // under the Button's node. `.access_hidden(true)` is the
        // documented escape hatch — confirm the swatch's AT node
        // carries the hidden flag (AT readers skip nodes flagged
        // hidden, even though the node still exists in the tree).
        use crate::color_picker::ColorSwatch;
        use teksilo_core::accessibility::widget_id_to_node_id;
        use teksilo_core::accesskit::Role;
        use teksilo_core::widget_builder::WidgetBuilder;
        use teksilo_tokens::Color;
        let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
        let id = tree.add(
            Button::new(lit!("Pick"))
                .leading(ColorSwatch::new(Color::RED).access_hidden(true))
                .on_activate_fn(|_| {}),
        );
        tree.layout(SizeProposal::exact(300.0, 80.0));
        let target = widget_id_to_node_id(id);
        let update = tree.sync_accessibility();
        let (_, btn_node) = update
            .nodes
            .iter()
            .find(|(nid, _)| *nid == target)
            .expect("button node");
        assert_eq!(btn_node.role(), Role::Button);
        let color_well_visible = update
            .nodes
            .iter()
            .any(|(_, n)| n.role() == Role::ColorWell && !n.is_hidden());
        assert!(
            !color_well_visible,
            "hidden swatch should not emit a non-hidden ColorWell node",
        );
    }

    #[test]
    fn plain_button_is_a_leaf_no_group_node() {
        // Regression: a Button's chrome is composed from layout primitives
        // (Padding/Center/HStack/…) that emit empty GenericContainer /
        // Unknown AT nodes. VoiceOver announces a GenericContainer as
        // "group", so the button read as "<label>, button, group". The AT
        // walker now collapses presentational nodes — assert the button is
        // a clean leaf and no grouping node survives anywhere.
        use teksilo_core::accessibility::widget_id_to_node_id;
        use teksilo_core::accesskit::Role;
        let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
        let id = tree.add(Button::new(lit!("Valider")).on_activate_fn(|_| {}));
        tree.layout(SizeProposal::exact(300.0, 80.0));
        let _ = tree.render();
        let update = tree.sync_accessibility();

        assert!(
            !update
                .nodes
                .iter()
                .any(|(_, n)| n.role() == Role::GenericContainer),
            "no GenericContainer ('group') node should remain in the AT tree"
        );

        let (_, btn) = update
            .nodes
            .iter()
            .find(|(nid, _)| *nid == widget_id_to_node_id(id))
            .expect("button node present");
        assert_eq!(btn.role(), Role::Button);
        assert_eq!(btn.label(), Some("Valider"));
        let has_visible_child = btn.children().iter().any(|cid| {
            update
                .nodes
                .iter()
                .find(|(nid, _)| nid == cid)
                .is_some_and(|(_, n)| !n.is_hidden())
        });
        assert!(
            !has_visible_child,
            "button should expose no visible AT child node (it is a leaf)"
        );
    }

    #[test]
    fn theme_slot_supplies_button_style_when_no_override() {
        // End-to-end check that `theme.style_slots.button = Some(rc)`
        // actually feeds the widget when no per-call `.style(...)`
        // override is present. Uses a custom `ButtonStyle` that adds a
        // sentinel `RectWidget` we can spot in the rendered frame.
        use teksilo_core::styles::{ButtonStyle, ButtonStyleConfig};
        use teksilo_tokens::Color;

        struct SentinelButton;
        impl ButtonStyle for SentinelButton {
            fn make_body(
                &self,
                cfg: &ButtonStyleConfig,
                ctx: &mut teksilo_core::build_context::BuildContext,
            ) -> teksilo_core::widget_id::WidgetId {
                // Distinctive bright-magenta background nobody else paints.
                let bg = ctx.add(
                    crate::primitives::RectWidget::new()
                        .background(Color::new(1.0, 0.0, 1.0, 1.0))
                        .corner_radius(teksilo_tokens::CornerRadius::uniform(0.0)),
                );
                ctx.add(
                    crate::primitives::ZStack::new()
                        .add_child(bg)
                        .add_child(cfg.label),
                )
            }
        }

        let mut theme = teksilo_core::presets::intui::light();
        theme.style_slots.button = Some(Rc::new(SentinelButton));
        let mut tree = WidgetTree::new().with_theme(theme);
        let _btn = tree.add(Button::new(lit!("T")).on_activate_fn(|_| {}));
        tree.layout(SizeProposal::exact(200.0, 80.0));
        let frame = tree.render();

        let sentinel = [1.0_f32, 0.0, 1.0, 1.0];
        assert!(
            frame.shapes.iter().any(|s| s.color == sentinel),
            "the theme's `style_slots.button` impl should drive Button chrome \
             — saw no sentinel magenta rect in the rendered frame",
        );
    }

    #[test]
    fn style_label_text_role_overrides_default_label_color() {
        // A `ButtonStyle` returning `Some(role)` from `label_text_role`
        // redirects the label/icon color — the Material 3 "text and
        // outlined buttons are accent-colored" need. Styles that return
        // `None` (the IntUI default) keep the Button's built-in mapping,
        // so this is purely additive (the rest of the suite covers the
        // default path).
        use std::cell::RefCell;
        use teksilo_canvas::MockTextBackend;
        use teksilo_core::styles::{ButtonStyle, ButtonStyleConfig, ButtonVariant};
        use teksilo_tokens::TextRole;

        struct LabelRoleSentinel;
        impl ButtonStyle for LabelRoleSentinel {
            fn make_body(
                &self,
                cfg: &ButtonStyleConfig,
                ctx: &mut teksilo_core::build_context::BuildContext,
            ) -> teksilo_core::widget_id::WidgetId {
                ctx.add(crate::primitives::ZStack::new().add_child(cfg.label))
            }
            fn label_text_role(&self, _variant: ButtonVariant) -> Option<TextRole> {
                Some(TextRole::Error)
            }
        }

        let want = teksilo_core::presets::intui::light()
            .colors
            .text_error
            .to_array();
        let mut theme = teksilo_core::presets::intui::light();
        theme.style_slots.button = Some(Rc::new(LabelRoleSentinel));
        let mut tree = WidgetTree::new()
            .with_theme(theme)
            .with_text_backend(Rc::new(RefCell::new(MockTextBackend::new())));
        let _btn = tree.add(Button::new(lit!("T")).on_activate_fn(|_| {}));
        tree.layout(SizeProposal::exact(200.0, 80.0));
        let frame = tree.render();

        assert!(
            frame.glyphs.iter().any(|g| g.color == want),
            "style.label_text_role(...) should drive the label glyph color; \
             expected the theme error color {want:?}, saw {:?}",
            frame.glyphs.iter().map(|g| g.color).collect::<Vec<_>>(),
        );
    }

    #[test]
    fn per_call_style_override_wins_over_theme_slot() {
        // When both `Button::style(...)` AND `theme.style_slots.button`
        // are set, the per-call wins. Verified by installing a sentinel
        // style on the theme then a *different* sentinel via `.style()`.
        use teksilo_core::styles::{ButtonStyle, ButtonStyleConfig};
        use teksilo_tokens::Color;

        struct ThemeSentinel;
        impl ButtonStyle for ThemeSentinel {
            fn make_body(
                &self,
                cfg: &ButtonStyleConfig,
                ctx: &mut teksilo_core::build_context::BuildContext,
            ) -> teksilo_core::widget_id::WidgetId {
                let bg = ctx.add(
                    crate::primitives::RectWidget::new()
                        .background(Color::new(1.0, 0.0, 1.0, 1.0)) // magenta
                        .corner_radius(teksilo_tokens::CornerRadius::uniform(0.0)),
                );
                ctx.add(
                    crate::primitives::ZStack::new()
                        .add_child(bg)
                        .add_child(cfg.label),
                )
            }
        }

        struct CallSentinel;
        impl ButtonStyle for CallSentinel {
            fn make_body(
                &self,
                cfg: &ButtonStyleConfig,
                ctx: &mut teksilo_core::build_context::BuildContext,
            ) -> teksilo_core::widget_id::WidgetId {
                let bg = ctx.add(
                    crate::primitives::RectWidget::new()
                        .background(Color::new(0.0, 1.0, 0.0, 1.0)) // green
                        .corner_radius(teksilo_tokens::CornerRadius::uniform(0.0)),
                );
                ctx.add(
                    crate::primitives::ZStack::new()
                        .add_child(bg)
                        .add_child(cfg.label),
                )
            }
        }

        let mut theme = teksilo_core::presets::intui::light();
        theme.style_slots.button = Some(Rc::new(ThemeSentinel));
        let mut tree = WidgetTree::new().with_theme(theme);
        let _btn = tree.add(
            Button::new(lit!("T"))
                .style(CallSentinel)
                .on_activate_fn(|_| {}),
        );
        tree.layout(SizeProposal::exact(200.0, 80.0));
        let frame = tree.render();

        let magenta = [1.0_f32, 0.0, 1.0, 1.0];
        let green = [0.0_f32, 1.0, 0.0, 1.0];
        assert!(
            frame.shapes.iter().any(|s| s.color == green),
            "per-call .style(...) override should drive chrome — no green rect found",
        );
        assert!(
            !frame.shapes.iter().any(|s| s.color == magenta),
            "theme slot must be ignored when per-call override is set — magenta should not appear",
        );
    }
}

/// [`Button::icon_keeps_color`] — the icon's own colour survives, or it does not.
#[cfg(test)]
mod icon_color_tests {
    use super::*;
    use teksilo_core::widget_tree::WidgetTree;

    /// A disc in a colour no theme role would ever produce, so finding it in the frame
    /// can only mean the icon kept it.
    const SWATCH: [f32; 4] = [0.93, 0.29, 0.60, 1.0];

    fn swatch_icon() -> IconWidget {
        let centre = teksilo_canvas::Point::new(5.0, 5.0);
        IconWidget::from_path(teksilo_canvas::Path::circle(centre, 4.5), 10.0).color(
            teksilo_tokens::Color::from_rgba(SWATCH[0], SWATCH[1], SWATCH[2], SWATCH[3]),
        )
    }

    fn painted(button: Button) -> bool {
        let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
        let _ = tree.add(button);
        tree.layout(SizeProposal::exact(240.0, 60.0));
        let frame = tree.render();
        // An `IconWidget::from_path` lands in `paths`, not `shapes` — the button's
        // own chrome is what fills `shapes`.
        frame.paths.iter().any(|p| p.color == SWATCH)
            || frame.shapes.iter().any(|s| s.color == SWATCH)
            || frame.decorations.iter().any(|d| d.color == SWATCH)
    }

    /// The default: an icon repeats the label, so it takes the label's colour and the
    /// button stays one legible unit under every variant and state.
    #[test]
    fn an_icon_is_tinted_to_the_label_by_default() {
        assert!(
            !painted(Button::new(lit!("Tag")).icon(swatch_icon(), IconLocation::Leading)),
            "the icon kept its own colour without being asked to"
        );
    }

    /// And the opt-out, for an icon whose colour *is* the information — a filter chip
    /// carrying a user-chosen tag colour has nothing left if it is tinted away.
    #[test]
    fn icon_keeps_color_survives_the_buttons_tint() {
        assert!(
            painted(
                Button::new(lit!("Tag"))
                    .icon(swatch_icon(), IconLocation::Leading)
                    .icon_keeps_color()
            ),
            "icon_keeps_color did not reach the painted icon"
        );
    }
}