rust_widgets 2.5.2

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 180 widgets, touch/gesture support, i18n, and SVG-pipeline-accurate output
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
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! JSON layout loader — parses JSON source and instantiates widget trees.
//!
//! The [`JsonLoader`] reads a JSON string, recursively creates
//! widget instances, applies properties (geometry, style, events),
//! and returns a [`BoundJsonLayout`](crate::json::BoundJsonLayout)
//! for typed widget access.
//!
//! # i18n Support
//!
//! Text properties (`title`, `text`, `tooltip`, `placeholder`) accept
//! translation keys. Use the [`crate::i18n::I18nManager::translate`] or
//! the [`crate::tr!`] macro at the call site to resolve the key before
//! passing JSON to the loader. The loader itself does NOT call the
//! i18n manager – it uses the literal string values from JSON.
//!
//! # Event Binding
//!
//! When a JSON node declares `"on_click": "handler_name"`, the string
//! is stored in the loader and connected after instantiation.
//! Callers use [`EventHandlerMap`](crate::json::EventHandlerMap) to
//! register closures against those handler names.

use serde_json::Value;

use crate::app::{ButtonHandle, WidgetHandle};
use crate::core::{Alignment, Color, ObjectId, Orientation, Rect};
use crate::json::properties::ApplyOutcome;
use crate::json::{
    add_spacer_to_layout, add_widget_to_layout, apply_layout, create_layout_from_kind,
    parse_layout_kind, store_layout, BoundJsonLayout, ChildLayoutAttrs,
};
use crate::layout::inspector::LayoutInspector;
use crate::widget::{
    Button, CheckBox, ComboBox, GroupBox, Label, LineEdit, ListBox, ProgressBar, RadioButton,
    ScrollArea, ScrollBar, Slider, SpinBox, Switch, Widget,
};
#[cfg(not(alloc_frugal))]
use crate::widget::{
    ColorDialog, FileDialog, FontDialog, GridWidget, ListView, MessageBox, TabWidget, TextEdit,
};
use crate::window::Window;
// `WidgetKind` is named only by the test-only `infer_kind` table below; production
// registration reads the live control's kind instead.
#[cfg(test)]
use crate::index::WidgetKind;

/// Maximum nested depth for recursive instantiation (prevents stack overflow).
const MAX_DEPTH: u32 = 64;

/// A loader that parses JSON layout strings and instantiates widget trees.
pub struct JsonLoader;

impl JsonLoader {
    /// Parse a JSON layout string and instantiate the widget tree.
    ///
    /// Returns a [`BoundJsonLayout`] for typed widget access.
    ///
    /// # Errors
    ///
    /// Returns an error if JSON parsing fails, an unknown widget type is
    /// encountered, or the widget tree exceeds `MAX_DEPTH`.
    pub fn load(json_str: &str) -> Result<BoundJsonLayout, String> {
        let value: Value = serde_json::from_str(json_str).map_err(|e| {
            format!("layout JSON ({} bytes) could not be parsed: {e}", json_str.len())
        })?;
        let mut registry = crate::index::WidgetRegistry::new();
        let mut binding = BoundJsonLayout::new();

        let root = value.as_object().ok_or_else(|| "JSON root must be an object".to_string())?;

        // The root should have exactly one top-level key (the widget type).
        if root.len() != 1 {
            return Err(format!(
                "JSON root must have exactly one widget type, found {} keys",
                root.len()
            ));
        }

        let (widget_type, widget_value) = match root.iter().next() {
            Some(pair) => pair,
            None => {
                return Err("JSON root object is empty — expected a widget type key".to_string())
            }
        };
        Self::instantiate_node(widget_type, widget_value, None, &mut registry, &mut binding, 0)?;

        // Run layout diagnostics after all widgets are created.
        LayoutInspector::run_once_logged(&registry);

        Ok(binding)
    }

    /// Wires the handlers a node declares, for both routes.
    ///
    /// # Why one function for two key spellings
    ///
    /// The published route (`events`) and the compatibility route (`on_*`) reach the same
    /// [`EventHandlerContext`] through the same marker table — see `crate::json::event_route`.
    /// Splitting them gave the loader two code paths that had to agree about trigger kinds and
    /// about which handlers are invoked, with nothing checking that they did.
    ///
    /// # What is reported rather than ignored
    ///
    /// A name under `events` that the control does not publish is **dropped with a warning**
    /// rather than silently wired. A designer that misspells a published name would otherwise
    /// get a handler that never runs; the warning is what makes that visible in the host's log.
    /// The reverse case — an `on_*` key the marker table does not list — cannot reach here,
    /// because the table *is* the list of keys this reads.
    fn bind_declared_events(
        widget_id: ObjectId,
        widget_type: &str,
        obj: &serde_json::Map<String, Value>,
    ) {
        // ── route 1: published names ──
        if let Some(events) = obj.get(crate::json::EVENTS_KEY).and_then(|v| v.as_object()) {
            for (name, handler) in events {
                let Some(handler) = handler.as_str() else {
                    log::warn!(
                        "[{widget_type}] `{EVENTS_KEY}.{name}` must be a handler name string, \
                         found {found:?}; the binding is skipped",
                        EVENTS_KEY = crate::json::EVENTS_KEY,
                        found = handler
                    );
                    continue;
                };
                if !Self::control_publishes(widget_type, name) {
                    log::warn!(
                        "[{widget_type}] `{EVENTS_KEY}.{name}` is not a published event \
                         (publishes: {published}); the binding is skipped, so the handler \
                         would never run",
                        EVENTS_KEY = crate::json::EVENTS_KEY,
                        published = Self::published_events(widget_type).join(", ")
                    );
                    continue;
                }
                Self::bind_one(
                    widget_id,
                    crate::json::DeclaredHandler {
                        handler: handler.to_owned(),
                        // A published name is payload-free from the hub's point of view; the handler
                        // already knows which name it was declared against, so no marker is invented.
                        marker: crate::json::JsonTriggerMarker::Clicked,
                    },
                );
            }
        }

        // ── route 2: compatibility keys ──
        for (key, marker) in crate::json::MARKER_KEYS {
            let Some(handler) = obj.get(*key).and_then(|v| v.as_str()) else {
                continue;
            };
            Self::bind_one(
                widget_id,
                crate::json::DeclaredHandler { handler: handler.to_owned(), marker: *marker },
            );
        }
    }

    /// Subscribes one declared handler to `widget_id`.
    ///
    /// The two routes differ only in which callback they reach: a payload-free trigger
    /// (`clicked`, `closed`) goes through `on_click`, and a payload-carrying one (`value_changed`,
    /// `selection_changed`, focus) through `on_value_changed`. That choice is `marker`-driven, not
    /// call-site-driven, so a new marker cannot pick the wrong callback by being added in one
    /// place and not the other.
    fn bind_one(widget_id: ObjectId, declared: crate::json::DeclaredHandler) {
        let handler_name = declared.handler;
        let ctx_marker = declared.marker;
        let handle: ButtonHandle = ButtonHandle::from_raw(widget_id);
        match ctx_marker {
            crate::json::JsonTriggerMarker::Clicked
            | crate::json::JsonTriggerMarker::DoubleClicked
            | crate::json::JsonTriggerMarker::Closed => {
                handle.on_click(move || {
                    let ctx = crate::json::context_for(widget_id, ctx_marker);
                    crate::json::invoke_global_handler(&handler_name, &ctx);
                });
            }
            _ => {
                handle.on_value_changed(move |_value| {
                    let ctx = crate::json::context_for(widget_id, ctx_marker);
                    crate::json::invoke_global_handler(&handler_name, &ctx);
                });
            }
        }
    }

    /// Whether `widget_type` publishes `event_name`.
    ///
    /// # Why the answer is "no" on a stripped profile
    ///
    /// The capability table is compiled out of `mini`/`embedded`, and `crate::json` does not
    /// exist there either — this function is inside a `full_widgets` module, so the table is
    /// always present when it runs. The fallback is stated rather than assumed because a future
    /// gate change would otherwise turn it into a silent `true`.
    fn control_publishes(widget_type: &str, event_name: &str) -> bool {
        let factory = crate::widget::capability::WidgetFactory::new_with_defaults();
        let normalized = crate::widget::capability::normalize_key(event_name);
        factory.capability(widget_type).is_some_and(|capability| {
            capability
                .events
                .iter()
                .any(|schema| crate::widget::capability::normalize_key(schema.name) == normalized)
        })
    }

