cranpose-foundation 0.20.0

Modifier-node, input, focus, text and semantics contracts for Cranpose UI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
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
//! Modifier node scaffolding for Cranpose.
//!
//! This module defines the foundational pieces of the Cranpose
//! `Modifier.Node` system. It introduces traits for modifier nodes and their
//! contexts as well as a lightweight chain container that reconciles nodes
//! across updates.

use std::{
    any::{Any, TypeId, type_name},
    cell::{Cell, RefCell},
    fmt,
    hash::{Hash, Hasher},
    ops::{BitOr, BitOrAssign},
    rc::Rc,
};

use cranpose_core::{PackedU64, ProvidedValue, hash::default};
pub use cranpose_ui_graphics::{DrawScope, Size};
pub use cranpose_ui_layout::{Constraints, Measurable};

use crate::nodes::input::types::PointerEvent;

mod chain;
mod chain_node_ref;
mod scroll_axis_range;

pub use chain::ModifierNodeChain;
pub use chain_node_ref::{ModifierChainIter, ModifierChainNodeRef};
pub use scroll_axis_range::ScrollAxisRange;

/// Identifies which part of the rendering pipeline should be invalidated
/// after a modifier node changes state.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum InvalidationKind {
    /// The node's size or placement may have changed, so layout runs again.
    Layout,
    /// The node's drawn output changed, so it draws again.
    Draw,
    /// The node's pointer input handling changed.
    PointerInput,
    /// The node's accessibility semantics changed.
    Semantics,
    /// The node's focus behavior changed.
    Focus,
}

/// Runtime services exposed to modifier nodes while attached to a tree.
pub trait ModifierNodeContext {
    /// Requests that a particular pipeline stage be invalidated.
    fn invalidate(&mut self, _kind: InvalidationKind) {}

    /// Requests that the node's `update` method run again outside of a
    /// regular composition pass.
    fn request_update(&mut self) {}

    /// Returns the ID of the layout node this modifier is attached to, if known.
    /// This is used by modifiers that need to register callbacks for invalidation (e.g. Scroll).
    fn node_id(&self) -> Option<cranpose_core::NodeId> {
        None
    }

    /// Signals that a node with `capabilities` is about to interact with this context.
    fn push_active_capabilities(&mut self, _capabilities: NodeCapabilities) {}

    /// Signals that the most recent node interaction has completed.
    fn pop_active_capabilities(&mut self) {}

    /// The device pixels per layout point of the grid a layout modifier
    /// measures on, Compose's `MeasureScope` density: lengths it places land
    /// on whole device pixels of it. A context outside a layout pass answers
    /// a unit grid.
    fn density(&self) -> f32 {
        1.0
    }
}

/// Lightweight [`ModifierNodeContext`] implementation that records
/// invalidation requests and update signals.
///
/// The context intentionally avoids leaking runtime details so the core
/// crate can evolve independently from higher level UI crates. It simply
/// stores the sequence of requested invalidation kinds and whether an
/// explicit update was requested. Callers can inspect or drain this state
/// after driving a [`ModifierNodeChain`] reconciliation pass.
#[derive(Default, Debug, Clone)]
pub struct BasicModifierNodeContext {
    invalidations: ModifierInvalidations,
    update_requested: bool,
    /// The capabilities of the nodes interacting with the context, the
    /// innermost last; nesting stays shallow, so the stack lives inline.
    active_capabilities: smallvec::SmallVec<[NodeCapabilities; 4]>,
    node_id: Option<cranpose_core::NodeId>,
}

impl BasicModifierNodeContext {
    /// Creates a new empty context.
    pub fn new() -> Self {
        Self::default()
    }

    /// A context for the modifier nodes of node `node_id`, holding
    /// `invalidations` an earlier operation left for this one to report.
    pub fn for_node(
        node_id: Option<cranpose_core::NodeId>,
        invalidations: ModifierInvalidations,
    ) -> Self {
        Self {
            invalidations,
            node_id,
            ..Self::default()
        }
    }

    /// Returns the ordered list of invalidation kinds that were requested
    /// since the last call to `clear_invalidations`. Duplicate requests for
    /// the same kind are coalesced.
    pub fn invalidations(&self) -> &[ModifierInvalidation] {
        &self.invalidations
    }

    /// Removes all currently recorded invalidation kinds.
    pub fn clear_invalidations(&mut self) {
        self.invalidations.clear();
    }

    /// Drains the recorded invalidations and returns them to the caller.
    pub fn take_invalidations(&mut self) -> ModifierInvalidations {
        std::mem::take(&mut self.invalidations)
    }

    /// Returns whether an update was requested since the last call to
    /// `take_update_requested`.
    pub fn update_requested(&self) -> bool {
        self.update_requested
    }

    /// Returns whether an update was requested and clears the flag.
    pub fn take_update_requested(&mut self) -> bool {
        std::mem::take(&mut self.update_requested)
    }

    /// Sets the node ID associated with this context.
    pub fn set_node_id(&mut self, id: Option<cranpose_core::NodeId>) {
        self.node_id = id;
    }

    fn push_invalidation(&mut self, kind: InvalidationKind) {
        let mut capabilities = self.current_capabilities();
        capabilities.insert(NodeCapabilities::for_invalidation(kind));
        if let Some(existing) = self
            .invalidations
            .iter_mut()
            .find(|entry| entry.kind() == kind)
        {
            let updated = existing.capabilities() | capabilities;
            *existing = ModifierInvalidation::new(kind, updated);
        } else {
            self.invalidations
                .push(ModifierInvalidation::new(kind, capabilities));
        }
    }

    fn current_capabilities(&self) -> NodeCapabilities {
        self.active_capabilities
            .last()
            .copied()
            .unwrap_or_else(NodeCapabilities::empty)
    }
}

impl ModifierNodeContext for BasicModifierNodeContext {
    fn invalidate(&mut self, kind: InvalidationKind) {
        self.push_invalidation(kind);
    }

    fn request_update(&mut self) {
        self.update_requested = true;
    }

    fn push_active_capabilities(&mut self, capabilities: NodeCapabilities) {
        self.active_capabilities.push(capabilities);
    }

    fn pop_active_capabilities(&mut self) {
        self.active_capabilities.pop();
    }

    fn node_id(&self) -> Option<cranpose_core::NodeId> {
        self.node_id
    }
}

const MAX_DELEGATE_DEPTH: usize = 3;

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub(crate) struct NodePath {
    /// The chain entry, 32 bits wide: a path sits in every link of a
    /// chain's order, and no chain nears four billion entries.
    entry: u32,
    delegate_buf: [u8; MAX_DELEGATE_DEPTH],
    delegate_len: u8,
}

impl NodePath {
    #[inline]
    fn root(entry: usize) -> Self {
        debug_assert!(entry <= u32::MAX as usize, "chain entry exceeds u32 range");
        Self {
            entry: entry as u32,
            delegate_buf: [0; MAX_DELEGATE_DEPTH],
            delegate_len: 0,
        }
    }

    #[inline]
    fn from_slice(entry: usize, path: &[usize]) -> Self {
        debug_assert!(
            path.len() <= MAX_DELEGATE_DEPTH,
            "delegate depth {} exceeds MAX_DELEGATE_DEPTH {}",
            path.len(),
            MAX_DELEGATE_DEPTH
        );
        debug_assert!(
            path.iter().all(|&i| i <= u8::MAX as usize),
            "delegate index exceeds u8 range"
        );
        let mut delegate_buf = [0u8; MAX_DELEGATE_DEPTH];
        for (i, &v) in path.iter().enumerate().take(MAX_DELEGATE_DEPTH) {
            delegate_buf[i] = v as u8;
        }
        Self {
            delegate_buf,
            delegate_len: path.len().min(MAX_DELEGATE_DEPTH) as u8,
            ..Self::root(entry)
        }
    }

    #[inline]
    fn entry(&self) -> usize {
        self.entry as usize
    }

    #[inline]
    fn delegates(&self) -> &[u8] {
        &self.delegate_buf[..self.delegate_len as usize]
    }
}

/// Runtime state tracked for every [`ModifierNode`].
///
/// This type is part of the internal node system API and should not be directly
/// constructed or manipulated by external code. Modifier nodes automatically receive
/// and manage their NodeState through the modifier chain infrastructure.
#[derive(Debug)]
pub struct NodeState {
    capabilities: Cell<NodeCapabilities>,
    attached: Cell<bool>,
}

impl Default for NodeState {
    fn default() -> Self {
        Self::new()
    }
}

impl NodeState {
    /// Creates the state of a node that is not attached to a chain yet and has no capabilities.
    pub const fn new() -> Self {
        Self {
            capabilities: Cell::new(NodeCapabilities::empty()),
            attached: Cell::new(false),
        }
    }

    /// Records the capabilities of the node that owns this state. The chain calls it when it adds
    /// or updates the node.
    pub fn set_capabilities(&self, capabilities: NodeCapabilities) {
        self.capabilities.set(capabilities);
    }

    /// The capabilities of the node that owns this state.
    #[inline]
    pub fn capabilities(&self) -> NodeCapabilities {
        self.capabilities.get()
    }

    // The chain marks a node attached before `on_attach` and detached after `on_detach`.
    pub(crate) fn set_attached(&self, attached: bool) {
        self.attached.set(attached);
    }

    /// Whether the node is attached to a chain. It is true after `on_attach` ran and before
    /// `on_detach` runs.
    pub fn is_attached(&self) -> bool {
        self.attached.get()
    }
}

/// Provides traversal helpers that mirror Jetpack Compose's [`DelegatableNode`] contract.
pub trait DelegatableNode {
    /// The runtime state of this node. Return a `NodeState` field of the node; the chain uses it to
    /// track the node's capabilities and attachment.
    fn node_state(&self) -> &NodeState;
}

/// Core trait implemented by modifier nodes.
///
/// # Capability-Driven Architecture
///
/// This trait follows Jetpack Compose's `Modifier.Node` pattern where nodes declare
/// their capabilities via [`NodeCapabilities`] and implement specialized traits
/// ([`DrawModifierNode`], [`PointerInputNode`], [`SemanticsNode`], [`FocusNode`], etc.)
/// to participate in specific pipeline stages.
///
/// ## How to Implement a Modifier Node
///
/// 1. **Declare capabilities** in your [`ModifierNodeElement::capabilities()`] implementation
/// 2. **Implement specialized traits** for the capabilities you declared
/// 3. **Use helper macros** to reduce boilerplate (recommended)
///
/// ### Example: Draw Node
///
/// ```text
/// use cranpose_foundation::*;
///
/// struct MyDrawNode {
///     state: NodeState,
///     color: Color,
/// }
///
/// impl DelegatableNode for MyDrawNode {
///     fn node_state(&self) -> &NodeState {
///         &self.state
///     }
/// }
///
/// impl ModifierNode for MyDrawNode {
///     // Use the helper macro instead of manual as_* implementations
///     impl_modifier_node!(draw);
/// }
///
/// impl DrawModifierNode for MyDrawNode {
///     fn draw(&mut self, _context: &mut dyn ModifierNodeContext, draw_scope: &mut dyn DrawScope) {
///         // Drawing logic here
///     }
/// }
/// ```
///
/// ### Example: Multi-Capability Node
///
/// ```text
/// impl ModifierNode for MyComplexNode {
///     // This node participates in draw, pointer input, and semantics
///     impl_modifier_node!(draw, pointer_input, semantics);
/// }
/// ```
///
/// ## Lifecycle Callbacks
///
/// Nodes receive lifecycle callbacks when they attach to or detach from a
/// composition and may optionally react to resets triggered by the runtime
/// (for example, when reusing nodes across modifier list changes).
pub trait ModifierNode: Any + DelegatableNode {
    /// Called once when the node joins an attached chain. `context` receives the invalidation
    /// requests of the node.
    fn on_attach(&mut self, _context: &mut dyn ModifierNodeContext) {}

    /// Called when the node leaves the chain or when the chain detaches. Release here whatever
    /// `on_attach` acquired.
    fn on_detach(&mut self) {}

    /// Called when the chain is reset, as Compose's `onReset`. Clear state that belongs to an
    /// earlier use of the node.
    fn on_reset(&mut self) {}

    /// Returns this node as a draw modifier if it implements the trait.
    fn as_draw_node(&self) -> Option<&dyn DrawModifierNode> {
        None
    }

    /// Returns this node as a mutable draw modifier if it implements the trait.
    fn as_draw_node_mut(&mut self) -> Option<&mut dyn DrawModifierNode> {
        None
    }

    /// Returns this node as a pointer-input modifier if it implements the trait.
    fn as_pointer_input_node(&self) -> Option<&dyn PointerInputNode> {
        None
    }

    /// Returns this node as a mutable pointer-input modifier if it implements the trait.
    fn as_pointer_input_node_mut(&mut self) -> Option<&mut dyn PointerInputNode> {
        None
    }

    /// Returns this node as a semantics modifier if it implements the trait.
    fn as_semantics_node(&self) -> Option<&dyn SemanticsNode> {
        None
    }

    /// Returns this node as a mutable semantics modifier if it implements the trait.
    fn as_semantics_node_mut(&mut self) -> Option<&mut dyn SemanticsNode> {
        None
    }

    /// Returns this node as a focus modifier if it implements the trait.
    fn as_focus_node(&self) -> Option<&dyn FocusNode> {
        None
    }

    /// Returns this node as a mutable focus modifier if it implements the trait.
    fn as_focus_node_mut(&mut self) -> Option<&mut dyn FocusNode> {
        None
    }

    /// Returns this node as a layout modifier if it implements the trait.
    fn as_layout_node(&self) -> Option<&dyn LayoutModifierNode> {
        None
    }

    /// Returns this node as a mutable layout modifier if it implements the trait.
    fn as_layout_node_mut(&mut self) -> Option<&mut dyn LayoutModifierNode> {
        None
    }

    /// Visits every delegate node owned by this modifier.
    fn for_each_delegate<'b>(&'b self, _visitor: &mut dyn FnMut(&'b dyn ModifierNode)) {}

    /// Visits every delegate node mutably.
    fn for_each_delegate_mut<'b>(&'b mut self, _visitor: &mut dyn FnMut(&'b mut dyn ModifierNode)) {
    }
}

/// Marker trait for layout-specific modifier nodes.
///
/// Layout nodes participate in the measure and layout passes of the render
/// pipeline. They can intercept and modify the measurement and placement of
/// their wrapped content.
pub trait LayoutModifierNode: ModifierNode {
    /// Measures the wrapped content and returns both the size this modifier
    /// occupies and where the wrapped content should be placed.
    ///
    /// The node receives a measurable representing the wrapped content and
    /// the incoming constraints from the parent.
    ///
    /// Returns a `LayoutModifierMeasureResult` containing:
    /// - `size`: The final size this modifier will occupy
    /// - `placement_offset_x/y`: Where to place the wrapped content relative
    ///   to this modifier's top-left corner
    ///
    /// For example, a padding modifier would:
    /// - Measure child with deflated constraints
    /// - Return size = child size + padding
    /// - Return placement offset = (padding.left, padding.top)
    ///
    /// The default implementation delegates to the wrapped content without
    /// modification (size = child size, offset = 0).
    ///
    /// NOTE: This takes `&self` not `&mut self` to match Jetpack Compose semantics.
    /// Nodes that need mutable state should use interior mutability (Cell/RefCell).
    fn measure(
        &self,
        _context: &mut dyn ModifierNodeContext,
        measurable: &dyn Measurable,
        constraints: Constraints,
    ) -> cranpose_ui_layout::LayoutModifierMeasureResult {
        let placeable = measurable.measure(constraints);
        cranpose_ui_layout::LayoutModifierMeasureResult::with_size(Size {
            width: placeable.width(),
            height: placeable.height(),
        })
    }

    /// The incoming constraints the last measure of this node, which gave
    /// `size` under `constraints`, holds for: every constraints inside give
    /// the same result. `wrapped` is what the content this node wraps
    /// measured. `None`, the default, holds for `constraints` alone; a node
    /// that tells must give the range its own measure keeps its result and
    /// hands its content constraints that `wrapped` holds for.
    fn measure_hold(
        &self,
        _density: f32,
        _constraints: Constraints,
        _size: Size,
        _wrapped: cranpose_ui_layout::WrappedHold,
    ) -> Option<cranpose_ui_layout::ConstraintsHold> {
        None
    }

    /// Returns the minimum intrinsic width of this modifier node. The default is
    /// the wrapped content's, for a node that keeps the content's size.
    fn min_intrinsic_width(&self, measurable: &dyn Measurable, height: f32, _density: f32) -> f32 {
        measurable.min_intrinsic_width(height)
    }

    /// Returns the maximum intrinsic width of this modifier node. The default is
    /// the wrapped content's, for a node that keeps the content's size.
    fn max_intrinsic_width(&self, measurable: &dyn Measurable, height: f32, _density: f32) -> f32 {
        measurable.max_intrinsic_width(height)
    }

    /// Returns the minimum intrinsic height of this modifier node. The default is
    /// the wrapped content's, for a node that keeps the content's size.
    fn min_intrinsic_height(&self, measurable: &dyn Measurable, width: f32, _density: f32) -> f32 {
        measurable.min_intrinsic_height(width)
    }

    /// Returns the maximum intrinsic height of this modifier node. The default is
    /// the wrapped content's, for a node that keeps the content's size.
    fn max_intrinsic_height(&self, measurable: &dyn Measurable, width: f32, _density: f32) -> f32 {
        measurable.max_intrinsic_height(width)
    }
}

/// Marker trait for draw-specific modifier nodes.
///
/// Draw nodes participate in the draw pass of the render pipeline. A node
/// draws through the closures it hands out, which the renderer runs at render
/// time with a live scope of the node's size; slice collection only gathers
/// them.
pub trait DrawModifierNode: ModifierNode {
    /// Creates a closure for deferred drawing that will be evaluated at render time.
    ///
    /// This is the preferred method for nodes with dynamic content like:
    /// - Blinking cursors (visibility changes over time)
    /// - Live selection during drag (selection changes during mouse move)
    ///
    /// The returned closure captures the node's internal state (via Rc) and
    /// evaluates at render time, not at slice collection time.
    ///
    /// Returns None by default. Override for nodes needing deferred draw.
    fn create_draw_closure(&self) -> Option<NodeDrawClosure> {
        None
    }