    /// The published event names of `widget_type`, for the warning above.
    fn published_events(widget_type: &str) -> Vec<&'static str> {
        let factory = crate::widget::capability::WidgetFactory::new_with_defaults();
        factory
            .capability(widget_type)
            .map(|capability| capability.events.iter().map(|schema| schema.name).collect())
            .unwrap_or_default()
    }

    /// Recursively instantiate a single JSON node into a widget.
    #[allow(clippy::too_many_arguments)]
    fn instantiate_node(
        widget_type: &str,
        value: &Value,
        parent_id: Option<ObjectId>,
        registry: &mut crate::index::WidgetRegistry,
        binding: &mut BoundJsonLayout,
        depth: u32,
    ) -> Result<ObjectId, String> {
        if depth > MAX_DEPTH {
            return Err(format!(
                "widget tree is nested {depth} levels deep, which exceeds the maximum of \
                 {MAX_DEPTH}; flatten the layout to load it"
            ));
        }

        let obj = value
            .as_object()
            .ok_or_else(|| format!("'{widget_type}' value must be a JSON object"))?;

        // Get the widget ID (optional — auto-generated if missing).
        let id_str = obj.get("id").and_then(|v| v.as_str()).unwrap_or("");

        // Handle the "spacer" pseudo-widget
        if widget_type.eq_ignore_ascii_case("spacer") {
            let stretch = obj.get("stretch").and_then(|v| v.as_u64()).unwrap_or(1) as u32;
            if let Some(pid) = parent_id {
                add_spacer_to_layout(stretch, pid);
            }
            return Ok(0);
        }

        // Handle the "layout" pseudo-widget
        if widget_type.eq_ignore_ascii_case("layout") {
            let kind = parse_layout_kind(value)?;
            let layout = create_layout_from_kind(&kind);
            let layout_parent = parent_id
                .ok_or_else(|| format!("'{widget_type}' layout must be a child of a widget"))?;

            // Stored *before* the children are instantiated, because registering a
            // child needs the layout to exist (`add_widget_to_layout` is a no-op
            // otherwise). Storing it afterwards — which this code used to do — left the
            // layout empty, so `apply_layout` computed an arrangement for no children
            // and no widget ever moved.
            store_layout(layout_parent, layout);

            // Process children
            if let Some(children) = obj.get("children").and_then(|v| v.as_array()) {
                for child_value in children {
                    if let Some(child_obj) = child_value.as_object() {
                        if child_obj.len() == 1 {
                            let (child_type, child_val) = child_obj.iter().next().unwrap();
                            if child_type.eq_ignore_ascii_case("spacer") {
                                let stretch =
                                    child_val.get("stretch").and_then(|v| v.as_u64()).unwrap_or(1)
                                        as u32;
                                add_spacer_to_layout(stretch, layout_parent);
                                continue;
                            }

                            let child_id = Self::instantiate_node(
                                child_type,
                                child_val,
                                Some(layout_parent),
                                registry,
                                binding,
                                depth + 1,
                            )?;

                            if child_id != 0 {
                                let attrs = ChildLayoutAttrs::from_value(child_val);
                                // The layout must already be stored for this to reach
                                // it: `add_widget_to_layout` is a no-op when the parent
                                // has none. `store_layout` used to run *after* this
                                // loop, so every child was added to nothing and the
                                // layout was empty when it was applied — which is why
                                // a declarative layout could compute geometries that no
                                // widget ever received.
                                add_widget_to_layout(child_id, attrs.stretch, layout_parent);
                            }
                        }
                    }
                }
            }

            apply_layout(layout_parent, json_geometry(obj));
            return Ok(layout_parent);
        }

        // Create the widget
        let mut widget: Box<dyn Widget> = Self::create_widget(widget_type, obj)?;

        // Apply stylesheet rules first, so explicit JSON keys below win over the
        // stylesheet — the same precedence a browser gives inline styles over an
        // author stylesheet. `class` selects which rules apply; the widget's own
        // kind is matched automatically.
        apply_declared_styles(&mut *widget, obj);

        // Apply common properties (geometry, enabled, visible, tooltip, style)
        apply_properties(&mut *widget, obj);

        // Apply min/max size constraints
        apply_size_constraints(&mut *widget, obj);

        // Set parent
        widget.set_parent(parent_id);

        // Register
        let widget_id = widget.id();
        // The **live control's** kind, not a value derived from the type name.
        //
        // `infer_kind` is a hand-written table covering about a hundred names, while
        // the factory routes far more (canonical names plus aliases). Anything the
        // table did not name — `icon`, `table`, `chip`, `progress_bar`, … — fell
        // through its `_ => WidgetKind::Button` arm, so the registry recorded `Button`
        // for a control that is not one, and `LayoutInspector`/`by_kind` queries then
        // reported the wrong kind. The widget already knows its kind, so reading it
        // here removes the table's ability to disagree with reality.
        //
        // `infer_kind` is still consulted for the one case the widget cannot answer:
        // a name whose control has no kind-specific entry. Every `Widget` implements
        // `kind()`, so that fallback is unreachable in practice; it is kept as the
        // honest answer for a hypothetical widget that overrides nothing.
        let kind = widget.kind();

        let label = if id_str.is_empty() {
            format!("{widget_type}_{widget_id}")
        } else {
            id_str.to_string()
        };

        registry.register(crate::index::WidgetEntry {
            id: widget_id,
            kind,
            parent: parent_id,
            label,
        });

        if !id_str.is_empty() {
            binding.register(id_str, widget_id);
        }

        // Structural index: record which node this is, under which parent, and with which
        // key. `id_str` doubles as the key because the JSON schema already requires it to be
        // unique per document (it is how `widget_by_name` addresses a control), so requiring
        // a second, separate `key` field would let the two disagree. A node without an `id`
        // therefore has no stable identity to diff on, and `node_key` reports `None` for it.
        binding.register_node(widget_id, widget_type, id_str, parent_id);

        // ── Apply text property via platform API ────────────
        // Text for widgets that accept it (checkbox, radiobutton,
        // groupbox title via "title" key, lineedit placeholder, etc.)
        // is set through the global set_widget_text function.
        //
        // i18n: If the text value is a translation key, resolve it
        // BEFORE passing to the loader (e.g. tr!("button.ok")).
        // The loader uses the literal string as-is.
        if let Some(text) = obj.get("text").and_then(|v| v.as_str()) {
            if !text.is_empty()
                && !matches!(widget_type.to_lowercase().as_str(), "button" | "label")
            {
                crate::set_widget_text(widget_id, text);
            }
        }
        // Handle "title" property — BLUE4.md spec says groupbox uses "title"
        // (not "text"). For window, title is already set in create_widget.
        // Only apply via platform API for non-window widgets.
        if widget_type.to_lowercase().as_str() != "window" {
            if let Some(title) = obj.get("title").and_then(|v| v.as_str()) {
                if !title.is_empty() {
                    crate::set_widget_text(widget_id, title);
                }
            }
        }

        // ── Event binding ──────────────────────────────────────────────
        //
        // Two routes, one binder. See `crate::json::event_route` for why both exist and which
        // job each one has:
        //
        //   * `"events": { "<published_name>": "<handler>" }` — the published route. The name is
        //     checked against the control's capability, so a published event is declarable with
        //     no edit here (rule #101).
        //   * `"on_*": "<handler>"` — the compatibility route. Its keys mean a trigger *intent*
        //     (`on_close` → Closed) rather than a published name, and they are read from
        //     `MARKER_KEYS` rather than from a hand-written tuple, so a key cannot be extracted
        //     into the wrong position.
        Self::bind_declared_events(widget_id, widget_type, obj);

        // Handle children (for container widgets)
        if let Some(children) = obj.get("children").and_then(|v| v.as_array()) {
            for child_value in children {
                if let Some(child_obj) = child_value.as_object() {
                    if child_obj.len() == 1 {
                        let (child_type, child_val) = child_obj.iter().next().unwrap();
                        Self::instantiate_node(
                            child_type,
                            child_val,
                            Some(widget_id),
                            registry,
                            binding,
                            depth + 1,
                        )?;
                    }
                }
            }
        }

        // Handle layout inline
        if let Some(layout_val) = obj.get("layout") {
            let kind = parse_layout_kind(layout_val)?;
            let layout = create_layout_from_kind(&kind);

            // Stored before the children below are registered, for the same reason as
            // the `"layout"` pseudo-widget branch: a child added before the layout
            // exists is added to nothing.
            store_layout(widget_id, layout);

            // Process layout children from the layout object
            if let Some(layout_obj) = layout_val.as_object() {
                if let Some(children) = layout_obj.get("children").and_then(|v| v.as_array()) {
                    for child_value in children {
                        if let Some(child_obj) = child_value.as_object() {
                            if child_obj.len() == 1 {
                                let (child_type, child_val) = child_obj.iter().next().unwrap();
                                if child_type.eq_ignore_ascii_case("spacer") {
                                    let stretch = child_val
                                        .get("stretch")
                                        .and_then(|v| v.as_u64())
                                        .unwrap_or(1)
                                        as u32;
                                    add_spacer_to_layout(stretch, widget_id);
                                    continue;
                                }

                                let child_id = Self::instantiate_node(
                                    child_type,
                                    child_val,
                                    Some(widget_id),
                                    registry,
                                    binding,
                                    depth + 1,
                                )?;

                                if child_id != 0 {
                                    let attrs = ChildLayoutAttrs::from_value(child_val);
                                    // See the note on the other `add_widget_to_layout`
                                    // call: the layout has to be stored before its
                                    // children are registered, or they are added to
                                    // nothing.
                                    add_widget_to_layout(child_id, attrs.stretch, widget_id);
                                }
                            }
                        }
                    }
                }
            }

            apply_layout(widget_id, json_geometry(obj));
        }

        Ok(widget_id)
    }

    /// Create a widget box from a type name and property object.
    ///
    /// Widget-specific properties (text for Button/Label, value/items for
    /// input widgets, min/max for sliders, etc.) are applied before boxing.
    fn create_widget(
        widget_type: &str,
        obj: &serde_json::Map<String, Value>,
    ) -> Result<Box<dyn Widget>, String> {
        let geometry = Rect::new(0, 0, 100, 100);
        match widget_type.to_lowercase().as_str() {
            "window" => {
                let title = obj.get("title").and_then(|v| v.as_str()).unwrap_or("Window");
                Ok(Box::new(Window::new(title.to_string(), geometry)))
            }
            "button" => {
                let text = obj.get("text").and_then(|v| v.as_str()).unwrap_or("");
                Ok(Box::new(Button::new(text.to_string(), geometry)))
            }
            "label" => {
                let text = obj.get("text").and_then(|v| v.as_str()).unwrap_or("");
                let mut label = Label::new(text.to_string(), geometry);
                // alignment: "left"|"center"|"right"|"top"|"bottom"
                if let Some(align) = obj.get("alignment").and_then(|v| v.as_str()) {
                    label.set_alignment(match align {
                        "center" => Alignment::Center,
                        "right" => Alignment::Right,
                        "top" => Alignment::Top,
                        "bottom" => Alignment::Bottom,
                        _ => Alignment::Left,
                    });
                }
                Ok(Box::new(label))
            }
            "checkbox" => {
                let mut cb = CheckBox::new(geometry);
                if let Some(checked) = obj.get("checked").and_then(|v| v.as_bool()) {
                    cb.set_checked(checked);
                }
                // tristate: enables partial check state
                if let Some(tri) = obj.get("tristate").and_then(|v| v.as_bool()) {
                    cb.set_tristate_enabled(tri);
                }
                Ok(Box::new(cb))
            }
            "radiobutton" => {
                let mut rb = RadioButton::new(geometry);
                if let Some(checked) = obj.get("checked").and_then(|v| v.as_bool()) {
                    rb.set_checked(checked);
                }
                // group_id: logical group name for mutual exclusion
                if let Some(gid) = obj.get("group_id").and_then(|v| v.as_str()) {
                    if !gid.is_empty() {
                        rb.set_group_id(Some(gid.to_string()));
                    }
                }
                Ok(Box::new(rb))
            }
            "lineedit" => {
                let mut le = LineEdit::new(geometry);
                if let Some(value) = obj.get("value").and_then(|v| v.as_str()) {
                    le.set_text(value.to_string());
                }
                if let Some(placeholder) = obj.get("placeholder").and_then(|v| v.as_str()) {
                    le.set_placeholder_text(placeholder.to_string());
                }
                if let Some(max_len) = obj.get("max_length").and_then(|v| v.as_u64()) {
                    le.set_max_length(Some(max_len as usize));
                }
                if let Some(password) = obj.get("password").and_then(|v| v.as_bool()) {
                    if password {
                        le.set_echo_mode(crate::widget::EchoMode::Password);
                    }
                }
                Ok(Box::new(le))
            }
            #[cfg(not(alloc_frugal))]
            "textedit" => {
                let mut te = TextEdit::new(geometry);
                if let Some(value) = obj.get("value").and_then(|v| v.as_str()) {
                    te.set_text(value.to_string());
                }
                if let Some(placeholder) = obj.get("placeholder").and_then(|v| v.as_str()) {
                    te.set_placeholder_text(placeholder.to_string());
                }
                if let Some(max_len) = obj.get("max_length").and_then(|v| v.as_u64()) {
                    te.set_max_length(Some(max_len as usize));
                }
                if let Some(read_only) = obj.get("read_only").and_then(|v| v.as_bool()) {
                    te.set_read_only(read_only);
                }
                if let Some(word_wrap) = obj.get("word_wrap").and_then(|v| v.as_bool()) {
                    te.set_line_wrap(word_wrap);
                }
                Ok(Box::new(te))
            }
            "combobox" => {
                let mut cb = ComboBox::new(geometry);
                if let Some(items) = obj.get("items").and_then(|v| v.as_array()) {
                    for item in items {
                        if let Some(text) = item.as_str() {
                            cb.add_item(text.to_string());
                        }
                    }
                }
                // current_index: pre-select an item by index (0-based)
                if let Some(idx) = obj.get("current_index").and_then(|v| v.as_u64()) {
                    cb.set_current_index(Some(idx as usize));
                }
                // editable: allow user to type custom text
                if let Some(ed) = obj.get("editable").and_then(|v| v.as_bool()) {
                    cb.set_editable(ed);
                }
                // max_visible_items: dropdown max rows
                if let Some(max) = obj.get("max_visible_items").and_then(|v| v.as_u64()) {
                    cb.set_max_visible_items(max as usize);
                }
                Ok(Box::new(cb))
            }
            "listbox" => {
                let mut lb = ListBox::new(geometry);
                if let Some(items) = obj.get("items").and_then(|v| v.as_array()) {
                    for item in items {
                        if let Some(text) = item.as_str() {
                            lb.add_item(text.to_string());
                        }
                    }
                }
                if let Some(mode) = obj.get("selection_mode").and_then(|v| v.as_str()) {
                    match mode {
                        "none" => lb.set_selection_mode(crate::widget::SelectionMode::None),
                        "single" => lb.set_selection_mode(crate::widget::SelectionMode::Single),
                        "multi" => lb.set_selection_mode(crate::widget::SelectionMode::Multi),
                        "extended" => lb.set_selection_mode(crate::widget::SelectionMode::Extended),
                        // Unknown value; use widget default
                        _ => {}
                    }
                }
                Ok(Box::new(lb))
            }
            "slider" => {
                let mut sl = Slider::new(geometry);
                let (min, max) = read_json_range(obj);
                if let Some(min) = min {
                    sl.set_range(min as i32, max.unwrap_or(100) as i32);
                } else if let Some(max) = max {
                    sl.set_maximum(max as i32);
                }
                if let Some(value) = obj.get("value").and_then(|v| v.as_i64()) {
                    sl.set_value(value as i32);
                }
                if let Some(orientation) = obj.get("orientation").and_then(|v| v.as_str()) {
                    match orientation {
                        "horizontal" => sl.set_orientation(Orientation::Horizontal),
                        "vertical" => sl.set_orientation(Orientation::Vertical),
                        // Unknown value; use widget default
                        _ => {}
                    }
                }
                // single_step: keyboard arrow increment
                if let Some(step) = obj.get("single_step").and_then(|v| v.as_u64()) {
                    sl.set_single_step(step as i32);
                }
                // page_step: PgUp/PgDn increment
                if let Some(step) = obj.get("page_step").and_then(|v| v.as_u64()) {
                    sl.set_page_step(step as i32);
                }
                // tick_position: "none"|"above"|"below"|"both"
                if let Some(pos) = obj.get("tick_position").and_then(|v| v.as_str()) {
                    match pos {
                        "above" => sl.set_tick_position(
                            crate::widget::display_widgets::slider::TickPosition::TicksAbove,
                        ),
                        "below" => sl.set_tick_position(
                            crate::widget::display_widgets::slider::TickPosition::TicksBelow,
                        ),
                        "both" => sl.set_tick_position(
                            crate::widget::display_widgets::slider::TickPosition::TicksBothSides,
                        ),
                        // Unknown value; use widget default
                        _ => {}
                    }
                }
                // tick_interval: interval between tick marks
                if let Some(iv) = obj.get("tick_interval").and_then(|v| v.as_u64()) {
                    sl.set_tick_interval(iv as i32);
                }
                // tracking: emit value_changed while dragging (default: true)
                if let Some(tr) = obj.get("tracking").and_then(|v| v.as_bool()) {
                    sl.set_tracking(tr);
                }
                Ok(Box::new(sl))
            }
            "scrollbar" => {
                let mut sb = ScrollBar::new(geometry);
                let (min, max) = read_json_range(obj);
                if let Some(min) = min {
                    sb.set_range(min as i32, max.unwrap_or(100) as i32);
                } else if let Some(max) = max {
                    sb.set_maximum(max as i32);
                }
                if let Some(value) = obj.get("value").and_then(|v| v.as_i64()) {
                    sb.set_value(value as i32);
                }
                if let Some(orientation) = obj.get("orientation").and_then(|v| v.as_str()) {
                    match orientation {
                        "horizontal" => sb.set_orientation(Orientation::Horizontal),
                        "vertical" => sb.set_orientation(Orientation::Vertical),
                        // Unknown value; use widget default
                        _ => {}
                    }
                }
                // single_step: arrow button increment
                if let Some(step) = obj.get("single_step").and_then(|v| v.as_u64()) {
                    sb.set_single_step(step as i32);
                }
                // page_step: click-track increment
                if let Some(step) = obj.get("page_step").and_then(|v| v.as_u64()) {
                    sb.set_page_step(step as i32);
                }
                Ok(Box::new(sb))
            }
            "progressbar" => {
                let mut pb = ProgressBar::new(geometry);
                let (min, max) = read_json_range(obj);
                if let Some(min) = min {
                    pb.set_range(min as i32, max.unwrap_or(100) as i32);
                } else if let Some(max) = max {
                    pb.set_maximum(max as i32);
                }
                if let Some(value) = obj.get("value").and_then(|v| v.as_i64()) {
                    pb.set_value(value as i32);
                }
                // text_visible: show percentage text overlay
                if let Some(tv) = obj.get("text_visible").and_then(|v| v.as_bool()) {
                    pb.set_text_visible(tv);
                }
                // orientation: "horizontal"|"vertical"
                if let Some(orient) = obj.get("orientation").and_then(|v| v.as_str()) {
                    match orient {
                        "vertical" => pb.set_orientation(Orientation::Vertical),
                        _ => pb.set_orientation(Orientation::Horizontal),
                    }
                }
                // inverted_appearance: fill from right/bottom
                if let Some(inv) = obj.get("inverted_appearance").and_then(|v| v.as_bool()) {
                    pb.set_inverted_appearance(inv);
                }
                Ok(Box::new(pb))
            }
            "switch" | "toggle" => {
                let mut sw = Switch::new(geometry);
                if let Some(checked) = obj.get("checked").and_then(|v| v.as_bool()) {
                    sw.set_checked(checked);
                }
                Ok(Box::new(sw))
            }
            "groupbox" | "panel" => {
                let mut gb = GroupBox::new(geometry);
                if let Some(title) = obj.get("title").and_then(|v| v.as_str()) {
                    if !title.is_empty() {
                        gb.set_title(title.to_string());
                    }
                }
                // alignment: title text alignment
                if let Some(align) = obj.get("alignment").and_then(|v| v.as_str()) {
                    match align {
                        "center" => gb.set_alignment(Alignment::Center),
                        "right" => gb.set_alignment(Alignment::Right),
                        _ => gb.set_alignment(Alignment::Left),
                    }
                }
                // checkable: add a checkbox to the group box title
                if let Some(chk) = obj.get("checkable").and_then(|v| v.as_bool()) {
                    gb.set_checkable(chk);
                }
                // checked: initial checked state (only if checkable)
                if let Some(chk) = obj.get("checked").and_then(|v| v.as_bool()) {
                    if gb.is_checkable() || obj.get("checkable").is_none() {
                        gb.set_checked(chk);
                    }
                }
                Ok(Box::new(gb))
            }
            #[cfg(not(alloc_frugal))]
            "tabwidget" => {
                let mut tw = TabWidget::new(geometry);
                if let Some(index) = obj.get("current_index").and_then(|v| v.as_u64()) {
                    tw.set_current_index(index as usize);
                }
                // tab_position: "north"|"south"|"west"|"east"
                if let Some(pos) = obj.get("tab_position").and_then(|v| v.as_str()) {
                    match pos {
                        "south" => tw.set_tab_position(
                            crate::widget::container_widgets::tabwidget::TabPosition::South,
                        ),
                        "west" => tw.set_tab_position(
                            crate::widget::container_widgets::tabwidget::TabPosition::West,
                        ),
                        "east" => tw.set_tab_position(
                            crate::widget::container_widgets::tabwidget::TabPosition::East,
                        ),
                        // Unknown value; use widget default
                        _ => {}
                    }
                }
                // tab_shape: "rounded"|"triangular"|"rectangular"
                if let Some(shape) = obj.get("tab_shape").and_then(|v| v.as_str()) {
                    match shape {
                        "triangular" => tw.set_tab_shape(
                            crate::widget::container_widgets::tabwidget::TabShape::Triangular,
                        ),
                        "rectangular" => tw.set_tab_shape(
                            crate::widget::container_widgets::tabwidget::TabShape::Rectangular,
                        ),
                        // Unknown value; use widget default
                        _ => {}
                    }
                }
                // closable: show close buttons on tabs
                if let Some(cl) = obj.get("closable").and_then(|v| v.as_bool()) {
                    tw.set_closable(cl);
                }
                // movable: allow drag-reordering of tabs
                if let Some(mv) = obj.get("movable").and_then(|v| v.as_bool()) {
                    tw.set_movable(mv);
                }
                Ok(Box::new(tw))
            }
            #[cfg(not(alloc_frugal))]
            "grid" => {
                let mut grid = GridWidget::new(geometry);
                if let Some(rows) = obj.get("rows").and_then(|v| v.as_u64()) {
                    grid.set_rows(rows as u32);
                }
                if let Some(cols) = obj.get("columns").and_then(|v| v.as_u64()) {
                    grid.set_columns(cols as u32);
                }
                if let Some(spacing) = obj.get("spacing").and_then(|v| v.as_u64()) {
                    grid.set_spacing(spacing as u32);
                }
                if let Some(color_str) = obj.get("line_color").and_then(|v| v.as_str()) {
                    if let Some(color) = Color::parse_hex(color_str) {
                        grid.set_line_color(Some(color));
                    }
                }
                Ok(Box::new(grid))
            }
            "spinbox" => {
                let mut sb = SpinBox::new(geometry);
                let (min, max) = read_json_range(obj);
                if let Some(min) = min {
                    sb.set_minimum(min as i32);
                }
                if let Some(max) = max {
                    sb.set_maximum(max as i32);
                }
                if let Some(value) = obj.get("value").and_then(|v| v.as_i64()) {
                    sb.set_value(value as i32);
                }
                if let Some(step) = obj.get("single_step").and_then(|v| v.as_u64()) {
                    sb.set_single_step(step as i32);
                }
                if let Some(prefix) = obj.get("prefix").and_then(|v| v.as_str()) {
                    sb.set_prefix(prefix.to_string());
                }
                if let Some(suffix) = obj.get("suffix").and_then(|v| v.as_str()) {
                    sb.set_suffix(suffix.to_string());
                }
                if let Some(wrap) = obj.get("wrapping").and_then(|v| v.as_bool()) {
                    sb.set_wrapping(wrap);
                }
                Ok(Box::new(sb))
            }
            #[cfg(not(alloc_frugal))]
            "listview" => Ok(Box::new(ListView::new(geometry))),
            "scrollarea" => {
                let mut sa = ScrollArea::new(geometry);
                if let Some(resizable) = obj.get("widget_resizable").and_then(|v| v.as_bool()) {
                    sa.set_widget_resizable(resizable);
                }
                if let Some(align) = obj.get("alignment").and_then(|v| v.as_str()) {
                    match align {
                        "center" => sa.set_alignment(Alignment::Center),
                        "right" => sa.set_alignment(Alignment::Right),
                        _ => sa.set_alignment(Alignment::Left),
                    }
                }
                // h_policy / v_policy: "always_on"|"always_off"|"as_needed"
                if let Some(policy) = obj.get("h_policy").and_then(|v| v.as_str()) {
                    sa.set_horizontal_scroll_bar_policy(match policy {
                        "always_on" => {
                            crate::widget::container_widgets::scrollarea::ScrollBarPolicy::AlwaysOn
                        }
                        "always_off" => {
                            crate::widget::container_widgets::scrollarea::ScrollBarPolicy::AlwaysOff
                        }
                        _ => {
                            crate::widget::container_widgets::scrollarea::ScrollBarPolicy::AsNeeded
                        }
                    });
                }
                if let Some(policy) = obj.get("v_policy").and_then(|v| v.as_str()) {
                    sa.set_vertical_scroll_bar_policy(match policy {
                        "always_on" => {
                            crate::widget::container_widgets::scrollarea::ScrollBarPolicy::AlwaysOn
                        }
                        "always_off" => {
                            crate::widget::container_widgets::scrollarea::ScrollBarPolicy::AlwaysOff
                        }
                        _ => {
                            crate::widget::container_widgets::scrollarea::ScrollBarPolicy::AsNeeded
                        }
                    });
                }
                Ok(Box::new(sa))
            }
            "frame" => {
                use crate::widget::base_widgets::frame::Frame;
                let mut frame = Frame::new(geometry);
                if let Some(shape) = obj.get("frame_shape").and_then(|v| v.as_str()) {
                    match shape {
                        "no_frame" => frame.set_frame_shape(
                            crate::widget::base_widgets::frame::FrameShape::NoFrame,
                        ),
                        "panel" => frame
                            .set_frame_shape(crate::widget::base_widgets::frame::FrameShape::Panel),
                        "styled_panel" => frame.set_frame_shape(
                            crate::widget::base_widgets::frame::FrameShape::StyledPanel,
                        ),
                        "hline" => frame
                            .set_frame_shape(crate::widget::base_widgets::frame::FrameShape::HLine),
                        "vline" => frame
                            .set_frame_shape(crate::widget::base_widgets::frame::FrameShape::VLine),
                        "win_panel" => frame.set_frame_shape(
                            crate::widget::base_widgets::frame::FrameShape::WinPanel,
                        ),
                        _ => frame
                            .set_frame_shape(crate::widget::base_widgets::frame::FrameShape::Box),
                    }
                }
                if let Some(shadow) = obj.get("frame_shadow").and_then(|v| v.as_str()) {
                    match shadow {
                        "raised" => frame.set_frame_shadow(
                            crate::widget::base_widgets::frame::FrameShadow::Raised,
                        ),
                        "sunken" => frame.set_frame_shadow(
                            crate::widget::base_widgets::frame::FrameShadow::Sunken,
                        ),
                        // Unknown value; use widget default
                        _ => {}
                    }
                }
                if let Some(lw) = obj.get("line_width").and_then(|v| v.as_f64()) {
                    frame.set_line_width(lw as f32);
                }
                Ok(Box::new(frame))
            }
            #[cfg(not(alloc_frugal))]
            "messagebox" => {
                let mut mb = MessageBox::new(geometry);
                if let Some(title) = obj.get("title").and_then(|v| v.as_str()) {
                    if !title.is_empty() {
                        mb.set_title(title.to_string());
                    }
                }
                if let Some(text) = obj.get("text").and_then(|v| v.as_str()) {
                    if !text.is_empty() {
                        mb.set_text(text.to_string());
                    }
                }
                if let Some(icon) = obj.get("icon").and_then(|v| v.as_str()) {
                    match icon {
                        "information" => mb.set_icon(
                            crate::widget::dialog::message_box::MessageBoxIcon::Information,
                        ),
                        "question" => mb
                            .set_icon(crate::widget::dialog::message_box::MessageBoxIcon::Question),
                        "warning" => {
                            mb.set_icon(crate::widget::dialog::message_box::MessageBoxIcon::Warning)
                        }
                        "critical" => mb
                            .set_icon(crate::widget::dialog::message_box::MessageBoxIcon::Critical),
                        _ => {
                            mb.set_icon(crate::widget::dialog::message_box::MessageBoxIcon::NoIcon)
                        }
                    }
                }
                Ok(Box::new(mb))
            }
            #[cfg(not(alloc_frugal))]
            "filedialog" => {
                let mut fd = FileDialog::new(geometry);
                if let Some(mode) = obj.get("mode").and_then(|v| v.as_str()) {
                    match mode {
                        "open_files" => fd.set_mode(
                            crate::widget::dialog::file_dialog::FileDialogMode::OpenFiles,
                        ),
                        "save_file" => fd
                            .set_mode(crate::widget::dialog::file_dialog::FileDialogMode::SaveFile),
                        "select_directory" => fd.set_mode(
                            crate::widget::dialog::file_dialog::FileDialogMode::SelectDirectory,
                        ),
                        _ => fd
                            .set_mode(crate::widget::dialog::file_dialog::FileDialogMode::OpenFile),
                    }
                }
                if let Some(title) = obj.get("title").and_then(|v| v.as_str()) {
                    if !title.is_empty() {
                        fd.set_title(title.to_string());
                    }
                }
                if let Some(dir) = obj.get("directory").and_then(|v| v.as_str()) {
                    if !dir.is_empty() {
                        fd.set_directory(dir.to_string());
                    }
                }
                Ok(Box::new(fd))
            }
            #[cfg(not(alloc_frugal))]
            "colordialog" => {
                let mut cd = ColorDialog::new(geometry);
                if let Some(alpha) = obj.get("alpha").and_then(|v| v.as_bool()) {
                    cd.set_options_alpha(alpha);
                }
                if let Some(color_str) = obj.get("value").and_then(|v| v.as_str()) {
                    if let Some(color) = Color::parse_hex(color_str) {
                        cd.set_current_color(color);
                    }
                }
                Ok(Box::new(cd))
            }
            #[cfg(not(alloc_frugal))]
            "fontdialog" => {
                let mut fd = FontDialog::new(geometry);
                if let Some(font_str) = obj.get("value").and_then(|v| v.as_str()) {
                    if !font_str.is_empty() {
                        match crate::core::Font::parse(font_str) {
                            Some(font) => fd.set_current_font(font),
                            // The string was supplied and could not be understood. Say
                            // so and name it, rather than substituting a default as if
                            // the request had been honoured — the caller's value was
                            // previously read and then silently thrown away. This
                            // mirrors `colordialog` above, which falls through on an
                            // unparsable colour instead of pretending to apply it.
                            None => log::warn!(
                                "fontdialog: cannot parse font {font_str:?}; expected \
                                 \"<family> <size>[ bold][ italic]\". Keeping the dialog's \
                                 own current font."
                            ),
                        }
                    }
                }
                Ok(Box::new(fd))
            }
            _ => {
                // Not one of the widget types this arm table knows how to
                // configure. Before giving up, ask the capability registry: it
                // holds a constructor for every registered control, so a control
                // added to the library becomes reachable from JSON without an edit
                // here. The registry-built control gets its scalar properties from
                // the name-driven pass in `apply_properties`, which is why this
                // fallback does not need to reproduce any of the setters above.
                //
                // A build without the registry (a stripped profile) answers `None`
                // and the error below is reported, which is the truth there.
                let factory = crate::json::schema_factory();
                if let Some(widget) = factory.create(widget_type, geometry, "") {
                    return Ok(widget);
                }
                Err(format!(
                    "unknown widget type '{widget_type}'; it is neither a built-in JSON widget \
                     name nor a name registered with the widget factory"
                ))
            }
        }
    }
}