    /// Like [`create_draw_closure`](Self::create_draw_closure), but the
    /// primitives render BEHIND the node's content — e.g. a text field's
    /// selection highlight, which must sit under the glyphs (a highlight
    /// drawn over them tints the text with its translucent fill).
    fn create_behind_draw_closure(&self) -> Option<NodeDrawClosure> {
        None
    }
}

/// A deferred draw closure returned by
/// [`DrawModifierNode::create_draw_closure`]: it records into a scope the
/// renderer provides at render time, so the recording's identity stays with
/// the consumer rather than with a closure-owned vector.
pub type NodeDrawClosure = Rc<dyn Fn(&mut cranpose_ui_graphics::DrawScopeDefault)>;

/// Marker trait for pointer input modifier nodes.
///
/// Pointer input nodes participate in hit-testing and pointer event
/// dispatch. They can intercept pointer events and handle them before
/// they reach the wrapped content.
pub trait PointerInputNode: ModifierNode {
    /// Called when a pointer event occurs within the bounds of this node.
    /// Returns true if the event was consumed and should not propagate further.
    fn on_pointer_event(
        &mut self,
        _context: &mut dyn ModifierNodeContext,
        _event: &PointerEvent,
    ) -> bool {
        false
    }

    /// Returns true if this node should participate in hit-testing for the
    /// given pointer position.
    fn hit_test(&self, _x: f32, _y: f32) -> bool {
        true
    }

    /// Returns an event handler closure if the node wants to participate in pointer dispatch.
    fn pointer_input_handler(&self) -> Option<Rc<dyn Fn(PointerEvent)>> {
        None
    }

    /// Returns the cell this node reads its owning layout node's resolved size
    /// from, if it exposes a size to its handler (Compose's
    /// `PointerInputScope.size`).
    ///
    /// The cell is shared with the node, so the layout pass publishes the size
    /// into it once per pass and every read — including reads that happen
    /// before any pointer event arrives — observes the current size. The size
    /// is the node's layout box in the same local coordinate space the
    /// dispatched [`PointerEvent`] positions use, so
    /// `event.local_position / size` is a well-defined fraction of the node.
    ///
    /// Returns `None` for pointer nodes with no size-bearing scope.
    fn layout_size_sink(&self) -> Option<Rc<Cell<Size>>> {
        None
    }
}

/// Marker trait for semantics modifier nodes.
///
/// Semantics nodes participate in the semantics tree construction. They can
/// add or modify semantic properties of their wrapped content for
/// accessibility and testing purposes.
pub trait SemanticsNode: ModifierNode {
    /// Merges semantic properties into the provided configuration.
    fn merge_semantics(&self, _config: &mut SemanticsConfiguration) {}

    /// Whether this node makes its subtree modal or hides it, and whether
    /// what it merges can change without its semantics being invalidated.
    /// The default merges into a fresh configuration, reads the two flags and
    /// counts the node as reading live state; a node that can declare
    /// neither flag and reports only what its updates bring overrides it to
    /// skip that work.
    fn reach(&self) -> SemanticsReach {
        SemanticsReach::merged_by(self, true)
    }
}

/// The semantics flags that decide how a node's semantics reach the tree:
/// which part of a window is live ([`SemanticsConfiguration::is_modal`] and
/// [`SemanticsConfiguration::hidden`]), and whether a tree update may keep
/// what the node reported last.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct SemanticsReach {
    /// The subtree takes over the screen.
    pub is_modal: bool,
    /// The subtree is skipped by readers.
    pub hidden: bool,
    /// What the node merges can change without its semantics being
    /// invalidated, as a `.semantics { }` recorder reading live state can,
    /// so every tree update merges it again.
    pub merges_live_state: bool,
}

impl SemanticsReach {
    /// The modal and hidden flags `node` merges into a fresh configuration,
    /// with whether what it merges can change without an invalidation.
    pub fn merged_by(node: &(impl SemanticsNode + ?Sized), merges_live_state: bool) -> Self {
        let mut config = SemanticsConfiguration::default();
        node.merge_semantics(&mut config);
        Self {
            is_modal: config.is_modal,
            hidden: config.hidden,
            merges_live_state,
        }
    }

    /// Every flag of `self` and `other`.
    pub fn union(self, other: Self) -> Self {
        Self {
            is_modal: self.is_modal || other.is_modal,
            hidden: self.hidden || other.hidden,
            merges_live_state: self.merges_live_state || other.merges_live_state,
        }
    }
}

/// Whether a check box or switch is on, off or partly on: Compose's
/// `ToggleableState`. A check box over a list whose items are partly checked
/// is `Indeterminate`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ToggleableState {
    /// The control is on or checked.
    On,
    /// The control is off or unchecked.
    Off,
    /// The control is partly on, as a check box over items of which some are checked.
    Indeterminate,
}

impl From<bool> for ToggleableState {
    fn from(on: bool) -> Self {
        if on { Self::On } else { Self::Off }
    }
}

/// Focus state of a focus target node.
///
/// This mirrors Jetpack Compose's FocusState enum which tracks whether
/// a node is focused, has a focused child, or is inactive.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
pub enum FocusState {
    /// The focusable component is currently active (i.e. it receives key events).
    Active,
    /// One of the descendants of the focusable component is Active.
    ActiveParent,
    /// The focusable component is currently active (has focus), and is in a state
    /// where it does not want to give up focus. (Eg. a text field with an invalid
    /// phone number).
    Captured,
    /// The focusable component does not receive any key events. (ie it is not active,
    /// nor are any of its descendants active).
    #[default]
    Inactive,
}

impl FocusState {
    /// Returns whether the component is focused (Active or Captured).
    pub fn is_focused(self) -> bool {
        matches!(self, Self::Active | Self::Captured)
    }

    /// Returns whether this node or any descendant has focus.
    pub fn has_focus(self) -> bool {
        matches!(self, Self::Active | Self::ActiveParent | Self::Captured)
    }

    /// Returns whether focus is captured.
    pub fn is_captured(self) -> bool {
        matches!(self, Self::Captured)
    }
}

/// Marker trait for focus modifier nodes.
///
/// Focus nodes participate in focus management. They can request focus,
/// track focus state, and participate in focus traversal.
pub trait FocusNode: ModifierNode {
    /// Returns the current focus state of this node.
    fn focus_state(&self) -> FocusState;

    /// Called when focus state changes for this node.
    fn on_focus_changed(&mut self, _context: &mut dyn ModifierNodeContext, _state: FocusState) {}
}

/// What kind of control a node is, as screen readers announce it.
///
/// This is Compose's `SemanticsProperties.Role` (`Modifier.semantics { role =
/// Role.RadioButton }`), not a description of where the node sits in the tree.
/// A screen reader turns it into the trailing noun it speaks after the label —
/// TalkBack says "CAMPAIGN, radio button, selected" — and into the on/off
/// wording it uses for a switch. Compose keeps this separate from the node's
/// structural kind for the same reason Cranpose does: a `Row` that happens to
/// be clickable is still a row, and a drawn ring segment that is a radio button
/// has no layout node of its own at all.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SemanticsWidgetRole {
    /// A control that acts when pressed. Compose's `Role.Button`.
    Button,
    /// A control that is checked or unchecked. Compose's `Role.Checkbox`.
    Checkbox,
    /// A control that is on or off. Compose's `Role.Switch`.
    Switch,
    /// One choice of a set in which only one choice is selected. Compose's `Role.RadioButton`.
    RadioButton,
    /// One page selector of a tab bar. Compose's `Role.Tab`.
    Tab,
    /// A picture. Compose's `Role.Image`.
    Image,
    /// A control that opens a list of choices and holds the one that is
    /// picked. Compose's `Role.DropdownList`.
    DropdownList,
    /// A control that holds one value out of an ordered set and steps through
    /// them. Compose's `Role.ValuePicker`.
    ValuePicker,
    /// Compose's `heading()`, which is a property rather than a `Role`, but
    /// reaches the platform through the same field on every backend Cranpose
    /// targets (`AccessibilityNodeInfo.setHeading`, `Role::Heading`,
    /// `<h*>`/`UIAccessibilityTraitHeader`).
    Header,
    /// A modal surface that takes over the screen until it is dismissed.
    /// Screen readers announce it and confine their traversal to it, which is
    /// the accessible half of what makes a dialog modal.
    Dialog,
    /// Text that takes the user somewhere else when pressed. Compose has no
    /// such `Role`; SwiftUI's `.isLink`, ARIA's `link`.
    Link,
    /// A field that narrows what is on the screen as the user types. ARIA's
    /// `searchbox`, VoiceOver's search field trait.
    SearchField,
    /// A control that shows how far work has come and takes no input. ARIA's
    /// `progressbar`.
    ProgressBar,
    /// A button that stays pressed or released. ARIA's `button` with
    /// `aria-pressed`.
    ToggleButton,
    /// A message a reader speaks as soon as it shows, with no move to it.
    /// ARIA's `alert`.
    Alert,
    /// A row of controls that act on the content beside them. ARIA's
    /// `toolbar`.
    Toolbar,
    /// A list of commands that opens on a press. ARIA's `menu`.
    Menu,
    /// One command inside a menu. ARIA's `menuitem`.
    MenuItem,
    /// The row that holds the tabs of a screen. ARIA's `tablist`, VoiceOver's
    /// tab bar trait.
    TabBar,
    /// A container whose rows a reader counts and walks into. ARIA's `list`.
    List,
    /// One row of a list. ARIA's `listitem`.
    ListItem,
    /// A set of mutually exclusive radio choices. ARIA's `radiogroup`.
    RadioGroup,
}

/// The value a control holds inside a range, for a slider, a dial or a
/// progress bar.
///
/// This is Compose's `ProgressBarRangeInfo` (`Modifier.progressSemantics(value,
/// range, steps)`). A control without it reads as plain text: a screen reader
/// user hears "47 percent" and has no way to change it, because nothing tells
/// the platform the control is adjustable.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ProgressBarRangeInfo {
    /// The current value, between `start` and `end`.
    pub current: f32,
    /// The value at the low end of the range.
    pub start: f32,
    /// The value at the high end of the range.
    pub end: f32,
    /// How many stops sit between `start` and `end`, as Compose counts them.
    /// Zero means the value moves without stops.
    pub steps: u32,
}