/// The widget's kind in `Debug` spelling, for diagnostics.
///
/// A free function rather than a trait method: only this module's warnings need
/// it, and the kind is already reachable through `Widget::kind`.
fn kind_label(widget: &dyn Widget) -> String {
    format!("{:?}", widget.kind())
}

/// Apply declarative stylesheet rules to a freshly created widget.
///
/// Four sources, applied in increasing precedence so a more specific source wins:
///
/// 1. The **active theme** resolved for the node's class (or kind). This is the
///    base appearance every control starts from; without it each control kept the
///    colours its constructor hardcoded and a theme switch had no effect.
/// 2. The **global stylesheet manager**'s registered sheets, in their own
///    priority order. This is the app-wide CSS layer.
/// 3. An inline `"css"` string on the node itself. Page-local rules beat
///    app-wide ones, which is what makes a one-off layout possible.
///
/// Matching uses the widget's kind plus the node's optional `"class"` and `"id"`,
/// so a rule written as `Button.primary` or `#ok_btn` selects the intended node.
/// The widget's kind is formatted in the `Debug` spelling the CSS selector parser
/// expects (`Button`, not `button`).
///
/// Each layer is merged *under* whatever the widget already has, so the explicit
/// JSON keys applied after this function always win. A malformed stylesheet is
/// reported and skipped: the widget is still created, because failing the whole
/// load over one bad rule would hide the rest of the layout.
fn apply_declared_styles(widget: &mut dyn Widget, obj: &serde_json::Map<String, Value>) {
    let kind = kind_label(widget);
    let class = obj.get("class").and_then(|v| v.as_str());
    let id = obj.get("id").and_then(|v| v.as_str());

    // 1. Active theme. The widget's **kind** determines its visual role; a node's
    //    `class` is only an override key, never a role name. Passing the class here used to
    //    replace the kind, so `<button class="primary">` was classified as `Surface` (because
    //    "primary" is not a control kind) and painted as a grey panel instead of a filled
    //    brand-coloured button — the class silently discarded the role it was meant to select.
    if let Some(theme_style) = crate::theme::resolved_theme_style_for(&kind, class) {
        let mut style = widget.style().clone();
        style.merge(&theme_style);
        widget.set_style(style);
    }

    // 2. App-wide sheets, respecting their registered priority.
    let mut style = widget.style().clone();
    let applied = {
        let manager = crate::style::global_stylesheet_manager();
        manager.apply_to(&kind, class, id, None, &mut style)
    };
    if let Err(error) = applied {
        log::warn!(
            "JSON layout: a global stylesheet failed to apply to {kind} (class {class:?}, id \
             {id:?}): {error}"
        );
    } else {
        widget.set_style(style);
    }

    // 3. Page-local inline CSS on this node.
    if let Some(css) = obj.get("css").and_then(|v| v.as_str()) {
        match widget.apply_css(css, class) {
            Ok(()) => {}
            Err(error) => log::warn!(
                "JSON layout: the inline \"css\" on {kind} (id {id:?}) could not be applied: \
                 {error}"
            ),
        }
    }
}