impl ProgressBarRangeInfo {
    /// Creates range info for `current` between `start` and `end`, with `steps` stops between the
    /// two ends.
    pub fn new(current: f32, start: f32, end: f32, steps: u32) -> Self {
        Self {
            current,
            start,
            end,
            steps,
        }
    }

    /// Where the value sits between the two ends, from 0 to 1.
    pub fn fraction(&self) -> f32 {
        let span = self.end - self.start;
        if span.abs() < f32::EPSILON {
            return 0.0;
        }
        ((self.current - self.start) / span).clamp(0.0, 1.0)
    }

    /// How far one stop moves the value. With no stops, one tenth of the
    /// range, which is what a screen reader's swipe up and down expects.
    pub fn step(&self) -> f32 {
        let span = self.end - self.start;
        if self.steps == 0 {
            span / 10.0
        } else {
            span / (self.steps as f32 + 1.0)
        }
    }
}

/// How many rows and columns a list holds, so a screen reader can say
/// "list, 12 items" as its cursor enters. Compose's `CollectionInfo`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CollectionInfo {
    /// The number of rows the collection holds. A plain list reports its item count here.
    pub rows: usize,
    /// The number of columns the collection holds. A plain list reports 1.
    pub columns: usize,
}

/// What a container does when a screen reader pages it, e.g. TalkBack's
/// scroll forward action or an accesskit scroll down. The two deltas are in
/// layout pixels; the answer says whether anything moved.
///
/// This is Compose's `SemanticsActions.ScrollBy`.
#[derive(Clone)]
pub struct SemanticsScrollBy {
    handler: Rc<dyn Fn(f32, f32) -> bool>,
}

impl SemanticsScrollBy {
    /// Wraps `handler`, which receives the horizontal and the vertical distance in layout pixels
    /// and returns whether the container moved.
    pub fn new(handler: impl Fn(f32, f32) -> bool + 'static) -> Self {
        Self {
            handler: Rc::new(handler),
        }
    }

    /// Runs the handler with the distances `dx` and `dy`, in layout pixels. Returns whether the
    /// container moved.
    pub fn invoke(&self, dx: f32, dy: f32) -> bool {
        (self.handler)(dx, dy)
    }
}

impl fmt::Debug for SemanticsScrollBy {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SemanticsScrollBy").finish_non_exhaustive()
    }
}

impl PartialEq for SemanticsScrollBy {
    fn eq(&self, _other: &Self) -> bool {
        true
    }
}

impl Eq for SemanticsScrollBy {}

/// What a list does when a screen reader asks for the row at an index, e.g. a
/// TalkBack scroll-to-position action.
///
/// This is Compose's `SemanticsActions.ScrollToIndex`. The index counts rows
/// from zero, and the answer says whether the list moved.
#[derive(Clone)]
pub struct SemanticsScrollToIndex {
    handler: Rc<dyn Fn(usize) -> bool>,
}

impl SemanticsScrollToIndex {
    /// Wraps `handler`, which receives a row index counted from zero and returns whether the list
    /// moved.
    pub fn new(handler: impl Fn(usize) -> bool + 'static) -> Self {
        Self {
            handler: Rc::new(handler),
        }
    }

    /// Runs the handler for the row at `index`, counted from zero. Returns whether the list moved.
    pub fn invoke(&self, index: usize) -> bool {
        (self.handler)(index)
    }
}

impl fmt::Debug for SemanticsScrollToIndex {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SemanticsScrollToIndex")
            .finish_non_exhaustive()
    }
}

impl PartialEq for SemanticsScrollToIndex {
    fn eq(&self, _other: &Self) -> bool {
        true
    }
}

impl Eq for SemanticsScrollToIndex {}

/// What a control does when a screen reader moves its value, e.g. a VoiceOver
/// swipe up or a TalkBack set-progress action.
///
/// This is Compose's `SemanticsActions.SetProgress`. The value comes in the
/// control's own range, and the answer says whether the control took it.
#[derive(Clone)]
pub struct SemanticsSetProgress {
    handler: Rc<dyn Fn(f32) -> bool>,
}

impl SemanticsSetProgress {
    /// Wraps `handler`, which receives a value in the range of the control and returns whether the
    /// control took it.
    pub fn new(handler: impl Fn(f32) -> bool + 'static) -> Self {
        Self {
            handler: Rc::new(handler),
        }
    }

    /// Runs the handler with `value`, in the range of the control. Returns whether the control took
    /// it.
    pub fn invoke(&self, value: f32) -> bool {
        (self.handler)(value)
    }
}

impl fmt::Debug for SemanticsSetProgress {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SemanticsSetProgress")
            .finish_non_exhaustive()
    }
}

/// What a text field does when a screen reader or a voice tool hands it new
/// text. This is Compose's `SemanticsActions.SetText`; the answer says
/// whether the field took the text.
#[derive(Clone)]
pub struct SemanticsSetText(Rc<dyn Fn(&str) -> bool>);

impl SemanticsSetText {
    /// Wraps `handler`, which receives the new text and returns whether the field took it.
    pub fn new(handler: impl Fn(&str) -> bool + 'static) -> Self {
        Self(Rc::new(handler))
    }

    /// Runs the handler with `text`. Returns whether the field took it.
    pub fn invoke(&self, text: &str) -> bool {
        (self.0)(text)
    }
}

impl fmt::Debug for SemanticsSetText {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("SemanticsSetText")
    }
}

/// What a text field does when a screen reader moves its caret or picks a
/// stretch of its text: the two ends of the new selection, as byte offsets
/// into the field's text, the anchor first and the end that moves second. Equal
/// ends are a caret. This is Compose's `SemanticsActions.SetSelection`; the
/// answer says whether the field took the selection.
#[derive(Clone)]
pub struct SemanticsSetSelection(Rc<dyn Fn(usize, usize) -> bool>);

impl SemanticsSetSelection {
    /// Wraps `handler`, which receives the anchor and the focus offsets of the selection and
    /// returns whether the field took it.
    pub fn new(handler: impl Fn(usize, usize) -> bool + 'static) -> Self {
        Self(Rc::new(handler))
    }

    /// Runs the handler with the selection from byte offset `anchor` to byte offset `focus`.
    /// Returns whether the field took it.
    pub fn invoke(&self, anchor: usize, focus: usize) -> bool {
        (self.0)(anchor, focus)
    }
}

impl fmt::Debug for SemanticsSetSelection {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("SemanticsSetSelection")
    }
}

/// What a control does when a screen reader asks it to open or to close.
/// Compose's `expand` and `collapse` actions.
#[derive(Clone)]
pub struct SemanticsExpand(Rc<dyn Fn() -> bool>);

impl SemanticsExpand {
    /// Wraps `handler`, which returns whether the control opened or closed.
    pub fn new(handler: impl Fn() -> bool + 'static) -> Self {
        Self(Rc::new(handler))
    }

    /// Runs the handler. Returns whether the control opened or closed.
    pub fn invoke(&self) -> bool {
        (self.0)()
    }
}

impl fmt::Debug for SemanticsExpand {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("SemanticsExpand")
    }
}

/// What a control does when a screen reader asks for its long press. This is
/// Compose's `SemanticsActions.OnLongClick`; the answer says whether the
/// control took the ask.
#[derive(Clone)]
pub struct SemanticsLongClick(Rc<dyn Fn() -> bool>);

impl SemanticsLongClick {
    /// Wraps `handler`, which returns whether the control took the long press.
    pub fn new(handler: impl Fn() -> bool + 'static) -> Self {
        Self(Rc::new(handler))
    }

    /// Runs the handler. Returns whether the control took the long press.
    pub fn invoke(&self) -> bool {
        (self.0)()
    }
}

impl fmt::Debug for SemanticsLongClick {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("SemanticsLongClick")
    }
}

impl PartialEq for SemanticsLongClick {
    fn eq(&self, _other: &Self) -> bool {
        true
    }
}

impl PartialEq for SemanticsExpand {
    fn eq(&self, _other: &Self) -> bool {
        true
    }
}

/// What a control does when a screen reader asks to send it away: a row a
/// sighted person swipes off, a sheet a sighted person taps outside of.
/// Compose's `dismiss` action.
#[derive(Clone)]
pub struct SemanticsDismiss(Rc<dyn Fn() -> bool>);

impl SemanticsDismiss {
    /// Wraps `handler`, which returns whether the control was dismissed.
    pub fn new(handler: impl Fn() -> bool + 'static) -> Self {
        Self(Rc::new(handler))
    }

    /// Runs the handler. Returns whether the control was dismissed.
    pub fn invoke(&self) -> bool {
        (self.0)()
    }
}

impl fmt::Debug for SemanticsDismiss {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("SemanticsDismiss")
    }
}

impl PartialEq for SemanticsDismiss {
    fn eq(&self, _other: &Self) -> bool {
        true
    }
}

impl PartialEq for SemanticsSetText {
    fn eq(&self, _other: &Self) -> bool {
        true
    }
}

impl PartialEq for SemanticsSetSelection {
    fn eq(&self, _other: &Self) -> bool {
        true
    }
}

/// What a control does when a VoiceOver user makes the magic tap, the two
/// finger double tap that starts or stops the main action of a screen. On
/// the other platforms the action is listed by its label among the control's
/// actions. SwiftUI's `accessibilityAction(.magicTap)`; the answer says
/// whether the control took the tap.
#[derive(Clone)]
pub struct SemanticsMagicTap(Rc<dyn Fn() -> bool>);

impl SemanticsMagicTap {
    /// Wraps `handler`, which returns whether the control took the magic tap.
    pub fn new(handler: impl Fn() -> bool + 'static) -> Self {
        Self(Rc::new(handler))
    }

    /// Runs the handler. Returns whether the control took the magic tap.
    pub fn invoke(&self) -> bool {
        (self.0)()
    }
}

impl fmt::Debug for SemanticsMagicTap {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("SemanticsMagicTap")
    }
}

impl PartialEq for SemanticsMagicTap {
    fn eq(&self, _other: &Self) -> bool {
        true
    }
}

impl PartialEq for SemanticsSetProgress {
    fn eq(&self, _other: &Self) -> bool {
        true
    }
}

impl Eq for SemanticsSetProgress {}

/// How urgently a screen reader reads a node whose text changed on its own.
///
/// This is Compose's `LiveRegionMode` (`Modifier.semantics { liveRegion =
/// LiveRegionMode.Polite }`). A node without it stays silent until the reader
/// lands on it, which is wrong for a timer, a countdown, a status line, or an
/// error that appears next to a text field: a blind user hears nothing.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum LiveRegionMode {
    /// Read the new text once the reader finishes what it says now.
    Polite,
    /// Cut off what the reader says now and read the new text at once. For
    /// text a user must hear immediately, such as an error that stops them.
    Assertive,
}

/// A named accessibility operation, e.g. Compose's
/// `customActions = listOf(CustomAccessibilityAction("Pause") { … })`.
///
/// TalkBack surfaces these through its actions menu rather than by activating
/// the node, which is the only way to reach a command that has no on-screen
/// control — pausing a game whose whole surface is one tap-to-launch target.
#[derive(Clone)]
pub struct SemanticsCustomAction {
    /// What the screen reader reads out in its actions menu.
    pub label: String,
    handler: Rc<dyn Fn()>,
}

impl SemanticsCustomAction {
    /// Creates an action that a screen reader lists as `label` and that runs `handler` when chosen.
    pub fn new(label: impl Into<String>, handler: impl Fn() + 'static) -> Self {
        Self {
            label: label.into(),
            handler: Rc::new(handler),
        }
    }

    /// Runs the handler of the action.
    pub fn invoke(&self) {
        (self.handler)();
    }
}

impl fmt::Debug for SemanticsCustomAction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SemanticsCustomAction")
            .field("label", &self.label)
            .finish_non_exhaustive()
    }
}

impl PartialEq for SemanticsCustomAction {
    fn eq(&self, other: &Self) -> bool {
        self.label == other.label
    }
}

impl Eq for SemanticsCustomAction {}

/// A semantics node for content that is *drawn* rather than laid out.
///
/// An immediate-mode surface — one `Canvas` that paints a whole screen — has
/// exactly one layout node, so the semantics tree built from layout has exactly
/// one node to offer a screen reader. This is the escape hatch: the drawing
/// code already knows where it put every control, so it publishes those
/// rectangles as semantics directly. Android's own answer for a canvas-drawn
/// `View` is the same shape (`ExploreByTouchHelper` feeding virtual view ids
/// into an `AccessibilityNodeProvider`), and Cranpose's Android bridge is
/// already an `AccessibilityNodeProvider`, so these land as first-class
/// virtual views next to the ones layout produces.
///
/// `bounds` is in the publishing node's own coordinates (logical px, origin at
/// that node's top-left), because that is what a draw scope works in.
#[derive(Clone, Debug, PartialEq)]
pub struct CanvasSemanticsNode {
    /// Identity that must survive a redraw.
    ///
    /// A screen reader parks its cursor on a virtual view id; if the id for
    /// "the Haptics switch" changes when the list scrolls, the cursor jumps.
    /// Derive this from what the control *is* (a row index, an enum
    /// discriminant), never from where it currently sits.
    pub key: u64,
    /// Where the control was drawn, relative to the publishing node.
    pub bounds: cranpose_ui_graphics::Rect,
    /// What the screen reader reads for the control.
    pub label: String,
    /// What kind of control it is, as the screen reader announces it.
    pub role: Option<SemanticsWidgetRole>,
    /// Compose's `stateDescription` — what the control currently reads as
    /// ("CAMPAIGN", "3 of 18 gold"), spoken after the label and re-spoken on
    /// its own when only the state changed.
    pub state_description: Option<String>,
    /// Compose's `onClick(label = …)`. TalkBack reads it as "double tap to
    /// `<label>`", so it is a verb phrase, not a repeat of the label.
    pub on_click_label: Option<String>,
    /// Whether the control can be activated.
    pub clickable: bool,
    /// Compose's `selected`, for `Role.RadioButton`/`Role.Tab`.
    pub selected: Option<bool>,
    /// Compose's `toggleableState`, for `Role.Switch`/`Role.Checkbox`.
    pub toggled: Option<ToggleableState>,
    /// Whether the control accepts input. A disabled control is announced as such.
    pub enabled: bool,
    /// Named actions that the screen reader lists in its actions menu for the control.
    pub custom_actions: Vec<SemanticsCustomAction>,
}

impl Default for CanvasSemanticsNode {
    fn default() -> Self {
        Self {
            key: 0,
            bounds: cranpose_ui_graphics::Rect {
                x: 0.0,
                y: 0.0,
                width: 0.0,
                height: 0.0,
            },
            label: String::new(),
            role: None,
            state_description: None,
            on_click_label: None,
            clickable: false,
            selected: None,
            toggled: None,
            enabled: true,
            custom_actions: Vec::new(),
        }
    }
}

impl CanvasSemanticsNode {
    /// A clickable control drawn at `bounds`.
    pub fn control(key: u64, bounds: cranpose_ui_graphics::Rect, label: impl Into<String>) -> Self {
        Self {
            key,
            bounds,
            label: label.into(),
            clickable: true,
            ..Self::default()
        }
    }

    /// A drawn label that is read but not activated.
    pub fn text(key: u64, bounds: cranpose_ui_graphics::Rect, label: impl Into<String>) -> Self {
        Self {
            key,
            bounds,
            label: label.into(),
            ..Self::default()
        }
    }

    /// Returns the node with `role` set.
    pub fn with_role(mut self, role: SemanticsWidgetRole) -> Self {
        self.role = Some(role);
        self
    }

    /// Returns the node with the state description `state` set. Compose's `stateDescription`.
    pub fn with_state_description(mut self, state: impl Into<String>) -> Self {
        self.state_description = Some(state.into());
        self
    }

    /// Returns the node with `label` set as the verb phrase for activation. The node becomes
    /// clickable.
    pub fn with_click_label(mut self, label: impl Into<String>) -> Self {
        self.on_click_label = Some(label.into());
        self.clickable = true;
        self
    }

    /// Returns the node with its selected state set to `selected`.
    pub fn with_selected(mut self, selected: bool) -> Self {
        self.selected = Some(selected);
        self
    }

    /// Returns the node with its toggle state set to `toggled`. A `bool` converts to `On` or `Off`.
    pub fn with_toggled(mut self, toggled: impl Into<ToggleableState>) -> Self {
        self.toggled = Some(toggled.into());
        self
    }

    /// Returns the node with `enabled` set. A disabled node is announced as such.
    pub fn with_enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }

    /// Returns the node with `action` added to its custom actions.
    pub fn with_custom_action(mut self, action: SemanticsCustomAction) -> Self {
        self.custom_actions.push(action);
        self
    }
}