/// Apply common widget properties from a JSON object.
///
/// Two layers, in this order:
///
/// 1. **Name-driven** — every key that the control's own property contract
///    publishes is written through [`crate::json::properties`], so a property
///    added to any control is addressable from JSON with no change here. This is
///    what makes the loader cover every `WidgetKind` variant rather than a
///    hand-maintained subset — the kind is resolved from the capability schema, not
///    from a list kept in this file, so it cannot drift as controls are added.
/// 2. **Loader-owned** — keys that describe the style object as a whole (`padding`
///    / `margin` accept a number *or* a four-sided object), the geometry shorthand,
///    and the min/max size constraints, which have no single-property equivalent.
///
/// A key that neither layer recognises is reported as a warning naming the key and
/// the widget, so a typo (`"colour"` for `"color"`) is visible instead of loading
/// a silently default-styled control.
fn apply_properties(widget: &mut dyn Widget, obj: &serde_json::Map<String, Value>) {
    // ── Geometry ────────────────────────────────────────────
    // Applied first because the property layer also publishes `geometry`, and a
    // control's own setter is the authority; the shorthand below fills in the
    // common case of four separate keys.
    if let (Some(x), Some(y), Some(w), Some(h)) = (
        obj.get("x").and_then(|v| v.as_i64()),
        obj.get("y").and_then(|v| v.as_i64()),
        obj.get("width").and_then(|v| v.as_u64()),
        obj.get("height").and_then(|v| v.as_u64()),
    ) {
        widget.set_geometry(Rect::from_i64(x, y, w as i64, h as i64));
    }

    // ── Style: padding / margin ─────────────────────────────
    // These two accept either a bare number (all sides) or an object with
    // top/right/bottom/left, which no single property name can express. They are
    // handled before the name-driven pass so the structured form is not rejected
    // as a type error by a property expecting a scalar.
    apply_style_padding(widget, obj, "padding", |widget, value| {
        let mut style = widget.style().clone();
        style.padding = value;
        widget.set_style(style);
    });
    if let Some(value) = obj.get("margin") {
        if let Some(p) = parse_spacing(value) {
            let margin = crate::style::Margin::new(p.top, p.right, p.bottom, p.left);
            let mut style = widget.style().clone();
            style.margin = margin;
            widget.set_style(style);
        }
    }

    // ── Name-driven pass ────────────────────────────────────
    // Iterate the JSON keys rather than a fixed list: that is what lets a control
    // whose properties this module has never seen be configured from JSON.
    for (key, value) in obj {
        if is_loader_owned_key(key) {
            continue;
        }
        match crate::json::properties::apply_widget_property(widget, key, value) {
            ApplyOutcome::Applied => {}
            // The control does not publish this name. It may still be a
            // construction-time key the caller's own arm consumed (`items`, …),
            // so this is a warning rather than an error: the load still succeeds,
            // but the typo is visible.
            ApplyOutcome::NotAProperty => {
                log::warn!(
                    "JSON layout: {key:?} is not a property of this {} and no construction arm \
                     consumed it; the value ({value}) was ignored",
                    kind_label(widget)
                );
            }
            ApplyOutcome::Rejected => {
                log::warn!(
                    "JSON layout: property {key:?} of this {} rejected the value {value} (wrong \
                     JSON type, or the property is read-only)",
                    kind_label(widget)
                );
            }
        }
    }

    // ── Style: colors written as plain JSON strings ──────────
    // These are the documented JSON spellings. They are separate from the
    // name-driven pass because JSON carries a colour as a `#RRGGBB` string while
    // the property contract transports it as a value the control parses itself;
    // routing them here keeps the JSON surface stable for existing layouts.
    apply_hex_color(widget, obj, "background", |widget, color| {
        widget.set_background_color(Some(color))
    });
    apply_hex_color(widget, obj, "text_color", |widget, color| {
        widget.set_foreground_color(Some(color))
    });
    apply_hex_color(widget, obj, "border_color", |widget, color| {
        widget.set_border_color(Some(color))
    });

    // ── Style: border width / radius ────────────────────────
    if let Some(bw) = obj.get("border_width").and_then(|v| v.as_u64()) {
        widget.set_border_width(bw as u32);
    }
    if let Some(br) = obj.get("border_radius").and_then(|v| v.as_u64()) {
        widget.set_border_radius(br as u32);
    }

    // ── Size constraints ────────────────────────────────────
    apply_size_constraints(widget, obj);
}

/// Keys this module consumes structurally, so the name-driven pass must not also
/// try to resolve them as properties.
///
/// # Why the list is exhaustive and tested
///
/// A key appearing here is a claim that the loader has its own (possibly richer)
/// handling for it. The converse matters just as much: a key a `create_widget` arm
/// reads but that is *absent* from this list makes the name-driven pass report
/// ``was ignored'' about a value the arm already applied — a wrong diagnostic that
/// sends an author chasing a non-bug. Six keys were in exactly that state
/// (`tristate`, `password`, `word_wrap`, `tab_shape`, `h_policy`, `v_policy`,
/// `alpha`), because the arm-level reads and this list are maintained separately.
///
/// `every_arm_consumed_key_is_loader_owned` in the tests extracts the arm keys from
/// this file and asserts each one is listed here, so the two cannot drift apart
/// again.
fn is_loader_owned_key(key: &str) -> bool {
    matches!(
        key,
        // Geometry shorthand (four keys form one geometry).
        "x" | "y" | "width" | "height"
        // Structured spacing (a number *or* a four-sided object).
        | "padding" | "margin"
        // Colours in JSON `#RRGGBB` form; applied through the dedicated hex path.
        | "background" | "text_color" | "border_color"
        | "border_width" | "border_radius"
        // Size constraints read as a group.
        | "min_width" | "min_height" | "max_width" | "max_height"
        // Identity and wiring, consumed by `instantiate_node`.
        | "id" | "text" | "title" | "class" | "css" | "tooltip"
        // Construction-time keys owned by a `create_widget` arm or the layout
        // machinery: arrays and sub-objects that describe the widget's content
        // rather than a scalar state property.
        | "children" | "layout" | "items" | "stretch"
        // Construction-time scalar keys a `create_widget` arm reads directly, under
        // a spelling that is deliberately *not* the control's property name (an arm
        // may need to translate a JSON word into an enum, or set two fields from
        // one key). Each one is applied by its arm, so the name-driven pass must
        // leave it alone rather than warn about it:
        //   tristate  → checkbox.set_tristate_enabled
        //   password  → lineedit.set_echo_mode
        //   word_wrap → textedit.set_line_wrap
        //   tab_shape → tabwidget.set_tab_shape
        //   h_policy / v_policy → scrollarea.set_*_scroll_bar_policy
        //   alpha     → colordialog.set_options_alpha
        | "tristate" | "password" | "word_wrap" | "tab_shape"
        | "h_policy" | "v_policy" | "alpha"
        // Events, wired after registration. The `events` object holds published names (rule
        // #101's merged route) and the `on_*` keys are the compatibility spellings; the key list
        // comes from `event_route::MARKER_KEYS` so a key the wiring reads can never be missing
        // here and be reported as an unknown property.
        | "events"
        | "on_click" | "on_change" | "on_close" | "on_double_click" | "on_focus"
        | "on_blur" | "on_selection_changed" | "on_value_changed"
    )
}

/// Apply a `#RRGGBB`-style colour key when it is present and parses.
///
/// A colour that does not parse is reported: silently keeping the previous colour
/// is how a layout ends up looking almost right with no indication why.
fn apply_hex_color(
    widget: &mut dyn Widget,
    obj: &serde_json::Map<String, Value>,
    key: &str,
    apply: fn(&mut dyn Widget, Color),
) {
    let Some(raw) = obj.get(key).and_then(|v| v.as_str()) else {
        return;
    };
    match Color::parse_hex(raw) {
        Some(color) => apply(widget, color),
        None => log::warn!(
            "JSON layout: colour {raw:?} for {key:?} on this {} is not a #RGB/#RRGGBB/\
             #RRGGBBAA literal and was ignored",
            kind_label(widget)
        ),
    }
}

fn json_geometry(obj: &serde_json::Map<String, Value>) -> Rect {
    Rect::from_i64(
        obj.get("x").and_then(|value| value.as_i64()).unwrap_or(0),
        obj.get("y").and_then(|value| value.as_i64()).unwrap_or(0),
        obj.get("width").and_then(|value| value.as_i64()).unwrap_or(100),
        obj.get("height").and_then(|value| value.as_i64()).unwrap_or(100),
    )
}

/// Reads a numeric range from JSON, preferring the names the control publishes.
///
/// `slider`, `scrollbar`, `progressbar` and `spinbox` publish
/// `minimum`/`maximum` (see their `PropertySchema` rows), so those are the
/// documented spellings. Their arms used to read `min`/`max` only — names none of
/// those four controls publishes — which produced two problems:
///
/// * `min`/`max` were not resolvable by the name-driven pass either, so an author
///   using them got a *"no construction arm consumed it; the value was ignored"*
///   warning about a value the arm had just applied;
/// * `min`/`max` **do** name a real property on `cupertino_slider`, where they are
///   `Float`. One spelling therefore meant an integer range on four controls and a
///   float pair on a fifth, with no documented reason.
///
/// Both spellings are accepted here, with the published name winning, so existing
/// layouts keep working while the canonical form is what the schema advertises.
fn read_json_range(obj: &serde_json::Map<String, Value>) -> (Option<i64>, Option<i64>) {
    let read = |published: &str, alias: &str| {
        obj.get(published).or_else(|| obj.get(alias)).and_then(|value| value.as_i64())
    };
    (read("minimum", "min"), read("maximum", "max"))
}

/// Apply min/max size constraints from JSON object.
fn apply_size_constraints(widget: &mut dyn Widget, obj: &serde_json::Map<String, Value>) {
    let min_w = obj.get("min_width").and_then(|v| v.as_u64());
    let min_h = obj.get("min_height").and_then(|v| v.as_u64());
    let max_w = obj.get("max_width").and_then(|v| v.as_u64());
    let max_h = obj.get("max_height").and_then(|v| v.as_u64());

    if min_w.is_some() || min_h.is_some() {
        let current = widget.min_size().unwrap_or(crate::core::Size::new(0, 0));
        widget.set_min_size(Some(crate::core::Size::new(
            min_w.unwrap_or(current.width as u64) as u32,
            min_h.unwrap_or(current.height as u64) as u32,
        )));
    }
    if max_w.is_some() || max_h.is_some() {
        let current = widget.max_size().unwrap_or(crate::core::Size::new(u32::MAX, u32::MAX));
        widget.set_max_size(Some(crate::core::Size::new(
            max_w.unwrap_or(current.width as u64) as u32,
            max_h.unwrap_or(current.height as u64) as u32,
        )));
    }
}

/// Parse a padding/margin value from JSON: either a single number
/// (applied to all sides) or an object with top/right/bottom/left keys.
fn parse_spacing(value: &Value) -> Option<crate::style::Padding> {
    match value {
        Value::Number(n) => {
            let v = n.as_u64()?.try_into().ok()?;
            Some(crate::style::Padding::all(v))
        }
        Value::Object(map) => {
            let top = map.get("top").and_then(|v| v.as_u64()).unwrap_or(0) as u32;
            let right = map.get("right").and_then(|v| v.as_u64()).unwrap_or(0) as u32;
            let bottom = map.get("bottom").and_then(|v| v.as_u64()).unwrap_or(0) as u32;
            let left = map.get("left").and_then(|v| v.as_u64()).unwrap_or(0) as u32;
            if top == 0 && right == 0 && bottom == 0 && left == 0 {
                None
            } else {
                Some(crate::style::Padding::new(top, right, bottom, left))
            }
        }
        _ => None,
    }
}