/// Semantics configuration for accessibility.
#[derive(Clone, Debug, PartialEq)]
pub struct SemanticsConfiguration {
    /// What a screen reader reads as the name of the node. Compose's `contentDescription`.
    pub content_description: Option<String>,
    /// Compose's `stateDescription`.
    pub state_description: Option<String>,
    /// Compose's `onClick(label = …)`; implies clickable.
    pub on_click_label: Option<String>,
    /// Activation callback for controls whose pointer gesture is handled separately.
    /// Invoked by keyboard and native accessibility activation after validation.
    pub on_click: Option<SemanticsCustomAction>,
    /// What this control does when a screen reader asks for its long press.
    /// Compose's `onLongClick`.
    pub on_long_click: Option<SemanticsLongClick>,
    /// What the long press does, as a verb phrase a reader reads out:
    /// "Remove receipt". Compose's `onLongClick(label = …)`.
    pub on_long_click_label: Option<String>,
    /// What this control does on VoiceOver's magic tap, and on the other
    /// platforms as an action listed by [`Self::on_magic_tap_label`].
    /// SwiftUI's `accessibilityAction(.magicTap)`.
    pub on_magic_tap: Option<SemanticsMagicTap>,
    /// What the magic tap does, as a verb phrase a reader reads out: "Take
    /// the photo".
    pub on_magic_tap_label: Option<String>,
    /// The short names a person says to Voice Control to reach this control,
    /// when the name a reader hears is too long to say. SwiftUI's
    /// `accessibilityInputLabels`; iOS only.
    pub input_labels: Vec<String>,
    /// The language of this control's text as a BCP 47 tag, "de" or "pt-BR",
    /// so a reader picks the right voice for it. SwiftUI's
    /// `accessibilityLanguage`, ARIA's `lang`.
    pub language: Option<String>,
    /// Compose's `Role`.
    pub role: Option<SemanticsWidgetRole>,
    /// Whether the control is selected. `None` means the control has no selected state.
    pub selected: Option<bool>,
    /// Whether the control is on, off or partly on. Compose's
    /// `toggleableState`.
    pub toggled: Option<ToggleableState>,
    /// Whether the control accepts input. A disabled control is announced as such.
    pub enabled: bool,
    /// Whether the control reacts to a click.
    pub is_clickable: bool,
    /// Whether the node is a text field a user edits.
    pub is_editable_text: bool,
    /// Whether an editable field accepts line breaks, independent of its current text.
    pub multiline: bool,
    /// The text an editable field holds, read as its value. Compose's
    /// `editableText`.
    pub text: Option<String>,
    /// The selection or the caret of an editable field, as byte offsets into its text.
    pub text_selection: Option<crate::text::TextRange>,
    /// Named actions that a screen reader lists in its actions menu for the node.
    pub custom_actions: Vec<SemanticsCustomAction>,
    /// Controls this node drew itself instead of laying out. See
    /// [`CanvasSemanticsNode`].
    pub canvas_children: Vec<CanvasSemanticsNode>,
    /// Whether this node takes over the screen: everything outside it is
    /// inert, and a screen reader keeps its traversal inside.
    pub is_modal: bool,
    /// Whether a screen reader skips this node and everything under it: a
    /// decorative image, or a placeholder drawn under a named field. Compose's
    /// `hideFromAccessibility`.
    pub hidden: bool,
    /// Whether a screen reader takes this node and the text under it as one
    /// stop, the way it does for a button: a row whose name, count and price
    /// belong together. Compose's `mergeDescendants`.
    pub merge_descendants: bool,
    /// Whether the selectable controls under this node form one group, so a
    /// screen reader says which of how many a tab or a radio button is.
    /// Compose's `selectableGroup`.
    pub selectable_group: bool,
    /// The title of the screen or pane this node is the root of, read out when
    /// the app moves to it. Compose's `paneTitle`.
    pub pane_title: Option<String>,
    /// Why the control's content is wrong, read after its state: "invalid,
    /// the amount needs a number". Compose's `error`.
    pub error: Option<String>,
    /// What using the control does or what it wants, read after its other
    /// words: "double tap to choose a color". Compose's `hintText`.
    pub hint_text: Option<String>,
    /// Whether this field holds a secret, so screen readers never receive its
    /// text and native editors use protected input. Compose's `password`.
    pub password: bool,
    /// Where a screen reader visits this node among the ones beside it: a
    /// smaller number comes first, and nodes left at zero keep the order the
    /// app laid them out in. Compose's `traversalIndex`.
    pub traversal_index: f32,
    /// A name tests find this node by. Screen readers never receive it.
    /// Compose's `testTag`.
    pub test_tag: Option<String>,
    /// Compose's `liveRegion`. When set, a screen reader reads this node again
    /// whenever its text changes, without the user moving to it.
    pub live_region: Option<LiveRegionMode>,
    /// Compose's `progressBarRangeInfo`. A control with it is adjustable: a
    /// screen reader offers its own way to move the value.
    pub progress: Option<ProgressBarRangeInfo>,
    /// What the control does when a screen reader moves its value. Compose's
    /// `setProgress`.
    pub set_progress: Option<SemanticsSetProgress>,
    /// What this field does when a screen reader or a voice tool hands it
    /// text. Compose's `setText`.
    pub set_text: Option<SemanticsSetText>,
    /// What this field does when a screen reader moves its caret or picks a
    /// stretch of its text. Compose's `setSelection`.
    pub set_selection: Option<SemanticsSetSelection>,
    /// What this control does when a screen reader asks it to open. A control
    /// that says so reads as closed. Compose's `expand`.
    pub expand: Option<SemanticsExpand>,
    /// What this control does when a screen reader asks to send it away: a row
    /// a sighted person swipes off, a sheet a sighted person taps outside of.
    /// Compose's `dismiss`.
    pub dismiss: Option<SemanticsDismiss>,
    /// What this control does when a screen reader asks it to close. A control
    /// that says so reads as open. Compose's `collapse`.
    pub collapse: Option<SemanticsExpand>,
    /// How far this container scrolled up and down. Compose's
    /// `verticalScrollAxisRange`.
    pub vertical_scroll: Option<ScrollAxisRange>,
    /// How far this container scrolled left and right. Compose's
    /// `horizontalScrollAxisRange`.
    pub horizontal_scroll: Option<ScrollAxisRange>,
    /// What this container does when a screen reader pages it. Compose's
    /// `scrollBy`.
    pub scroll_by: Option<SemanticsScrollBy>,
    /// What this list does when a screen reader asks for the row at an index,
    /// so a reader reaches row 300 without paging to it. Compose's
    /// `scrollToIndex`.
    pub scroll_to_index: Option<SemanticsScrollToIndex>,
    /// How many rows and columns this list holds. Compose's `collectionInfo`.
    pub collection: Option<CollectionInfo>,
}

impl Default for SemanticsConfiguration {
    fn default() -> Self {
        Self {
            content_description: None,
            state_description: None,
            on_click_label: None,
            on_click: None,
            on_long_click: None,
            on_long_click_label: None,
            on_magic_tap: None,
            on_magic_tap_label: None,
            input_labels: Vec::new(),
            language: None,
            role: None,
            selected: None,
            toggled: None,
            enabled: true,
            is_clickable: false,
            is_editable_text: false,
            multiline: false,
            text: None,
            text_selection: None,
            custom_actions: Vec::new(),
            canvas_children: Vec::new(),
            is_modal: false,
            hidden: false,
            merge_descendants: false,
            selectable_group: false,
            pane_title: None,
            error: None,
            hint_text: None,
            password: false,
            traversal_index: 0.0,
            test_tag: None,
            live_region: None,
            progress: None,
            set_progress: None,
            set_text: None,
            set_selection: None,
            expand: None,
            dismiss: None,
            collapse: None,
            vertical_scroll: None,
            horizontal_scroll: None,
            scroll_by: None,
            scroll_to_index: None,
            collection: None,
        }
    }
}

/// One value that says what a screen reader reads for a node, built up with
/// the methods below and handed to `Modifier::semantics_spec`.
///
/// Compose has no such value: it takes a receiver lambda, which Kotlin makes
/// read well and Rust has no match for. `SemanticsSpec::new().content_description("Save")`
/// reads better than `|config| config.content_description = Some("Save".into())`,
/// it is one chain element rather than one per property, and two specs can be
/// compared. The closure form stays as `Modifier::semantics` for parity.
pub type SemanticsSpec = SemanticsConfiguration;

impl SemanticsConfiguration {
    /// An empty spec to build on. Every field is what it is with no semantics
    /// declared at all.
    pub fn new() -> Self {
        Self::default()
    }

    /// The name a screen reader reads for the control. Compose's
    /// `contentDescription`.
    pub fn content_description(mut self, name: impl Into<String>) -> Self {
        self.content_description = Some(name.into());
        self
    }

    /// A name tests find this node by. Screen readers never receive it.
    /// Compose's `testTag`.
    pub fn test_tag(mut self, tag: impl Into<String>) -> Self {
        self.test_tag = Some(tag.into());
        self
    }

    /// What the control says about itself after its name. Compose's
    /// `stateDescription`.
    pub fn state_description(mut self, state: impl Into<String>) -> Self {
        self.state_description = Some(state.into());
        self
    }

    /// A screen reader offers to activate the control. Compose's `onClick`.
    pub fn clickable(mut self) -> Self {
        self.is_clickable = true;
        self
    }

    /// Handles keyboard and screen-reader activation without adding a pointer gesture.
    /// An empty label uses the platform's default activation instruction.
    pub fn on_click(mut self, label: impl Into<String>, action: impl Fn() + 'static) -> Self {
        self.on_click = Some(SemanticsCustomAction::new(label, action));
        self
    }

    /// What the control does when a screen reader asks for its long press,
    /// and the verb phrase a reader reads out for it. Compose's
    /// `onLongClick(label) { … }`.
    pub fn on_long_click(
        mut self,
        label: impl Into<String>,
        action: impl Fn() -> bool + 'static,
    ) -> Self {
        self.on_long_click_label = Some(label.into());
        self.on_long_click = Some(SemanticsLongClick::new(action));
        self
    }

    /// What the control does on VoiceOver's magic tap, and the verb phrase
    /// the other platforms list it under. SwiftUI's
    /// `accessibilityAction(.magicTap)`.
    pub fn on_magic_tap(
        mut self,
        label: impl Into<String>,
        action: impl Fn() -> bool + 'static,
    ) -> Self {
        self.on_magic_tap_label = Some(label.into());
        self.on_magic_tap = Some(SemanticsMagicTap::new(action));
        self
    }

    /// The short names a person says to Voice Control to reach the control.
    /// SwiftUI's `accessibilityInputLabels`.
    pub fn input_labels<S: Into<String>>(mut self, labels: impl IntoIterator<Item = S>) -> Self {
        self.input_labels = labels.into_iter().map(Into::into).collect();
        self
    }

    /// The language of the control's text, as a BCP 47 tag. SwiftUI's
    /// `accessibilityLanguage`, ARIA's `lang`.
    pub fn language(mut self, tag: impl Into<String>) -> Self {
        self.language = Some(tag.into());
        self
    }

    /// Whether the control is on, off or partly on. Compose's
    /// `toggleableState`; a `bool` is on or off.
    pub fn toggled(mut self, toggled: impl Into<ToggleableState>) -> Self {
        self.toggled = Some(toggled.into());
        self
    }

    /// Whether the control is the one picked out of a group. Compose's
    /// `selected`.
    pub fn selected(mut self, selected: bool) -> Self {
        self.selected = Some(selected);
        self
    }