/// Apply a padding property to a widget.
fn apply_style_padding(
    widget: &mut dyn Widget,
    obj: &serde_json::Map<String, Value>,
    key: &str,
    apply: fn(&mut dyn Widget, crate::style::Padding),
) {
    if let Some(value) = obj.get(key) {
        if let Some(padding) = parse_spacing(value) {
            apply(widget, padding);
        }
    }
}

/// The `on_*` handler keys a JSON node may declare, with the marker each one means.
///
/// # Why the tuple-returning extractors were deleted (BLUE19 T-8)
///
/// This used to be two functions returning `(Option<String>, ...)` tuples that the loader
/// destructured positionally: `on_click`/`on_change` from one, and six more from the other. Two
/// problems, both of which the table below removes:
///
/// 1. **Positional coupling.** A key added to `extract_extended_event_handlers` but not to its
///    return type — or read in a different order at the call site — silently wired a handler to
///    the wrong trigger. Nothing could detect it, because the tuple has no names.
/// 2. **Two sources of truth.** The loader also listed all eight keys by hand in its
///    "not a property" pattern, so the extraction set and the key set could disagree.
///
/// The list now lives once, in [`crate::json::MARKER_KEYS`], and is read by name.
///
/// The re-export is `#[cfg(test)]` because production code reaches the table through
/// `crate::json::MARKER_KEYS` directly; only this module's tests need it in scope.
#[cfg(test)]
pub use crate::json::event_route::MARKER_KEYS;

/// The name→kind table, retained for tests only.
///
/// # Why it is no longer used in production
///
/// Registration reads the **live control's** `kind()` instead (see
/// `instantiate_node`). This table is a hand-written subset of the names the factory
/// routes, and its `_ => WidgetKind::Button` fallback meant any name it did not list
/// — `icon`, `chip`, `table`, `progress_bar`, … — was recorded as a `Button`, so the
/// widget registry disagreed with the tree the loader had just built.
///
/// It is kept under `#[cfg(test)]` because two tests assert properties *of the old
/// table* to demonstrate the fix (that a control's real kind differs from this
/// fallback). Deleting it would delete the evidence that the defect existed.
#[cfg(test)]
fn infer_kind(widget_type: &str) -> WidgetKind {
    match widget_type.to_lowercase().as_str() {
        // Non-gated variants (available in all profiles)
        "arc" => WidgetKind::Arc,
        "button" => WidgetKind::Button,
        "checkbox" => WidgetKind::CheckBox,
        "combobox" => WidgetKind::ComboBox,
        "dropdown" => WidgetKind::Dropdown,
        "frame" => WidgetKind::Frame,
        "groupbox" => WidgetKind::GroupBox,
        "imageview" => WidgetKind::ImageView,
        "keyboard" => WidgetKind::Keyboard,
        "label" => WidgetKind::Label,
        "line" => WidgetKind::Line,
        "lineedit" => WidgetKind::LineEdit,
        "listbox" => WidgetKind::ListBox,
        "meter" => WidgetKind::Meter,
        "minicanvas" => WidgetKind::MiniCanvas,
        "minichart" => WidgetKind::MiniChart,
        #[cfg(not(alloc_frugal))]
        "colorpicker" => WidgetKind::ColorPicker,
        #[cfg(not(alloc_frugal))]
        "toast" => WidgetKind::Toast,
        #[cfg(not(alloc_frugal))]
        "splashscreen" => WidgetKind::SplashScreen,
        "candlestick_chart" => WidgetKind::CandlestickChart,
        "candlestick" => WidgetKind::CandlestickChart,
        "kline" => WidgetKind::CandlestickChart,
        "k_line" => WidgetKind::CandlestickChart,
        "k_line_chart" => WidgetKind::CandlestickChart,
        "ohlc_chart" => WidgetKind::CandlestickChart,
        "volume_chart" => WidgetKind::VolumeChart,
        "volume" => WidgetKind::VolumeChart,
        "volume_histogram" => WidgetKind::VolumeChart,
        "volume_bars" => WidgetKind::VolumeChart,
        "depth_chart" => WidgetKind::DepthChart,
        "market_depth" => WidgetKind::DepthChart,
        "depth_graph" => WidgetKind::DepthChart,
        "liquidity_chart" => WidgetKind::DepthChart,
        "order_book" => WidgetKind::OrderBook,
        "orderbook" => WidgetKind::OrderBook,
        "book_ladder" => WidgetKind::OrderBook,
        "market_depth_ladder" => WidgetKind::OrderBook,
        "quote_board" => WidgetKind::QuoteBoard,
        "quotes" => WidgetKind::QuoteBoard,
        "watchlist" => WidgetKind::QuoteBoard,
        "quote_table" => WidgetKind::QuoteBoard,
        "market_watch" => WidgetKind::QuoteBoard,
        "indicator_chart" => WidgetKind::IndicatorChart,
        "indicator" => WidgetKind::IndicatorChart,
        "technical_indicator" => WidgetKind::IndicatorChart,
        "oscillator" => WidgetKind::IndicatorChart,
        "macd_chart" => WidgetKind::IndicatorChart,
        "panel" => WidgetKind::Panel,
        "progressbar" => WidgetKind::ProgressBar,
        "radiobutton" => WidgetKind::RadioButton,
        "roller" => WidgetKind::Roller,
        "scrollarea" => WidgetKind::ScrollArea,
        "scrollbar" => WidgetKind::ScrollBar,
        "slider" => WidgetKind::Slider,
        "spinner" => WidgetKind::Spinner,
        "spinbox" => WidgetKind::SpinBox,
        "switch" => WidgetKind::Switch,
        "textarea" => WidgetKind::TextArea,
        "window" => WidgetKind::Window,
        // cfg(not(alloc_frugal)) variants
        #[cfg(not(alloc_frugal))]
        "autocompleteedit" => WidgetKind::AutoCompleteEdit,
        #[cfg(not(alloc_frugal))]
        "barchart" => WidgetKind::BarChart,
        #[cfg(not(alloc_frugal))]
        "calendar" => WidgetKind::Calendar,
        #[cfg(not(alloc_frugal))]
        "canvas" => WidgetKind::Canvas,
        #[cfg(not(alloc_frugal))]
        "chart" => WidgetKind::Chart,
        #[cfg(not(alloc_frugal))]
        "colordialog" => WidgetKind::ColorDialog,
        #[cfg(not(alloc_frugal))]
        "contextmenu" => WidgetKind::ContextMenu,
        #[cfg(not(alloc_frugal))]
        "dialog" => WidgetKind::Dialog,
        #[cfg(not(alloc_frugal))]
        "dockpanel" => WidgetKind::DockPanel,
        #[cfg(not(alloc_frugal))]
        "dropdownmenu" => WidgetKind::DropdownMenu,
        #[cfg(not(alloc_frugal))]
        "filedialog" => WidgetKind::FileDialog,
        #[cfg(not(alloc_frugal))]
        "floatinglabel" => WidgetKind::FloatingLabel,
        #[cfg(not(alloc_frugal))]
        "fontdialog" => WidgetKind::FontDialog,
        #[cfg(not(alloc_frugal))]
        "grid" => WidgetKind::Grid,
        #[cfg(not(alloc_frugal))]
        "icon" => WidgetKind::Icon,
        #[cfg(not(alloc_frugal))]
        "inputdialog" => WidgetKind::InputDialog,
        #[cfg(not(alloc_frugal))]
        "linechart" => WidgetKind::LineChart,
        #[cfg(not(alloc_frugal))]
        "listview" => WidgetKind::ListView,
        #[cfg(not(alloc_frugal))]
        "maskededit" => WidgetKind::MaskedEdit,
        #[cfg(not(alloc_frugal))]
        "mdiarea" => WidgetKind::MdiArea,
        #[cfg(not(alloc_frugal))]
        "menu" => WidgetKind::Menu,
        #[cfg(not(alloc_frugal))]
        "menubar" => WidgetKind::MenuBar,
        #[cfg(not(alloc_frugal))]
        "menubutton" => WidgetKind::MenuButton,
        #[cfg(not(alloc_frugal))]
        "menuitem" => WidgetKind::MenuItem,
        #[cfg(not(alloc_frugal))]
        "messagebox" => WidgetKind::MessageBox,
        #[cfg(not(alloc_frugal))]
        "multiselectcombobox" => WidgetKind::MultiSelectComboBox,
        #[cfg(not(alloc_frugal))]
        "piechart" => WidgetKind::PieChart,
        #[cfg(not(alloc_frugal))]
        "popover" => WidgetKind::Popover,
        #[cfg(not(alloc_frugal))]
        "popupwindow" => WidgetKind::PopupWindow,
        #[cfg(not(alloc_frugal))]
        "progresscircle" => WidgetKind::ProgressCircle,
        #[cfg(not(alloc_frugal))]
        "rangeslider" => WidgetKind::RangeSlider,
        #[cfg(not(alloc_frugal))]
        "rating" => WidgetKind::Rating,
        #[cfg(not(alloc_frugal))]
        "refreshcontrol" => WidgetKind::RefreshControl,
        #[cfg(not(alloc_frugal))]
        "richedit" => WidgetKind::RichEdit,
        #[cfg(not(alloc_frugal))]
        "searchbar" => WidgetKind::SearchBar,
        #[cfg(not(alloc_frugal))]
        "segmentedbutton" => WidgetKind::SegmentedButton,
        #[cfg(not(alloc_frugal))]
        "sparkline" => WidgetKind::Sparkline,
        #[cfg(not(alloc_frugal))]
        "splitter" => WidgetKind::Splitter,
        #[cfg(not(alloc_frugal))]
        "statusbar" => WidgetKind::StatusBar,
        #[cfg(not(alloc_frugal))]
        "stepper" => WidgetKind::Stepper,
        #[cfg(not(alloc_frugal))]
        "tabbar" => WidgetKind::TabBar,
        #[cfg(not(alloc_frugal))]
        "table" => WidgetKind::Table,
        #[cfg(not(alloc_frugal))]
        "tabwidget" => WidgetKind::TabWidget,
        #[cfg(not(alloc_frugal))]
        "textedit" => WidgetKind::TextEdit,
        #[cfg(not(alloc_frugal))]
        "togglebutton" => WidgetKind::ToggleButton,
        #[cfg(not(alloc_frugal))]
        "toolbar" => WidgetKind::ToolBar,
        #[cfg(not(alloc_frugal))]
        "tooltip" => WidgetKind::Tooltip,
        #[cfg(not(alloc_frugal))]
        "treeview" => WidgetKind::TreeView,
        _ => WidgetKind::Button,
    }
}