    /// What kind of control a screen reader reads this as. Compose's `Role`.
    pub fn role(mut self, role: SemanticsWidgetRole) -> Self {
        self.role = Some(role);
        self
    }

    /// Reads as a heading, so a reader can jump between the headings of a
    /// screen. Compose's `heading()`.
    pub fn heading(self) -> Self {
        self.role(SemanticsWidgetRole::Header)
    }

    /// Why the control's content is wrong. Compose's `error`.
    pub fn error(mut self, message: impl Into<String>) -> Self {
        self.error = Some(message.into());
        self
    }

    /// What using the control does or what it wants. Compose's `hintText`.
    pub fn hint_text(mut self, hint: impl Into<String>) -> Self {
        self.hint_text = Some(hint.into());
        self
    }

    /// Holds a secret, so no reader reads the text out. Compose's `password`.
    pub fn password(mut self) -> Self {
        self.password = true;
        self
    }

    /// Names the screen or pane this node is the root of. Compose's
    /// `paneTitle`.
    pub fn pane_title(mut self, title: impl Into<String>) -> Self {
        self.pane_title = Some(title.into());
        self
    }

    /// Where a reader visits this node among the ones beside it. Compose's
    /// `traversalIndex`.
    pub fn traversal_index(mut self, index: f32) -> Self {
        self.traversal_index = index;
        self
    }

    /// Skips this node and everything under it. Compose's
    /// `hideFromAccessibility`.
    pub fn hidden(mut self) -> Self {
        self.hidden = true;
        self
    }

    /// Takes this node and the text under it as one stop. Compose's
    /// `mergeDescendants`.
    pub fn merge_descendants(mut self) -> Self {
        self.merge_descendants = true;
        self
    }

    /// Makes the selectable controls under this node one group. Compose's
    /// `selectableGroup`.
    pub fn selectable_group(mut self) -> Self {
        self.selectable_group = true;
        self
    }

    /// Reads this node again whenever its text changes. Compose's
    /// `liveRegion`.
    pub fn live_region(mut self, mode: LiveRegionMode) -> Self {
        self.live_region = Some(mode);
        self
    }
    /// Folds `other` into this configuration. A value that `other` sets replaces the value here.
    /// `enabled` stays true only when both are enabled, the boolean flags turn true when either is
    /// true, and the lists are appended.
    pub fn merge(&mut self, other: &Self) {
        if let Some(description) = &other.content_description {
            self.content_description = Some(description.clone());
        }
        if let Some(state) = &other.state_description {
            self.state_description = Some(state.clone());
        }
        if let Some(label) = &other.on_click_label {
            self.on_click_label = Some(label.clone());
        }
        if let Some(label) = &other.on_long_click_label {
            self.on_long_click_label = Some(label.clone());
        }
        if let Some(label) = &other.on_magic_tap_label {
            self.on_magic_tap_label = Some(label.clone());
        }
        if !other.input_labels.is_empty() {
            self.input_labels.clone_from(&other.input_labels);
        }
        if let Some(language) = &other.language {
            self.language = Some(language.clone());
        }
        if let Some(role) = other.role {
            self.role = Some(role);
        }
        if let Some(selected) = other.selected {
            self.selected = Some(selected);
        }
        if let Some(toggled) = other.toggled {
            self.toggled = Some(toggled);
        }
        self.enabled &= other.enabled;
        self.is_clickable |= other.is_clickable;
        self.is_editable_text |= other.is_editable_text;
        self.multiline |= other.multiline;
        if let Some(text) = &other.text {
            self.text = Some(text.clone());
        }
        self.is_modal |= other.is_modal;
        self.hidden |= other.hidden;
        self.merge_descendants |= other.merge_descendants;
        self.selectable_group |= other.selectable_group;
        self.password |= other.password;
        if other.traversal_index != 0.0 {
            self.traversal_index = other.traversal_index;
        }
        if let Some(live_region) = other.live_region {
            self.live_region = Some(live_region);
        }
        self.merge_words(other);
        self.merge_actions(other);
        self.merge_ranges(other);
    }

    fn merge_words(&mut self, other: &Self) {
        if let Some(title) = &other.pane_title {
            self.pane_title = Some(title.clone());
        }
        if let Some(error) = &other.error {
            self.error = Some(error.clone());
        }
        if let Some(hint) = &other.hint_text {
            self.hint_text = Some(hint.clone());
        }
        if let Some(tag) = &other.test_tag {
            self.test_tag = Some(tag.clone());
        }
    }

    fn merge_actions(&mut self, other: &Self) {
        if let Some(on_click) = &other.on_click {
            self.on_click = Some(on_click.clone());
        }
        self.custom_actions
            .extend(other.custom_actions.iter().cloned());
        self.canvas_children
            .extend(other.canvas_children.iter().cloned());
        if let Some(set_progress) = &other.set_progress {
            self.set_progress = Some(set_progress.clone());
        }
        if let Some(set_text) = &other.set_text {
            self.set_text = Some(set_text.clone());
        }
        if let Some(set_selection) = &other.set_selection {
            self.set_selection = Some(set_selection.clone());
        }
        if let Some(expand) = &other.expand {
            self.expand = Some(expand.clone());
        }
        if let Some(collapse) = &other.collapse {
            self.collapse = Some(collapse.clone());
        }
        if let Some(dismiss) = &other.dismiss {
            self.dismiss = Some(dismiss.clone());
        }
        if let Some(long_click) = &other.on_long_click {
            self.on_long_click = Some(long_click.clone());
        }
        if let Some(magic_tap) = &other.on_magic_tap {
            self.on_magic_tap = Some(magic_tap.clone());
        }
        if let Some(scroll_by) = &other.scroll_by {
            self.scroll_by = Some(scroll_by.clone());
        }
        if let Some(scroll_to_index) = &other.scroll_to_index {
            self.scroll_to_index = Some(scroll_to_index.clone());
        }
    }

    fn merge_ranges(&mut self, other: &Self) {
        if let Some(selection) = other.text_selection {
            self.text_selection = Some(selection);
        }
        if let Some(progress) = other.progress {
            self.progress = Some(progress);
        }
        if let Some(range) = other.vertical_scroll {
            self.vertical_scroll = Some(range);
        }
        if let Some(range) = other.horizontal_scroll {
            self.horizontal_scroll = Some(range);
        }
        if let Some(collection) = other.collection {
            self.collection = Some(collection);
        }
    }

    /// Whether a screen reader should offer activation. A named click label is
    /// how Compose declares `onClick`, so it implies the action the same way.
    pub fn is_activatable(&self) -> bool {
        self.is_clickable || self.on_click_label.is_some() || self.on_click.is_some()
    }
}

impl fmt::Debug for dyn ModifierNode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ModifierNode").finish_non_exhaustive()
    }
}

impl dyn ModifierNode {
    /// Returns the node as `Any`, for downcasting to its concrete type.
    pub fn as_any(&self) -> &dyn Any {
        self
    }

    /// Returns the node as mutable `Any`, for downcasting to its concrete type.
    pub fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }
}

/// Strongly typed modifier elements that can create and update nodes while
/// exposing equality/hash/inspector contracts that mirror Jetpack Compose.
pub trait ModifierNodeElement: fmt::Debug + Hash + PartialEq + 'static {
    /// The type of node that the element creates and updates.
    type Node: ModifierNode;

    /// Creates a new modifier node instance for this element.
    fn create(&self) -> Self::Node;

    /// Brings an existing modifier node up to date with the element's data.
    fn update(&self, node: &mut Self::Node);

    /// Optional key used to disambiguate multiple instances of the same element type.
    fn key(&self) -> Option<u64> {
        None
    }

    /// Human readable name surfaced to inspector tooling.
    fn inspector_name(&self) -> &'static str {
        type_name::<Self>()
    }

    /// Records inspector properties for tooling.
    fn inspector_properties(&self, _inspector: &mut dyn FnMut(&'static str, String)) {}

    /// Returns the capabilities of nodes created by this element.
    /// Override this to indicate which specialized traits the node implements.
    fn capabilities(&self) -> NodeCapabilities {
        NodeCapabilities::default()
    }

    /// Whether this element requires `update` to be called even if `eq` returns true.
    ///
    /// This is useful for elements that ignore certain fields in `eq` (e.g. closures)
    /// to allow node reuse, but still need those fields updated in the existing node.
    /// Defaults to `false`.
    fn always_update(&self) -> bool {
        false
    }

    /// Whether modifier reconciliation should request capability-wide invalidations
    /// after updating an existing node.
    fn auto_invalidate_on_update(&self) -> bool {
        true
    }

    /// Optional targeted invalidation requested after updating an existing node.
    ///
    /// This is for nodes whose attach/remove capability is broader than the
    /// work needed for a value-only update. For example, an offset node
    /// participates in layout on attach but an x/y change only needs placement
    /// data and draw output refreshed.
    fn update_invalidation_kind(&self) -> Option<InvalidationKind> {
        None
    }

    /// Composition locals this element hands to the content composed inside
    /// the node it decorates.
    ///
    /// A modifier that stands for something its subtree lives in, the way a
    /// window does, passes that thing down here instead of asking every
    /// composable in between to carry it as an argument.
    fn provided_composition_locals(&self) -> Vec<ProvidedValue> {
        Vec::new()
    }
}

/// Capability flags indicating which specialized traits a modifier node implements.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct NodeCapabilities(u32);

impl NodeCapabilities {
    /// No capabilities.
    pub const NONE: Self = Self(0);
    /// Modifier participates in measure/layout.
    pub const LAYOUT: Self = Self(1 << 0);
    /// Modifier participates in draw.
    pub const DRAW: Self = Self(1 << 1);
    /// Modifier participates in pointer input.
    pub const POINTER_INPUT: Self = Self(1 << 2);
    /// Modifier participates in semantics tree construction.
    pub const SEMANTICS: Self = Self(1 << 3);
    /// Modifier participates in modifier locals.
    pub const MODIFIER_LOCALS: Self = Self(1 << 4);
    /// Modifier participates in focus management.
    pub const FOCUS: Self = Self(1 << 5);
    /// Modifier makes its node the root of a separate window: the node's
    /// subtree is laid out into that window's size and drawn into that
    /// window's scene, and the parent's scene skips it.
    pub const WINDOW_ROOT: Self = Self(1 << 6);
    /// Modifier handles hardware keyboard events.
    pub const KEY_INPUT: Self = Self(1 << 7);

    /// Returns an empty capability set.
    pub const fn empty() -> Self {
        Self::NONE
    }

    /// Returns whether all bits in `other` are present in `self`.
    pub const fn contains(self, other: Self) -> bool {
        (self.0 & other.0) == other.0
    }

    /// Returns whether any bit in `other` is present in `self`.
    pub const fn intersects(self, other: Self) -> bool {
        (self.0 & other.0) != 0
    }

    /// Inserts the requested capability bits.
    pub fn insert(&mut self, other: Self) {
        self.0 |= other.0;
    }

    /// Returns the raw bit representation.
    pub const fn bits(self) -> u32 {
        self.0
    }

    /// Returns true when no capabilities are set.
    pub const fn is_empty(self) -> bool {
        self.0 == 0
    }

    /// Returns the capability bit mask required for the given invalidation.
    pub const fn for_invalidation(kind: InvalidationKind) -> Self {
        match kind {
            InvalidationKind::Layout => Self::LAYOUT,
            InvalidationKind::Draw => Self::DRAW,
            InvalidationKind::PointerInput => Self::POINTER_INPUT,
            InvalidationKind::Semantics => Self::SEMANTICS,
            InvalidationKind::Focus => Self::FOCUS,
        }
    }
}

impl Default for NodeCapabilities {
    fn default() -> Self {
        Self::NONE
    }
}

impl fmt::Debug for NodeCapabilities {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("NodeCapabilities")
            .field("layout", &self.contains(Self::LAYOUT))
            .field("draw", &self.contains(Self::DRAW))
            .field("pointer_input", &self.contains(Self::POINTER_INPUT))
            .field("semantics", &self.contains(Self::SEMANTICS))
            .field("modifier_locals", &self.contains(Self::MODIFIER_LOCALS))
            .field("focus", &self.contains(Self::FOCUS))
            .field("window_root", &self.contains(Self::WINDOW_ROOT))
            .field("key_input", &self.contains(Self::KEY_INPUT))
            .finish()
    }
}

impl BitOr for NodeCapabilities {
    type Output = Self;

    fn bitor(self, rhs: Self) -> Self::Output {
        Self(self.0 | rhs.0)
    }
}

impl BitOrAssign for NodeCapabilities {
    fn bitor_assign(&mut self, rhs: Self) {
        self.0 |= rhs.0;
    }
}

/// The invalidations a node's modifier update requested: at most one per
/// [`InvalidationKind`], held inline so handing them over allocates nothing.
pub type ModifierInvalidations = smallvec::SmallVec<[ModifierInvalidation; 5]>;

/// Records an invalidation request together with the capability mask that triggered it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ModifierInvalidation {
    kind: InvalidationKind,
    capabilities: NodeCapabilities,
}

impl ModifierInvalidation {
    /// Creates a new modifier invalidation entry.
    pub const fn new(kind: InvalidationKind, capabilities: NodeCapabilities) -> Self {
        Self { kind, capabilities }
    }

    /// Returns the invalidated pipeline kind.
    pub const fn kind(self) -> InvalidationKind {
        self.kind
    }

    /// Returns the capability mask associated with the invalidation.
    pub const fn capabilities(self) -> NodeCapabilities {
        self.capabilities
    }
}

/// Type-erased modifier element used by the runtime to reconcile chains.
pub trait AnyModifierElement: fmt::Debug {
    /// The type of node that the element creates.
    fn node_type(&self) -> TypeId;

    /// The type of the element itself.
    fn element_type(&self) -> TypeId;

    /// A new node for this element, in the shared cell its chain entry keeps.
    fn create_node(&self) -> Rc<RefCell<dyn ModifierNode>>;

    /// Whether `node` is of the type that this element updates.
    fn can_update_node(&self, node: &dyn ModifierNode) -> bool;

    /// Brings `node` up to date with the data of this element.
    fn update_node(&self, node: &mut dyn ModifierNode);

    /// The key that tells apart several elements of one type, or `None` when the element has none.
    fn key(&self) -> Option<u64>;

    /// The capabilities of the nodes that the element creates.
    fn capabilities(&self) -> NodeCapabilities {
        NodeCapabilities::default()
    }

    /// The hash of the element, computed once when the element was wrapped.
    fn hash_code(&self) -> u64;

    /// Whether `other` is an element of the same type with equal data.
    fn equals_element(&self, other: &dyn AnyModifierElement) -> bool;

    /// The name that inspector tooling shows for the element.
    fn inspector_name(&self) -> &'static str;

    /// Reports each inspector property of the element to `visitor` as a name and a value.
    fn record_inspector_properties(&self, visitor: &mut dyn FnMut(&'static str, String));

    /// Whether the node must be updated even when the new element equals the old one.
    fn requires_update(&self) -> bool;

    /// Whether updating an existing node invalidates all pipeline stages that its capabilities
    /// cover.
    fn auto_invalidates_on_update(&self) -> bool;

    /// The one pipeline stage that an update invalidates, or `None` to invalidate by capabilities.
    fn update_invalidation_kind(&self) -> Option<InvalidationKind>;

    /// Whether this element has composition locals for its content.
    fn provides_composition_locals(&self) -> bool {
        false
    }

    /// The composition locals this element hands to its content.
    fn provided_composition_locals(&self) -> Vec<ProvidedValue> {
        Vec::new()
    }

    /// Returns the element as `Any`, for downcasting to its concrete type.
    fn as_any(&self) -> &dyn Any;
}

struct TypedModifierElement<E: ModifierNodeElement> {
    element: E,
    /// The element's hash, worked out the first time a chain rebuilding
    /// asks for it: most elements are built for a recomposition and only
    /// compared with the last ones.
    hash: Cell<Option<PackedU64>>,
    provides_locals: bool,
}

impl<E: ModifierNodeElement> TypedModifierElement<E> {
    fn new(element: E) -> Self {
        let provides_locals = !element.provided_composition_locals().is_empty();
        Self {
            element,
            hash: Cell::new(None),
            provides_locals,
        }
    }
}

impl<E> fmt::Debug for TypedModifierElement<E>
where
    E: ModifierNodeElement,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TypedModifierElement")
            .field("type", &type_name::<E>())
            .finish()
    }
}

impl<E> AnyModifierElement for TypedModifierElement<E>
where
    E: ModifierNodeElement,
{
    fn node_type(&self) -> TypeId {
        TypeId::of::<E::Node>()
    }

    fn element_type(&self) -> TypeId {
        TypeId::of::<E>()
    }

    fn create_node(&self) -> Rc<RefCell<dyn ModifierNode>> {
        Rc::new(RefCell::new(self.element.create()))
    }

    fn can_update_node(&self, node: &dyn ModifierNode) -> bool {
        node.as_any().is::<E::Node>()
    }

    fn update_node(&self, node: &mut dyn ModifierNode) {
        if let Some(typed) = node.as_any_mut().downcast_mut::<E::Node>() {
            self.element.update(typed);
        }
    }

    fn key(&self) -> Option<u64> {
        self.element.key()
    }

    fn capabilities(&self) -> NodeCapabilities {
        self.element.capabilities()
    }

    fn provides_composition_locals(&self) -> bool {
        self.provides_locals
    }

    fn provided_composition_locals(&self) -> Vec<ProvidedValue> {
        self.element.provided_composition_locals()
    }

    fn hash_code(&self) -> u64 {
        if let Some(hash) = self.hash.get() {
            return hash.get();
        }
        let mut hasher = default::new();
        self.element.hash(&mut hasher);
        let hash = hasher.finish();
        self.hash.set(Some(PackedU64::new(hash)));
        hash
    }

    fn equals_element(&self, other: &dyn AnyModifierElement) -> bool {
        other
            .as_any()
            .downcast_ref::<Self>()
            .is_some_and(|typed| typed.element == self.element)
    }

    fn inspector_name(&self) -> &'static str {
        self.element.inspector_name()
    }

    fn record_inspector_properties(&self, visitor: &mut dyn FnMut(&'static str, String)) {
        self.element.inspector_properties(visitor);
    }

    fn requires_update(&self) -> bool {
        self.element.always_update()
    }

    fn auto_invalidates_on_update(&self) -> bool {
        self.element.auto_invalidate_on_update()
    }

    fn update_invalidation_kind(&self) -> Option<InvalidationKind> {
        self.element.update_invalidation_kind()
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// Convenience helper for callers to construct a type-erased modifier
/// element without having to mention the internal wrapper type.
pub fn modifier_element<E: ModifierNodeElement>(element: E) -> DynModifierElement {
    Rc::new(TypedModifierElement::new(element))
}

/// Boxed type-erased modifier element.
pub type DynModifierElement = Rc<dyn AnyModifierElement>;

#[cfg(test)]
#[path = "tests/modifier_tests.rs"]
mod tests;