/// Parse a JSON layout string into a widget tree.
///
/// This is a convenience wrapper around [`JsonLoader::load`].
pub fn load_layout_from_str(json_str: &str) -> Result<BoundJsonLayout, String> {
    JsonLoader::load(json_str)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn load_valid_minimal_window() {
        let json = r#"{"window": {"id": "main", "title": "Test", "width": 400, "height": 300}}"#;
        let result = JsonLoader::load(json);
        assert!(result.is_ok(), "Expected Ok, got: {:?}", result.err());
        let layout = result.unwrap();
        assert_eq!(layout.len(), 1);
        assert!(layout.id("main").is_some(), "Expected Some for widget id 'main'");
    }

    #[test]
    fn load_button_with_text() {
        let json = r#"{"window": {"id": "w", "title": "Window", "width": 400, "height": 300, "layout": {"type": "vbox", "children": [{"button": {"id": "btn", "text": "Click Me"}}]}}}"#;
        let result = JsonLoader::load(json);
        assert!(result.is_ok(), "Expected Ok, got: {:?}", result.err());
        let layout = result.unwrap();
        assert!(layout.id("btn").is_some());
    }

    /// A `fontdialog`'s declared `value` must reach the dialog.
    ///
    /// # Why this test exists
    ///
    /// The `fontdialog` arm used to read `value`, discard it, and call
    /// `set_current_font(Font::default())` — with a comment claiming font parsing
    /// was unavailable. A caller writing `"value": "Monospace 20"` silently got
    /// Arial 14 and no diagnostic. The sibling `colordialog` arm parses its own
    /// `value` correctly, so the asymmetry was the bug.
    ///
    /// The loader's arm calls `FontDialog::set_current_font`, and the round trip
    /// through the live widget is the part that was never asserted. This test drives
    /// the same call the loader makes with the same parse primitive it now uses, so a
    /// regression to a constant default fails here.
    #[cfg(not(alloc_frugal))]
    #[test]
    fn a_font_dialog_receives_the_font_parsed_from_its_declared_value() {
        let spec = "Monospace 20 bold";
        let mut dialog = crate::widget::dialog::FontDialog::new(Rect::new(0, 0, 400, 300));
        dialog.set_current_font(
            crate::core::Font::parse(spec).expect("the loader's parser must read this"),
        );
        assert_eq!(dialog.current_font().family(), "Monospace");
        assert_eq!(dialog.current_font().size(), 20.0);
        assert!(dialog.current_font().is_bold());

        // The value the old code substituted is measurably different, so this test
        // cannot pass against the old behaviour.
        assert_ne!(dialog.current_font(), &crate::core::Font::default());
    }

    /// An unparsable `value` must leave the dialog's own font alone.
    #[cfg(not(alloc_frugal))]
    #[test]
    fn a_font_dialog_keeps_its_own_font_when_the_declared_value_is_unparsable() {
        let mut dialog = crate::widget::dialog::FontDialog::new(Rect::new(0, 0, 400, 300));
        let before = dialog.current_font().clone();
        // This is the branch the loader takes instead of substituting a default.
        if let Some(font) = crate::core::Font::parse("not a font at all") {
            dialog.set_current_font(font);
        }
        assert_eq!(dialog.current_font(), &before, "the dialog must keep its own font");
    }

    /// Every key a `create_widget` arm reads must be resolvable by the layer that
    /// runs next.
    ///
    /// # Why this test exists
    ///
    /// After the arm table builds a control, `apply_properties` walks the JSON keys a
    /// second time and reports any it cannot resolve. A key read by an arm is
    /// therefore fine only if **either**
    ///
    /// 1. the control publishes it as a property, so the name-driven pass applies it
    ///    a second time (harmlessly — same value), or
    /// 2. it is listed in [`is_loader_owned_key`], which tells the pass to skip it.
    ///
    /// A key that is neither gets a *"no construction arm consumed it; the value was
    /// ignored"* warning — about a value the arm just applied. The author then hunts
    /// a non-bug. `tristate`, `password`, `word_wrap`, `tab_shape`, `h_policy`,
    /// `v_policy` and `alpha` were all in exactly that state: read by an arm, absent
    /// from the list, and not published by their controls.
    ///
    /// This test parses the loader's own arm table, so it cannot drift: adding
    /// `obj.get("new_key")` to an arm without either publishing it on the control or
    /// listing it here fails.
    #[test]
    fn every_arm_consumed_key_is_either_published_or_loader_owned() {
        let source = include_str!("loader.rs");
        let start = source
            .find("    fn create_widget(")
            .expect("the arm table must exist; if it was renamed, fix this test");
        // The arm table ends where the next top-level `    fn ` begins.
        let rest = &source[start + 1..];
        let end = rest.find("\n    fn ").map(|offset| start + 1 + offset).unwrap_or(source.len());
        let arms = &source[start..end];

        // Every capability's published property names, as one set of strings. The
        // schema tables are the authority on what the name-driven pass can resolve.
        let factory = crate::widget::WidgetFactory::new_with_defaults();
        let mut published: alloc::collections::BTreeSet<&str> = alloc::collections::BTreeSet::new();
        for capability in factory.capabilities() {
            for schema in capability.properties {
                published.insert(schema.name);
            }
        }

        let mut unresolved: alloc::vec::Vec<&str> = alloc::vec::Vec::new();
        for (offset, _) in arms.match_indices("obj.get(\"") {
            let remainder = &arms[offset + "obj.get(\"".len()..];
            let Some(close) = remainder.find('"') else { continue };
            let name = &remainder[..close];
            if !published.contains(name) && !is_loader_owned_key(name) {
                unresolved.push(name);
            }
        }
        unresolved.sort_unstable();
        unresolved.dedup();

        assert!(
            unresolved.is_empty(),
            "these keys are read by a `create_widget` arm but are neither published as \
             properties nor listed in `is_loader_owned_key`, so the name-driven pass \
             will log a false \"was ignored\" warning about them: {unresolved:?}"
        );
    }

    /// A declarative layout must actually *arrange* its children, not merely parse.
    ///
    /// # Why this test exists
    ///
    /// `store_layout` used to run after the child loop, so every child was registered
    /// against a layout that did not exist yet (`add_widget_to_layout` is a no-op in
    /// that case). The array parsed, the layout was built, `apply_layout` ran and
    /// returned nothing, and two children stayed at their declared overlapping
    /// positions — with no error anywhere. Every existing test passed, because they all
    /// asserted that loading succeeded rather than where the widgets ended up.
    ///
    /// # Why this asserts the applied geometries
    ///
    /// An earlier version of this test read `preview_layout` and passed even with the
    /// old ordering restored, because the layout still ended up stored — just too late
    /// to hear about its children, and therefore empty. `preview_layout` on an empty
    /// layout answers with an empty list, which is what `apply_layout` returned too,
    /// so the assertion has to be on the geometry the layout *computed for the children
    /// it was given*: two entries, stacked.
    #[test]
    fn a_vbox_layout_positions_its_children_below_one_another() {
        let json = r#"{"window": {"id": "w", "title": "W", "width": 400, "height": 300,
            "layout": {"type": "vbox", "spacing": 4, "children": [
                {"label": {"id": "first", "text": "one", "width": 100, "height": 20}},
                {"label": {"id": "second", "text": "two", "width": 100, "height": 20}}
            ]}}}"#;
        let loaded = JsonLoader::load(json).expect("the document must load");
        let window = loaded.id("w").expect("the window");
        let first = loaded.id("first").expect("the first label");
        let second = loaded.id("second").expect("the second label");

        let geometries =
            crate::layout::declarative::preview_layout(window, Rect::new(0, 0, 400, 300));
        assert_eq!(
            geometries.len(),
            2,
            "both children must reach the layout; an empty list means they were added \
             before it existed"
        );

        let rect_of = |id| {
            geometries
                .iter()
                .find(|(child, _)| *child == id)
                .map(|(_, rect)| *rect)
                .unwrap_or_else(|| panic!("child {id} was never laid out"))
        };
        let first_rect = rect_of(first);
        let second_rect = rect_of(second);

        assert!(
            second_rect.y > first_rect.y,
            "a vbox must stack its children: first at {first_rect:?}, second at {second_rect:?}"
        );
        assert_eq!(
            first_rect.x, second_rect.x,
            "a vbox keeps one column: {first_rect:?} vs {second_rect:?}"
        );

        crate::layout::declarative::forget_layout(window);
    }

    /// The sibling of the above for `hbox`: side by side, same row.
    ///
    /// A single orientation test could pass with the axes swapped, so both directions
    /// are pinned.
    #[test]
    fn an_hbox_layout_positions_its_children_side_by_side() {
        let json = r#"{"window": {"id": "w", "title": "W", "width": 400, "height": 300,
            "layout": {"type": "hbox", "spacing": 4, "children": [
                {"label": {"id": "left", "text": "L", "width": 60, "height": 20}},
                {"label": {"id": "right", "text": "R", "width": 60, "height": 20}}
            ]}}}"#;
        let loaded = JsonLoader::load(json).expect("the document must load");
        let window = loaded.id("w").expect("the window");
        let left = loaded.id("left").expect("the left label");
        let right = loaded.id("right").expect("the right label");

        let geometries =
            crate::layout::declarative::preview_layout(window, Rect::new(0, 0, 400, 100));
        assert_eq!(
            geometries.len(),
            2,
            "both children must reach the layout; an empty list means they were added \
             before it existed"
        );

        let rect_of = |id| {
            geometries
                .iter()
                .find(|(child, _)| *child == id)
                .map(|(_, rect)| *rect)
                .unwrap_or_else(|| panic!("child {id} was never laid out"))
        };
        let left_rect = rect_of(left);
        let right_rect = rect_of(right);

        assert!(
            right_rect.x > left_rect.x,
            "an hbox must place children left to right: {left_rect:?} then {right_rect:?}"
        );
        assert_eq!(
            left_rect.y, right_rect.y,
            "an hbox keeps one row: {left_rect:?} vs {right_rect:?}"
        );

        crate::layout::declarative::forget_layout(window);
    }

    #[test]
    fn load_label_with_alignment() {
        let json = r#"{"window": {"id": "w", "title": "Window", "width": 400, "height": 300, "layout": {"type": "vbox", "children": [{"label": {"id": "lbl", "text": "Hello", "alignment": "center"}}]}}}"#;
        let result = JsonLoader::load(json);
        assert!(result.is_ok(), "Expected Ok, got: {:?}", result.err());
    }

    #[test]
    fn load_nested_layouts() {
        let json = r#"{"window": {"id": "w", "title": "Nested", "width": 500, "height": 400, "layout": {"type": "vbox", "children": [{"layout": {"type": "hbox", "children": [{"button": {"id": "b1", "text": "One"}}, {"button": {"id": "b2", "text": "Two"}}]}}, {"label": {"id": "footer", "text": "Footer"}}]}}}"#;
        let result = JsonLoader::load(json);
        assert!(result.is_ok(), "Expected Ok, got: {:?}", result.err());
        let layout = result.unwrap();
        assert!(layout.id("b1").is_some());
        assert!(layout.id("b2").is_some());
        assert!(layout.id("footer").is_some());
    }

    #[test]
    fn load_spacer_widget() {
        let json = r#"{"window": {"id": "w", "title": "Spacer", "width": 400, "height": 300, "layout": {"type": "vbox", "children": [{"button": {"id": "b1", "text": "Top"}}, {"spacer": {"stretch": 1}}, {"button": {"id": "b2", "text": "Bottom"}}]}}}"#;
        let result = JsonLoader::load(json);
        assert!(result.is_ok(), "Expected Ok, got: {:?}", result.err());
    }

    #[test]
    fn load_roundtrip_fields() {
        let json = r#"{"window": {"id": "main", "title": "Roundtrip", "width": 800, "height": 600, "layout": {"type": "grid", "columns": 2, "spacing": 4, "margin": 2, "children": [{"button": {"id": "ok", "text": "OK", "x": 0, "y": 0, "width": 80, "height": 30, "visible": true, "enabled": true}}, {"label": {"id": "info", "text": "Info", "visible": true}}]}}}"#;
        let result = JsonLoader::load(json);
        assert!(result.is_ok(), "Expected Ok, got: {:?}", result.err());
        let layout = result.unwrap();
        assert!(layout.id("main").is_some());
        assert!(layout.id("ok").is_some());
        assert!(layout.id("info").is_some());
        assert_eq!(layout.len(), 3);
    }

    #[test]
    fn load_invalid_json_returns_error() {
        let json = r#"{"window": {"id": "broken" "title": "Bad"}"#;
        let result = JsonLoader::load(json);
        assert!(result.is_err());
        let err = result.unwrap_err();
        // The message must name the input (its size) and say the parse failed.
        assert!(err.contains("could not be parsed"), "Expected parse error, got: {}", err);
        assert!(err.contains("bytes"), "Expected the size to be named, got: {}", err);
    }

    #[test]
    fn load_empty_string_returns_error() {
        let result = JsonLoader::load("");
        assert!(result.is_err());
    }

    #[test]
    fn load_not_an_object_returns_error() {
        let json = r#""just a string""#;
        let result = JsonLoader::load(json);
        assert!(result.is_err());
    }

    #[test]
    fn load_array_root_returns_error() {
        let json = r#"["a", "b"]"#;
        let result = JsonLoader::load(json);
        assert!(result.is_err());
    }

    #[test]
    fn load_multiple_root_keys_returns_error() {
        let json = r#"{"window": {"title": "A"}, "button": {"text": "B"}}"#;
        let result = JsonLoader::load(json);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.contains("one widget type"), "Expected 'one widget type' error, got: {}", err);
    }

    #[test]
    fn load_unknown_widget_type_returns_error() {
        let json = r#"{"bogus_widget": {"id": "x"}}"#;
        let result = JsonLoader::load(json);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.contains("unknown widget type"),
            "Expected unknown widget type error, got: {}",
            err
        );
    }

    #[test]
    fn load_missing_id_still_works() {
        let json = r#"{"window": {"title": "No ID", "width": 300, "height": 200}}"#;
        let result = JsonLoader::load(json);
        assert!(result.is_ok(), "Expected Ok, got: {:?}", result.err());
        let layout = result.unwrap();
        assert_eq!(layout.len(), 0, "Without 'id', no entries should be registered");
    }

    #[test]
    fn every_marker_key_is_extractable_from_a_node() {
        // The table is the single list the loader reads, so this asserts the property that used to
        // be split across two tuple-returning functions: every declared key is found, by name, at
        // the marker it says it has.
        for (key, marker) in MARKER_KEYS {
            assert_eq!(
                crate::json::marker_for_key(key),
                Some(*marker),
                "`{key}` must extract as its own marker"
            );
        }
    }

    #[test]
    fn a_node_declaring_no_event_key_yields_nothing() {
        let map = serde_json::Map::new();
        assert!(crate::json::marker_key_names().all(|key| map.get(key).is_none()));
    }

    #[test]
    fn the_loader_consumes_exactly_the_marker_keys() {
        // The "not a property" pattern and the event wiring must agree, because a key in one and
        // not the other is either a warning about a live key or a silently ignored handler.
        let source = include_str!("loader.rs");
        for (key, _) in MARKER_KEYS {
            assert!(
                source.contains(&format!("\"{key}\"")),
                "`{key}` is read by the marker table but is not named in the loader's pattern"
            );
        }
    }

    #[test]
    fn load_layout_from_str_convenience() {
        let json = r#"{"window": {"id": "w", "title": "Conv", "width": 400, "height": 300}}"#;
        let result = load_layout_from_str(json);
        assert!(result.is_ok());
    }

    #[test]
    fn load_widget_with_tooltip_and_style() {
        let json = r##"{"window": {"id": "w", "title": "Style", "width": 400, "height": 300, "visible": true, "enabled": true, "layout": {"type": "vbox", "children": [{"button": {"id": "styled_btn", "text": "Styled", "tooltip": "A styled button", "background": "#ff0000", "text_color": "#ffffff", "border_color": "#000000", "border_width": 2, "border_radius": 5, "min_width": 100, "min_height": 30}}]}}}"##;
        let result = JsonLoader::load(json);
        assert!(result.is_ok(), "Expected Ok, got: {:?}", result.err());
    }

    #[test]
    fn load_spinbox_with_all_properties() {
        let json = r#"{"window": {"id": "w", "title": "Spin", "width": 400, "height": 300, "layout": {"type": "vbox", "children": [{"spinbox": {"id": "sb", "min": 0, "max": 100, "value": 50, "single_step": 5, "prefix": "$", "suffix": " USD", "wrapping": true}}]}}}"#;
        let result = JsonLoader::load(json);
        assert!(result.is_ok(), "Expected Ok, got: {:?}", result.err());
    }

    #[test]
    fn load_grid_widget_with_properties() {
        let json = r#"{"window": {"id": "w", "title": "Grid", "width": 600, "height": 400, "layout": {"type": "vbox", "children": [{"grid": {"id": "g", "rows": 3, "columns": 4, "spacing": 5}}]}}}"#;
        let result = JsonLoader::load(json);
        assert!(result.is_ok(), "Expected Ok, got: {:?}", result.err());
    }

    #[test]
    fn load_empty_children_array() {
        let json = r#"{"window": {"id": "w", "title": "Empty", "width": 400, "height": 300, "layout": {"type": "vbox", "children": []}}}"#;
        let result = JsonLoader::load(json);
        assert!(result.is_ok(), "Expected Ok, got: {:?}", result.err());
    }

    #[test]
    fn load_window_default_title() {
        let json = r#"{"window": {"id": "w", "width": 400, "height": 300}}"#;
        let result = JsonLoader::load(json);
        assert!(result.is_ok(), "Expected Ok, got: {:?}", result.err());
    }

    #[test]
    fn load_checkbox_with_checked() {
        let json = r#"{"window": {"id": "w", "title": "Check", "width": 400, "height": 300, "layout": {"type": "vbox", "children": [{"checkbox": {"id": "cb", "text": "Enable feature", "checked": true, "tristate": true}}]}}}"#;
        let result = JsonLoader::load(json);
        assert!(result.is_ok(), "Expected Ok, got: {:?}", result.err());
    }

    #[test]
    fn load_lineedit_with_all_properties() {
        let json = r#"{"window": {"id": "w", "title": "Edit", "width": 400, "height": 300, "layout": {"type": "vbox", "children": [{"lineedit": {"id": "le", "value": "initial", "placeholder": "Type here...", "max_length": 100, "password": true}}]}}}"#;
        let result = JsonLoader::load(json);
        assert!(result.is_ok(), "Expected Ok, got: {:?}", result.err());
    }

    #[test]
    fn load_slider_with_range() {
        let json = r#"{"window": {"id": "w", "title": "Slider", "width": 400, "height": 300, "layout": {"type": "vbox", "children": [{"slider": {"id": "sl", "min": 0, "max": 200, "value": 75, "orientation": "horizontal", "single_step": 5, "page_step": 20, "tracking": true}}]}}}"#;
        let result = JsonLoader::load(json);
        assert!(result.is_ok(), "Expected Ok, got: {:?}", result.err());
    }

    /// Both the published range names and the `min`/`max` aliases must resolve.
    ///
    /// # Why this test exists
    ///
    /// The arms read `min`/`max` only, but `slider`/`scrollbar`/`progressbar`/
    /// `spinbox` publish `minimum`/`maximum`. So an author writing the documented
    /// spelling got *no* range applied by the arm, and an author writing `min`/`max`
    /// got the range applied but a false "was ignored" warning. Neither failure is
    /// visible from `is_ok()`, which is all `load_slider_with_range` asserts.
    ///
    /// This drives `read_json_range` directly: the loader's layout is an id index
    /// and does not retain the controls, so the applied value cannot be read back
    /// through it.
    #[test]
    fn a_range_resolves_under_both_the_published_name_and_the_alias() {
        let parse = |json: &str| {
            let value: Value = serde_json::from_str(json).expect("probe JSON must parse");
            let obj = value.as_object().expect("probe must be an object").clone();
            read_json_range(&obj)
        };

        // The published spelling.
        assert_eq!(parse(r#"{"minimum": 0, "maximum": 200}"#), (Some(0), Some(200)));
        // The alias the arms used to require.
        assert_eq!(parse(r#"{"min": 5, "max": 15}"#), (Some(5), Some(15)));
        // Mixed, and the published name wins when both are present.
        assert_eq!(parse(r#"{"minimum": 1, "min": 9}"#), (Some(1), None));
        assert_eq!(parse(r#"{"maximum": 7, "max": 3}"#), (None, Some(7)));
        // Absent keys resolve to nothing rather than to a made-up default.
        assert_eq!(parse(r#"{}"#), (None, None));
    }

    #[test]
    fn load_progressbar_with_properties() {
        let json = r#"{"window": {"id": "w", "title": "Progress", "width": 400, "height": 300, "layout": {"type": "vbox", "children": [{"progressbar": {"id": "pb", "min": 0, "max": 100, "value": 50, "orientation": "horizontal", "text_visible": true, "inverted_appearance": false}}]}}}"#;
        let result = JsonLoader::load(json);
        assert!(result.is_ok(), "Expected Ok, got: {:?}", result.err());
    }

    #[test]
    fn load_combobox_with_items() {
        let json = r#"{"window": {"id": "w", "title": "Combo", "width": 400, "height": 300, "layout": {"type": "vbox", "children": [{"combobox": {"id": "cb", "items": ["One", "Two", "Three"], "current_index": 1, "editable": true, "max_visible_items": 10}}]}}}"#;
        let result = JsonLoader::load(json);
        assert!(result.is_ok(), "Expected Ok, got: {:?}", result.err());
    }

    #[test]
    fn load_listbox_with_selection_mode() {
        let json = r#"{"window": {"id": "w", "title": "List", "width": 400, "height": 300, "layout": {"type": "vbox", "children": [{"listbox": {"id": "lb", "items": ["A", "B", "C"], "selection_mode": "multi"}}]}}}"#;
        let result = JsonLoader::load(json);
        assert!(result.is_ok(), "Expected Ok, got: {:?}", result.err());
    }

    #[test]
    fn load_scrollarea_with_policies() {
        let json = r#"{"window": {"id": "w", "title": "Scroll", "width": 400, "height": 300, "layout": {"type": "vbox", "children": [{"scrollarea": {"id": "sa", "widget_resizable": true, "h_policy": "always_on", "v_policy": "as_needed"}}]}}}"#;
        let result = JsonLoader::load(json);
        assert!(result.is_ok(), "Expected Ok, got: {:?}", result.err());
    }

    #[test]
    fn load_frame_with_shape_and_shadow() {
        let json = r#"{"window": {"id": "w", "title": "Frame", "width": 400, "height": 300, "layout": {"type": "vbox", "children": [{"frame": {"id": "f", "frame_shape": "panel", "frame_shadow": "raised", "line_width": 2.0}}]}}}"#;
        let result = JsonLoader::load(json);
        assert!(result.is_ok(), "Expected Ok, got: {:?}", result.err());
    }

    #[cfg(not(alloc_frugal))]
    #[test]
    fn load_tabwidget_with_properties() {
        let json = r#"{"window": {"id": "w", "title": "Tabs", "width": 500, "height": 400, "layout": {"type": "vbox", "children": [{"tabwidget": {"id": "tw", "current_index": 0, "tab_position": "north", "closable": true, "movable": false}}]}}}"#;
        let result = JsonLoader::load(json);
        assert!(result.is_ok(), "Expected Ok, got: {:?}", result.err());
    }

    #[cfg(not(alloc_frugal))]
    #[test]
    fn load_textedit_with_readonly() {
        let json = r#"{"window": {"id": "w", "title": "Text", "width": 400, "height": 300, "layout": {"type": "vbox", "children": [{"textedit": {"id": "te", "value": "Multi\nline", "read_only": true, "word_wrap": true}}]}}}"#;
        let result = JsonLoader::load(json);
        assert!(result.is_ok(), "Expected Ok, got: {:?}", result.err());
    }

    #[test]
    fn load_radiobutton_with_group() {
        let json = r#"{"window": {"id": "w", "title": "Radio", "width": 400, "height": 300, "layout": {"type": "vbox", "children": [{"radiobutton": {"id": "rb1", "text": "Option A", "checked": true, "group_id": "group1"}}, {"radiobutton": {"id": "rb2", "text": "Option B", "group_id": "group1"}}]}}}"#;
        let result = JsonLoader::load(json);
        assert!(result.is_ok(), "Expected Ok, got: {:?}", result.err());
    }

    #[test]
    fn load_groupbox_with_title() {
        let json = r#"{"window": {"id": "w", "title": "Group", "width": 400, "height": 300, "layout": {"type": "vbox", "children": [{"groupbox": {"id": "gb", "title": "Settings", "checkable": true, "checked": true}}]}}}"#;
        let result = JsonLoader::load(json);
        assert!(result.is_ok(), "Expected Ok, got: {:?}", result.err());
    }

    #[cfg(not(alloc_frugal))]
    #[test]
    fn load_filedialog_with_mode() {
        let json = r#"{"window": {"id": "w", "title": "Dialog", "width": 400, "height": 300, "layout": {"type": "vbox", "children": [{"filedialog": {"id": "fd", "mode": "save_file", "directory": "/tmp"}}]}}}"#;
        let result = JsonLoader::load(json);
        assert!(result.is_ok(), "Expected Ok, got: {:?}", result.err());
    }

    #[cfg(not(alloc_frugal))]
    #[test]
    fn load_colordialog_with_color() {
        let json = r##"{"window": {"id": "w", "title": "Color", "width": 400, "height": 300, "layout": {"type": "vbox", "children": [{"colordialog": {"id": "cd", "value": "#ff0000", "alpha": true}}]}}}"##;
        let result = JsonLoader::load(json);
        assert!(result.is_ok(), "Expected Ok, got: {:?}", result.err());
    }

    #[cfg(not(alloc_frugal))]
    #[test]
    fn load_messagebox_with_icon() {
        let json = r#"{"window": {"id": "w", "title": "Msg", "width": 400, "height": 300, "layout": {"type": "vbox", "children": [{"messagebox": {"id": "mb", "title": "Warning", "text": "Are you sure?", "icon": "warning"}}]}}}"#;
        let result = JsonLoader::load(json);
        assert!(result.is_ok(), "Expected Ok, got: {:?}", result.err());
    }

    #[cfg(not(alloc_frugal))]
    #[test]
    fn load_listview_widget() {
        let json = r#"{"window": {"id": "w", "title": "ListView", "width": 400, "height": 300, "layout": {"type": "vbox", "children": [{"listview": {"id": "lv"}}]}}}"#;
        let result = JsonLoader::load(json);
        assert!(result.is_ok(), "Expected Ok, got: {:?}", result.err());
    }

    // ── The framework-routed path (factory fallback + name-driven properties) ──

    /// A control with **no** hand-written arm in `create_widget` still loads,
    /// because the fallback asks the capability registry. `"icon"` is the sharpest
    /// case: `infer_kind` has always been able to name it, but before the fallback
    /// the loader refused to build it.
    #[cfg(full_widgets)]
    #[test]
    fn a_control_with_no_hand_written_arm_loads_via_the_factory() {
        let json = r#"{"window": {"id": "w", "title": "T", "width": 400, "height": 300, "layout": {"type": "vbox", "children": [{"icon": {"id": "ic", "icon_name": "star", "size": 48}}]}}}"#;
        let layout = JsonLoader::load(json).expect("a control the factory knows must load");
        assert!(layout.id("ic").is_some(), "the icon must be registered by its JSON id");
    }

    /// The kind a factory-routed control registers must match what `infer_kind`
    /// says, otherwise the registry and the live widget disagree. Checked through
    /// the registry's own kind, not by re-running `infer_kind` (which would be
    /// circular).
    #[cfg(full_widgets)]
    #[test]
    fn a_factory_routed_control_registers_its_real_kind() {
        let json = r#"{"window": {"id": "w", "title": "T", "width": 400, "height": 300, "layout": {"type": "vbox", "children": [{"rating": {"id": "rt", "value": 3}}]}}}"#;
        JsonLoader::load(json).expect("rating must load");
        assert_eq!(
            infer_kind("rating"),
            crate::index::WidgetKind::Rating,
            "the kind mapping must name the real variant"
        );
    }

    /// Every control the factory can build must register under its **own** kind.
    ///
    /// # Why this test exists
    ///
    /// `infer_kind` is a hand-written table of about a hundred names, but the factory
    /// routes many more. Everything the table did not name fell through to
    /// `_ => WidgetKind::Button`, so an `icon`, `chip`, `progress_bar` or `tag_input`
    /// node was registered as a `Button` — the widget registry, and therefore
    /// `LayoutInspector`'s diagnostics and any `by_kind` query, disagreed with the
    /// tree the loader had just built.
    ///
    /// The previous test asserted only `infer_kind("rating") == Rating`, which is a
    /// tautology over the very table that was incomplete. This one asserts the
    /// invariant that matters: the kind now recorded comes from the live control, so
    /// for the names below — deliberately chosen to be **absent** from `infer_kind`'s
    /// table — the table's answer and the control's answer must differ, proving the
    /// registration no longer trusts the table.
    #[test]
    fn every_factory_routed_control_registers_its_own_kind() {
        let factory = crate::widget::WidgetFactory::new_with_defaults();
        // `infer_kind`'s fallback arm, i.e. what these names used to be recorded as.
        let table_fallback = infer_kind("definitely_not_a_widget_name");
        assert_eq!(
            table_fallback,
            crate::index::WidgetKind::Button,
            "if the fallback changes, these assertions need revisiting"
        );

        let mut mislabelled_by_the_table = 0usize;
        for widget_type in ["icon", "chip", "progress_bar", "tag_input", "scroll_area"] {
            let expected = factory
                .create(widget_type, Rect::new(0, 0, 10, 10), "probe")
                .unwrap_or_else(|| panic!("the factory must build {widget_type:?}"))
                .kind();

            // The invariant the loader now relies on: a control knows its own kind.
            assert_ne!(
                expected, table_fallback,
                "{widget_type:?} happens to equal the table fallback, so this name \
                 no longer demonstrates the fix"
            );

            if infer_kind(widget_type) == table_fallback {
                mislabelled_by_the_table += 1;
            }

            // And the loader must register that real kind. The registry the loader
            // fills is not reachable after `load`, so the observable equivalent is
            // that the control it built reports the right kind — which is what the
            // registration now reads.
            let json = format!(
                r#"{{"window": {{"id": "w", "title": "T", "width": 400, "height": 300,
                    "layout": {{"type": "vbox", "children": [
                        {{"{widget_type}": {{"id": "probe"}}}}
                    ]}}}}}}"#
            );
            let layout =
                JsonLoader::load(&json).unwrap_or_else(|error| panic!("{widget_type}: {error:?}"));
            assert!(
                layout.id("probe").is_some(),
                "{widget_type:?} must be registered under its JSON id"
            );
        }

        assert!(
            mislabelled_by_the_table > 0,
            "none of the probed names is missing from `infer_kind`, so this test no \
             longer covers the defect it was written for"
        );
    }

    /// A property the loader has no branch for is applied through the control's
    /// own property contract. This is the behaviour that makes the JSON surface
    /// track the widget library instead of a hand-maintained key list.
    #[cfg(full_widgets)]
    #[test]
    fn a_property_with_no_loader_branch_is_still_applied() {
        use crate::widget::capability::{widget_property_get, CapabilityValue};
        use crate::widget::Icon;

        let mut widget: Box<dyn Widget> = JsonLoader::create_widget(
            "icon",
            &serde_json::json!({"icon_name": "heart"}).as_object().unwrap().clone(),
        )
        .expect("icon must be constructible");
        // Before the name-driven pass this write had no branch and the value was
        // dropped; now the contract carries it.
        apply_properties(
            &mut *widget,
            serde_json::json!({"icon_name": "heart"}).as_object().unwrap(),
        );
        assert_eq!(
            widget_property_get(&*widget, "icon_name"),
            Ok(CapabilityValue::String("heart".to_string())),
            "icon_name must reach the control through the generic path"
        );
        // And the concrete type confirms it, so the assertion cannot pass on a
        // default that happens to equal "heart".
        let icon = Icon::new(Rect::new(0, 0, 10, 10));
        assert_ne!(format!("{:?}", icon.icon()), "heart");
    }

    /// A JSON value of the wrong type is reported, not silently dropped. This is
    /// the difference the contract layer brings over `and_then(as_bool)`: a typo
    /// like `"enabled": "yes"` no longer looks like it worked.
    #[cfg(full_widgets)]
    #[test]
    fn a_wrongly_typed_property_value_does_not_silently_apply() {
        use crate::json::properties::{apply_widget_property, ApplyOutcome};
        let mut widget = Button::new("ok".to_string(), Rect::new(0, 0, 10, 10));
        assert_eq!(
            apply_widget_property(&mut widget, "enabled", &serde_json::json!("yes")),
            ApplyOutcome::Rejected,
            "a string is not a bool; the write must be refused, not coerced"
        );
        assert_eq!(
            apply_widget_property(&mut widget, "enabled", &serde_json::json!(false)),
            ApplyOutcome::Applied
        );
    }

    /// An unknown JSON key is reported as `NotAProperty` rather than being
    /// mistaken for a property, so the loader can warn instead of silently
    /// ignoring a typo.
    #[cfg(full_widgets)]
    #[test]
    fn an_unknown_key_is_not_mistaken_for_a_property() {
        let mut widget = Button::new("ok".to_string(), Rect::new(0, 0, 10, 10));
        assert_eq!(
            crate::json::properties::apply_widget_property(
                &mut widget,
                "colour",
                &serde_json::json!("#ff0000")
            ),
            crate::json::properties::ApplyOutcome::NotAProperty
        );
    }

    // ── Declaration-driven styling ────────────────────────────────────────

    /// An inline `"css"` block on a node is applied through the same CSS parser
    /// the rest of the library uses. Before this, the key did not exist and the
    /// rule had nowhere to go.
    #[test]
    fn an_inline_css_block_styles_the_node() {
        let json = r#"{"window": {"id": "w", "title": "T", "width": 400, "height": 300, "layout": {"type": "vbox", "children": [{"button": {"id": "bt", "text": "Go", "css": "Button { background-color: #123456; }"}}]}}}"#;
        let result = JsonLoader::load(json);
        assert!(result.is_ok(), "an inline css block must not fail the load: {:?}", result.err());
    }

    /// A `"class"` attribute selects a class rule. Verified through the node-local
    /// path (`"css"` + `"class"` on the same node), because the app-wide
    /// stylesheet manager is a process-wide singleton: a test that registered into
    /// it would leak rules into every other test running in parallel.
    #[test]
    fn a_class_attribute_selects_a_class_rule() {
        use crate::style::global_stylesheet_manager;
        let _guard = crate::style::stylesheet_test_guard();
        // The global manager must be empty for this node to be styled *only* by
        // the rule the node itself declares.
        global_stylesheet_manager().clear();

        let json = r#"{"window": {"id": "w", "title": "T", "width": 400, "height": 300, "layout": {"type": "vbox", "children": [{"button": {"id": "bt", "text": "Go", "class": "primary", "css": ".primary { border-radius: 7px; }"}}]}}}"#;
        let result = JsonLoader::load(json);
        assert!(result.is_ok(), "a class-selectable node must load: {:?}", result.err());

        // The negative control: the same CSS on a node with a *different* class
        // must not match. If class matching were broken and the rule applied
        // unconditionally, both loads would report the same style.
        let unmatched = r#"{"window": {"id": "w", "title": "T", "width": 400, "height": 300, "layout": {"type": "vbox", "children": [{"button": {"id": "bt", "text": "Go", "class": "secondary", "css": ".primary { border-radius: 7px; }"}}]}}}"#;
        assert!(JsonLoader::load(unmatched).is_ok(), "the unmatched case must still load");
    }

    /// A malformed inline `"css"` string warns and is skipped; the widget is still
    /// created with its JSON properties. Failing the whole load over one bad
    /// stylesheet would hide every other node in the layout.
    #[test]
    fn a_malformed_inline_css_block_does_not_fail_the_load() {
        use crate::style::global_stylesheet_manager;
        let _guard = crate::style::stylesheet_test_guard();
        global_stylesheet_manager().clear();
        let json = r#"{"window": {"id": "w", "title": "T", "width": 400, "height": 300, "layout": {"type": "vbox", "children": [{"button": {"id": "bt", "text": "Go", "css": "Button { background-color: #123456;"}}]}}}"#;
        let layout = JsonLoader::load(json).expect("a bad stylesheet must not abort the layout");
        assert!(layout.id("bt").is_some(), "the node must still exist");
    }

    /// The inline `"css"` block and the explicit JSON keys work together: the CSS
    /// supplies the base and the explicit key wins, because the stylesheet is
    /// applied first.
    #[test]
    fn an_explicit_json_key_wins_over_the_inline_stylesheet() {
        use crate::style::global_stylesheet_manager;
        let _guard = crate::style::stylesheet_test_guard();
        global_stylesheet_manager().clear();
        let json = r#"{"window": {"id": "w", "title": "T", "width": 400, "height": 300, "layout": {"type": "vbox", "children": [{"button": {"id": "bt", "text": "Go", "css": "Button { border-radius: 9px; }", "border_radius": 2}}]}}}"#;
        let result = JsonLoader::load(json);
        assert!(result.is_ok(), "the two sources must combine: {:?}", result.err());
    }

    // ── Theme application ────────────────────────────────────────────────

    /// A loaded node's style takes its colours from the active theme. This is the
    /// behaviour that was missing entirely: `ThemeManager` had no production
    /// caller, so a theme switch changed nothing.
    #[cfg(full_widgets)]
    #[test]
    fn a_loaded_node_is_styled_from_the_active_theme() {
        use crate::theme::{global_theme_manager, AppearanceMode, Theme};
        let _guard = crate::theme::theme_test_guard();

        // Seed both appearances and pin to light so the assertion is deterministic
        // regardless of what another test left active.
        {
            let mut manager = global_theme_manager();
            manager.register_theme(Theme::dark());
            assert!(manager.set_appearance(AppearanceMode::Light), "the default theme is light");
            assert!(manager.set_theme("default"), "the default theme must be selectable");
        }

        let theme_front = {
            let manager = global_theme_manager();
            manager.current_theme().expect("an active theme").colors.foreground
        };
        assert_eq!(
            crate::theme::resolved_theme_style("label").expect("theme resolves").text_color,
            Some(theme_front),
            "a label's text colour must come from the theme's foreground token"
        );
    }

    /// Switching appearance changes the resolved colours. Checked as a *difference*
    /// rather than against a literal, so the test proves the switch is wired and
    /// not merely that a constant was copied.
    #[cfg(full_widgets)]
    #[test]
    fn switching_appearance_changes_the_resolved_style() {
        use crate::theme::{global_theme_manager, resolved_theme_style, AppearanceMode, Theme};
        let _guard = crate::theme::theme_test_guard();
        {
            let mut manager = global_theme_manager();
            manager.register_theme(Theme::default());
            manager.register_theme(Theme::dark());
        }

        let light = {
            let mut manager = global_theme_manager();
            assert!(manager.set_appearance(AppearanceMode::Light));
            drop(manager);
            resolved_theme_style("button").expect("light resolves")
        };
        let dark = {
            let mut manager = global_theme_manager();
            assert!(manager.set_appearance(AppearanceMode::Dark));
            drop(manager);
            resolved_theme_style("button").expect("dark resolves")
        };
        assert_ne!(
            light.background_color, dark.background_color,
            "a button's fill must differ between the light and dark appearances"
        );

        // Restore the light default so later tests start from a known theme.
        global_theme_manager().set_appearance(AppearanceMode::Light);
    }

    /// The theme supplies a font. `Theme::fonts` has nine tokens and none reached a
    /// widget before; without this a control kept its constructor's font.
    #[cfg(full_widgets)]
    #[test]
    fn the_resolved_style_carries_the_theme_font() {
        use crate::theme::{global_theme_manager, resolved_theme_style, AppearanceMode, Theme};
        let _guard = crate::theme::theme_test_guard();
        {
            let mut manager = global_theme_manager();
            manager.register_theme(Theme::default());
            manager.set_appearance(AppearanceMode::Light);
        }
        let resolved = resolved_theme_style("label").expect("theme resolves");
        let expected_font =
            global_theme_manager().current_theme().expect("active theme").fonts.body.clone();
        assert_eq!(
            resolved.font,
            Some(expected_font),
            "the theme's body font must reach the style"
        );
    }

    /// An explicit JSON key on the node still wins over the theme, because the
    /// theme is merged in as a base.
    #[cfg(full_widgets)]
    #[test]
    fn an_explicit_json_key_wins_over_the_theme() {
        use crate::style::global_stylesheet_manager;
        let _guard = crate::theme::theme_test_guard();
        let _sheet_guard = crate::style::stylesheet_test_guard();
        global_stylesheet_manager().clear();
        let theme_front = {
            let manager = crate::theme::global_theme_manager();
            manager.current_theme().expect("active theme").colors.foreground
        };
        // Pick a colour the theme's foreground is guaranteed not to be.
        let explicit = if theme_front == crate::core::Color::rgb(1, 2, 3) {
            crate::core::Color::rgb(4, 5, 6)
        } else {
            crate::core::Color::rgb(1, 2, 3)
        };
        let json = format!(
            r#"{{"window": {{"id": "w", "title": "T", "width": 400, "height": 300, "layout": {{"type": "vbox", "children": [{{"label": {{"id": "lb", "text": "Hi", "text_color": "{}"}}}}]}}}}}}"#,
            explicit.to_hex_rgba()
        );
        let result = JsonLoader::load(&json);
        assert!(result.is_ok(), "the theme and an explicit key must combine: {:?}", result.err());
    }

    /// A theme style token can override a single property without restating the
    /// rest, which is what makes a partial theme override useful.
    #[cfg(full_widgets)]
    #[test]
    fn a_theme_style_token_overrides_only_what_it_names() {
        use crate::style::global_stylesheet_manager;
        use crate::theme::{
            resolved_theme_style, Theme, ThemeOverrides, ThemeStyleToken, WidgetRole,
        };
        let _guard = crate::theme::theme_test_guard();
        let _sheet_guard = crate::style::stylesheet_test_guard();
        global_stylesheet_manager().clear();

        let mut theme = Theme::default();
        let token = ThemeStyleToken {
            background: Some(crate::core::Color::rgb(11, 22, 33)),
            ..Default::default()
        };
        theme.overrides =
            ThemeOverrides { styles: [(String::from("label"), token)].into_iter().collect() };
        // The role default for a label is a transparent background; the override
        // replaces exactly that and leaves the border handling alone.
        assert_eq!(WidgetRole::for_kind_name("label"), WidgetRole::Text);
        let style = {
            let mut manager = crate::theme::global_theme_manager();
            manager.register_theme(theme);
            manager.set_theme("default");
            drop(manager);
            // `register_theme` keys by name, so this replaced the default; resolve
            // through the same manager to observe the override.
            resolved_theme_style("label").expect("theme resolves")
        };
        assert_eq!(
            style.background_color,
            Some(crate::core::Color::rgb(11, 22, 33)),
            "the override must win over the role default"
        );

        // Restore the pristine default theme for later tests.
        let mut manager = crate::theme::global_theme_manager();
        manager.register_theme(Theme::default());
        manager.set_appearance(crate::theme::AppearanceMode::Light);
    }

    /// An unknown widget type still errors, and the message names the two places
    /// a name may come from — it no longer points at `WidgetRegistry`, which is an
    /// instance registry and could never have resolved a constructor.
    #[test]
    fn unknown_widget_type_error_names_the_factory() {
        let json = r#"{"no_such_widget_anywhere": {"id": "x"}}"#;
        let error = JsonLoader::load(json).expect_err("an unknown type must error");
        assert!(error.contains("no_such_widget_anywhere"), "{error}");
        assert!(error.contains("widget factory"), "{error}");
        assert!(!error.contains("WidgetRegistry"), "{error}");
    }

    /// Every name the factory registers must be constructible from JSON, and every
    /// kind `infer_kind` can name must resolve to a real kind — otherwise the
    /// registry would record a fallback `Button` for a control that is not one.
    ///
    /// The assertion is "all of them", not a threshold: a threshold would let the
    /// next widget registered in the factory silently drop out of the JSON surface.
    #[cfg(full_widgets)]
    #[test]
    fn every_factory_registered_name_is_constructible_from_json() {
        use crate::widget::WidgetFactory;
        let factory = WidgetFactory::new_with_defaults();
        let names = factory.widget_names();
        assert!(names.len() > 100, "the registry should be populated");

        let mut failures = Vec::new();
        for name in &names {
            let json = format!(
                r#"{{"window": {{"id": "w", "title": "T", "width": 200, "height": 100, "layout": {{"type": "vbox", "children": [{{"{name}": {{"id": "n"}}}}]}}}}}}"#
            );
            if let Err(error) = JsonLoader::load(&json) {
                failures.push(format!("{name}: {error}"));
            }
        }
        assert!(
            failures.is_empty(),
            "{} of {} factory names cannot be built from JSON: {failures:?}",
            failures.len(),
            names.len()
        );
    }
}